From 34daa0f4478a15a2536d3c4f568100119bb7e1e1 Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Wed, 3 Jun 2026 23:26:50 +0000 Subject: [PATCH] Add 8 ocr net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: ocr-configuration, ocr-optimization, skew-angle-calculation, text-recognition Source: AI Search API Tutorials: - Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images - Perform OCR on Image with Aspose OCR – Hindi Guide - Perform OCR on PDF with Aspose.OCR – Complete C# Guide - How to Use Aspose: Convert Image to HTML with OCR - OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# - Perform OCR on Image and Detect Misspelled Words in C# - Video Subtitle OCR in C# – Complete Guide - Get Aspose OCR Version in C# – Complete Guide Auto-generated by Professionalize.Tutorials Agent --- ocr/arabic/net/ocr-configuration/_index.md | 4 +- .../_index.md | 294 +++++++++++++++++ ocr/arabic/net/ocr-optimization/_index.md | 2 + .../_index.md | 284 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 5 +- .../_index.md | 275 ++++++++++++++++ ocr/arabic/net/text-recognition/_index.md | 13 +- .../_index.md | 275 ++++++++++++++++ .../_index.md | 243 ++++++++++++++ .../_index.md | 271 ++++++++++++++++ .../_index.md | 282 ++++++++++++++++ .../_index.md | 280 ++++++++++++++++ ocr/chinese/net/ocr-configuration/_index.md | 5 +- .../_index.md | 292 +++++++++++++++++ ocr/chinese/net/ocr-optimization/_index.md | 3 + .../_index.md | 282 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 270 ++++++++++++++++ ocr/chinese/net/text-recognition/_index.md | 13 +- .../_index.md | 273 ++++++++++++++++ .../_index.md | 239 ++++++++++++++ .../_index.md | 269 +++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 277 ++++++++++++++++ ocr/czech/net/ocr-configuration/_index.md | 4 +- .../_index.md | 280 ++++++++++++++++ ocr/czech/net/ocr-optimization/_index.md | 2 + .../_index.md | 287 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 271 ++++++++++++++++ ocr/czech/net/text-recognition/_index.md | 13 +- .../_index.md | 275 ++++++++++++++++ .../_index.md | 239 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/dutch/net/ocr-configuration/_index.md | 4 +- .../_index.md | 280 ++++++++++++++++ ocr/dutch/net/ocr-optimization/_index.md | 2 + .../_index.md | 287 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 271 ++++++++++++++++ ocr/dutch/net/text-recognition/_index.md | 13 +- .../_index.md | 279 ++++++++++++++++ .../_index.md | 243 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/english/net/ocr-configuration/_index.md | 4 +- .../_index.md | 294 +++++++++++++++++ ocr/english/net/ocr-optimization/_index.md | 4 +- .../_index.md | 286 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 5 +- .../_index.md | 276 ++++++++++++++++ ocr/english/net/text-recognition/_index.md | 13 +- .../_index.md | 279 ++++++++++++++++ .../_index.md | 243 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 281 ++++++++++++++++ ocr/french/net/ocr-configuration/_index.md | 5 +- .../_index.md | 282 ++++++++++++++++ ocr/french/net/ocr-optimization/_index.md | 2 + .../_index.md | 288 +++++++++++++++++ .../net/skew-angle-calculation/_index.md | 7 +- .../_index.md | 279 ++++++++++++++++ ocr/french/net/text-recognition/_index.md | 13 +- .../_index.md | 281 ++++++++++++++++ .../_index.md | 247 ++++++++++++++ .../_index.md | 275 ++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 280 ++++++++++++++++ ocr/german/net/ocr-configuration/_index.md | 4 +- .../_index.md | 280 ++++++++++++++++ ocr/german/net/ocr-optimization/_index.md | 4 +- .../_index.md | 287 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 272 ++++++++++++++++ ocr/german/net/text-recognition/_index.md | 19 +- .../_index.md | 281 ++++++++++++++++ .../_index.md | 242 ++++++++++++++ .../_index.md | 272 ++++++++++++++++ .../_index.md | 306 ++++++++++++++++++ .../_index.md | 282 ++++++++++++++++ ocr/greek/net/ocr-configuration/_index.md | 4 +- .../_index.md | 293 +++++++++++++++++ ocr/greek/net/ocr-optimization/_index.md | 2 + .../_index.md | 287 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 6 +- .../_index.md | 273 ++++++++++++++++ ocr/greek/net/text-recognition/_index.md | 14 +- .../_index.md | 279 ++++++++++++++++ .../_index.md | 241 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 275 ++++++++++++++++ ocr/hindi/net/ocr-configuration/_index.md | 4 +- .../_index.md | 294 +++++++++++++++++ ocr/hindi/net/ocr-optimization/_index.md | 3 + .../_index.md | 286 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 6 +- .../_index.md | 272 ++++++++++++++++ ocr/hindi/net/text-recognition/_index.md | 19 +- .../_index.md | 276 ++++++++++++++++ .../_index.md | 241 ++++++++++++++ .../_index.md | 271 ++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/hongkong/net/ocr-configuration/_index.md | 4 +- .../_index.md | 292 +++++++++++++++++ ocr/hongkong/net/ocr-optimization/_index.md | 2 + .../_index.md | 282 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 5 +- .../_index.md | 272 ++++++++++++++++ ocr/hongkong/net/text-recognition/_index.md | 12 +- .../_index.md | 276 ++++++++++++++++ .../_index.md | 239 ++++++++++++++ .../_index.md | 267 +++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 277 ++++++++++++++++ ocr/hungarian/net/ocr-configuration/_index.md | 6 +- .../_index.md | 288 +++++++++++++++++ ocr/hungarian/net/ocr-optimization/_index.md | 3 + .../_index.md | 287 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 280 ++++++++++++++++ ocr/hungarian/net/text-recognition/_index.md | 13 +- .../_index.md | 270 ++++++++++++++++ .../_index.md | 245 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 299 +++++++++++++++++ .../_index.md | 281 ++++++++++++++++ .../net/ocr-configuration/_index.md | 8 +- .../_index.md | 281 ++++++++++++++++ ocr/indonesian/net/ocr-optimization/_index.md | 2 + .../_index.md | 285 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 269 +++++++++++++++ ocr/indonesian/net/text-recognition/_index.md | 13 +- .../_index.md | 279 ++++++++++++++++ .../_index.md | 242 ++++++++++++++ .../_index.md | 274 ++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/italian/net/ocr-configuration/_index.md | 4 +- .../_index.md | 293 +++++++++++++++++ ocr/italian/net/ocr-optimization/_index.md | 4 +- .../_index.md | 288 +++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 277 ++++++++++++++++ ocr/italian/net/text-recognition/_index.md | 13 +- .../_index.md | 277 ++++++++++++++++ .../_index.md | 242 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 300 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/japanese/net/ocr-configuration/_index.md | 4 +- .../_index.md | 292 +++++++++++++++++ ocr/japanese/net/ocr-optimization/_index.md | 2 + .../_index.md | 282 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 262 +++++++++++++++ ocr/japanese/net/text-recognition/_index.md | 17 +- .../_index.md | 275 ++++++++++++++++ .../_index.md | 239 ++++++++++++++ .../_index.md | 270 ++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 278 ++++++++++++++++ ocr/korean/net/ocr-configuration/_index.md | 6 +- .../_index.md | 292 +++++++++++++++++ ocr/korean/net/ocr-optimization/_index.md | 4 +- .../_index.md | 284 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 268 +++++++++++++++ ocr/korean/net/text-recognition/_index.md | 14 +- .../_index.md | 277 ++++++++++++++++ .../_index.md | 239 ++++++++++++++ .../_index.md | 269 +++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/polish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 292 +++++++++++++++++ ocr/polish/net/ocr-optimization/_index.md | 3 + .../_index.md | 286 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 277 ++++++++++++++++ ocr/polish/net/text-recognition/_index.md | 15 +- .../_index.md | 263 +++++++++++++++ .../_index.md | 243 ++++++++++++++ .../_index.md | 271 ++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ .../net/ocr-configuration/_index.md | 4 +- .../_index.md | 292 +++++++++++++++++ ocr/portuguese/net/ocr-optimization/_index.md | 4 +- .../_index.md | 288 +++++++++++++++++ .../net/skew-angle-calculation/_index.md | 5 +- .../_index.md | 274 ++++++++++++++++ ocr/portuguese/net/text-recognition/_index.md | 13 +- .../_index.md | 275 ++++++++++++++++ .../_index.md | 243 ++++++++++++++ .../_index.md | 271 ++++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/russian/net/ocr-configuration/_index.md | 6 +- .../_index.md | 280 ++++++++++++++++ ocr/russian/net/ocr-optimization/_index.md | 3 + .../_index.md | 288 +++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 271 ++++++++++++++++ ocr/russian/net/text-recognition/_index.md | 13 +- .../_index.md | 281 ++++++++++++++++ .../_index.md | 241 ++++++++++++++ .../_index.md | 272 ++++++++++++++++ .../_index.md | 280 ++++++++++++++++ .../_index.md | 277 ++++++++++++++++ ocr/spanish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 293 +++++++++++++++++ ocr/spanish/net/ocr-optimization/_index.md | 2 + .../_index.md | 286 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 278 ++++++++++++++++ ocr/spanish/net/text-recognition/_index.md | 29 +- .../_index.md | 276 ++++++++++++++++ .../_index.md | 242 ++++++++++++++ .../_index.md | 272 ++++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/swedish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 292 +++++++++++++++++ ocr/swedish/net/ocr-optimization/_index.md | 2 + .../_index.md | 284 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 11 +- .../_index.md | 271 ++++++++++++++++ ocr/swedish/net/text-recognition/_index.md | 13 +- .../_index.md | 279 ++++++++++++++++ .../_index.md | 243 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 279 ++++++++++++++++ .../_index.md | 277 ++++++++++++++++ ocr/thai/net/ocr-configuration/_index.md | 5 +- .../_index.md | 292 +++++++++++++++++ ocr/thai/net/ocr-optimization/_index.md | 3 + .../_index.md | 284 ++++++++++++++++ ocr/thai/net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 270 ++++++++++++++++ ocr/thai/net/text-recognition/_index.md | 13 +- .../_index.md | 275 ++++++++++++++++ .../_index.md | 241 ++++++++++++++ .../_index.md | 271 ++++++++++++++++ .../_index.md | 301 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ ocr/turkish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 292 +++++++++++++++++ ocr/turkish/net/ocr-optimization/_index.md | 2 + .../_index.md | 287 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 4 +- .../_index.md | 267 +++++++++++++++ ocr/turkish/net/text-recognition/_index.md | 12 +- .../_index.md | 279 ++++++++++++++++ .../_index.md | 241 ++++++++++++++ .../_index.md | 272 ++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 279 ++++++++++++++++ .../net/ocr-configuration/_index.md | 4 +- .../_index.md | 293 +++++++++++++++++ ocr/vietnamese/net/ocr-optimization/_index.md | 2 + .../_index.md | 284 ++++++++++++++++ .../net/skew-angle-calculation/_index.md | 5 +- .../_index.md | 268 +++++++++++++++ ocr/vietnamese/net/text-recognition/_index.md | 13 +- .../_index.md | 280 ++++++++++++++++ .../_index.md | 242 ++++++++++++++ .../_index.md | 273 ++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 277 ++++++++++++++++ 276 files changed, 51487 insertions(+), 96 deletions(-) create mode 100644 ocr/arabic/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/arabic/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/arabic/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/arabic/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/arabic/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/arabic/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/arabic/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/arabic/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/chinese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/chinese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/chinese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/chinese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/chinese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/chinese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/chinese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/chinese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/czech/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/czech/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/czech/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/czech/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/czech/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/czech/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/czech/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/czech/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/dutch/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/dutch/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/dutch/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/dutch/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/dutch/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/dutch/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/dutch/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/dutch/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/english/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/english/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/english/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/english/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/english/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/english/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/english/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/english/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/french/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/french/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/french/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/french/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/french/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/french/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/french/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/french/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/german/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/german/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/german/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/german/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/german/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/german/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/german/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/german/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/greek/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/greek/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/greek/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/greek/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/greek/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/greek/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/greek/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/greek/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/hindi/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/hindi/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/hindi/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/hindi/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/hindi/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/hindi/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/hindi/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/hindi/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/hongkong/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/hongkong/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/hongkong/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/hongkong/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/hongkong/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/hongkong/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/hongkong/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/hongkong/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/hungarian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/hungarian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/hungarian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/hungarian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/hungarian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/hungarian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/hungarian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/hungarian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/indonesian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/indonesian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/indonesian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/indonesian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/indonesian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/indonesian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/indonesian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/indonesian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/italian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/italian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/italian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/italian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/italian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/italian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/italian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/italian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/japanese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/japanese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/japanese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/japanese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/japanese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/japanese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/japanese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/japanese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/korean/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/korean/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/korean/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/korean/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/korean/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/korean/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/korean/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/korean/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/polish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/polish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/polish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/polish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/polish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/polish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/polish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/polish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/portuguese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/portuguese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/portuguese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/portuguese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/portuguese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/portuguese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/portuguese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/portuguese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/russian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/russian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/russian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/russian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/russian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/russian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/russian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/russian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/spanish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/spanish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/spanish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/spanish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/spanish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/spanish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/spanish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/spanish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/swedish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/swedish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/swedish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/swedish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/swedish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/swedish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/swedish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/swedish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/thai/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/thai/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/thai/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/thai/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/thai/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/thai/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/thai/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/thai/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/turkish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/turkish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/turkish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/turkish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/turkish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/turkish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/turkish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/turkish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md create mode 100644 ocr/vietnamese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md create mode 100644 ocr/vietnamese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md create mode 100644 ocr/vietnamese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md diff --git a/ocr/arabic/net/ocr-configuration/_index.md b/ocr/arabic/net/ocr-configuration/_index.md index 64743e9bd..13dd2b344 100644 --- a/ocr/arabic/net/ocr-configuration/_index.md +++ b/ocr/arabic/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ weight: 24 استفد من قدرات OCR القوية مع Aspose.OCR for .NET. استخراج النص من الصور بسلاسة. ### [OCROperation مع القائمة في التعرف على الصور باستخدام OCR](./ocr-operation-with-list/) اكتشف إمكانات Aspose.OCR for .NET. تنفيذ التعرف على الصور باستخدام OCR مع القوائم بسهولة. عزّز الإنتاجية واستخراج البيانات في تطبيقاتك. +### [الحصول على إصدار Aspose OCR في C# – دليل كامل](./get-aspose-ocr-version-in-c-complete-guide/) +دليل شامل يوضح طريقة استخراج رقم إصدار Aspose OCR في تطبيق C# واستخدامه في بيئة .NET. ### حالات الاستخدام الشائعة - **استخراج نصوص الصور** من الفواتير الممسوحة لأتمتة المحاسبة. @@ -102,4 +104,4 @@ weight: 24 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/arabic/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..342712b64 --- /dev/null +++ b/ocr/arabic/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-03 +description: احصل على نسخة Aspose OCR في C# باستخدام مقتطف بسيط. تعلم كيفية استرجاع + نسخة مكتبة Aspose OCR باستخدام OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: ar +og_description: احصل على نسخة Aspose OCR في C# بسرعة. يوضح هذا الدرس بالضبط كيفية + استرجاع نسخة مكتبة Aspose OCR باستخدام OcrEngine GetVersion. +og_title: احصل على نسخة Aspose OCR في C# – الدليل الكامل +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: احصل على نسخة Aspose OCR في C# – دليل كامل +url: /ar/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# احصل على نسخة Aspose OCR في C# – دليل كامل + +هل تساءلت يومًا كيف **تحصل على نسخة Aspose OCR** من داخل مشروع .NET الخاص بك؟ ربما تحاول حل مشكلة عدم التوافق، أو تريد فقط تسجيل نسخة المكتبة الدقيقة التي تعمل في بيئة الإنتاج. مهما كان السبب، فقد وصلت إلى المكان الصحيح. + +في هذا الدرس سنستعرض برنامج C# صغير ومستقل يستدعي `OcrEngine.GetVersion()` ويطبع النتيجة. بنهاية الدرس ستعرف ليس فقط *كيف* تسترجع النسخة، بل أيضًا *لماذا* فحص النسخة يمكن أن يوفر عليك المتاعب عند ترقية **مكتبة Aspose OCR**. + +## ما ستتعلمه + +- إضافة حزمة Aspose.OCR NuGet إلى مشروع C# +- استخدام طريقة `OcrEngine.GetVersion()` (نقطة الدخول **ocrengine getversion**) +- معالجة الاستثناءات المحتملة والتحقق من المخرجات +- توسيع المقتطف لسيناريوهات العالم الحقيقي مثل التسجيل أو تبديل الميزات الشرطية + +لا تحتاج إلى خبرة سابقة في OCR — فقط فهم أساسي لـ C# و Visual Studio (أو بيئة التطوير المفضلة لديك). لنبدأ. + +--- + +## الخطوة 1: إعداد المشروع وجلب مكتبة Aspose OCR + +قبل أن تتمكن من استدعاء أي واجهات برمجة تطبيقات متعلقة بـ OCR، تحتاج إلى الإشارة إلى **مكتبة Aspose OCR** في مشروعك. + +1. افتح الطرفية أو وحدة التحكم Package Manager Console في Visual Studio. +2. نفّذ الأمر التالي لتثبيت أحدث نسخة مستقرة: + +```bash +dotnet add package Aspose.OCR +``` + +> **نصيحة احترافية:** إذا كنت تستهدف .NET Framework بدلاً من .NET Core، استخدم واجهة NuGet Package Manager UI واختر النسخة التي تتطابق مع بيئة التشغيل الخاصة بك. الحزمة تتضمن الفئة `OcrEngine` التي سنستخدمها لاحقًا. + +### لماذا هذا مهم + +عند تثبيت الحزمة، قد تختلف نسخة التجميع على القرص عن النسخة التي تُبلغ عنها المكتبة أثناء التشغيل. الاستعلام عن النسخة عبر الكود يضمن أنك تقرأ النسخة الدقيقة التي حمّلها CLR، وهو أمر حاسم للتصحيح ولتدقيق الامتثال. + +--- + +## الخطوة 2: كتابة الكود الأدنى للحصول على **نسخة Aspose OCR** + +أنشئ تطبيق console جديد (`dotnet new console -n OcrVersionDemo`) واستبدل ملف `Program.cs` الافتراضي بما يلي: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**شرح كل جزء** + +- `using Aspose.OCR;` يجلب مساحة الاسم OCR إلى النطاق، مما يسمح لنا باستدعاء `OcrEngine`. +- `OcrEngine.GetVersion()` هي الطريقة الساكنة **ocrengine getversion** التي تُعيد سلسلة مثل `"24.5.7"`. +- إحاطة الاستدعاء بكتلة `try/catch` تحميك من مفاجآت وقت التشغيل — ربما لا يتم العثور على الثنائيات الأصلية على الجهاز المستهدف. +- السلسلة المتداخلة `$"Aspose OCR version: {version}"` تطبع سطرًا واضحًا وقابلًا للقراءة للإنسان. + +### النتيجة المتوقعة + +عند تشغيل `dotnet run` داخل مجلد المشروع، يجب أن ترى شيئًا مشابهًا لـ: + +``` +Aspose OCR version: 24.5.7 +``` + +إذا تعذر تحميل المكتبة، سيطبع فرع الخطأ رسالة مختصرة، تساعدك على تحديد المشكلة بسرعة. + +--- + +## الخطوة 3: التحقق من أن النسخة تتطابق مع حزمة NuGet الخاصة بك + +من السهل الافتراض أن نسخة NuGet التي قمت بتثبيتها هي النسخة المستخدمة أثناء التشغيل، لكن قد تتدخل خصوصيات البيئة. للتحقق مرة أخرى: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +تشغيل هذا المقتطف الإضافي سيطبع شيئًا مثل: + +``` +Assembly file version: 24.5.7.0 +``` + +إذا اختلفت القيمتان، قد تكون تقوم بتحميل DLL أقدم من الـ Global Assembly Cache (GAC) أو من مجلد بناء سابق. في هذه الحالة، نظّف الحل (`dotnet clean`) وأعد بناءه. + +--- + +## الخطوة 4: وضع فحص النسخة في سجلات الإنتاج + +معظم التطبيقات في العالم الحقيقي لا تقوم فقط بطباعة إلى وحدة التحكم؛ بل تكتب إلى ملف سجل أو نظام تتبع. إليك مثال سريع باستخدام `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +الآن تظهر النسخة في سجلاتك المنظمة، مما يجعل من السهل تصفية السجلات حسب `{Version}` لاحقًا. هذا النمط مفيد بشكل خاص عندما يكون لديك عدة خدمات مصغرة كل منها يجلب DLL OCR قد تكون مختلفة. + +--- + +## أسئلة شائعة وحالات خاصة + +### ماذا لو أعاد `GetVersion()` سلسلة فارغة؟ + +عادةً ما يشير ذلك إلى تثبيت معطوب أو اعتماد أصلي مفقود. أعد تثبيت حزمة NuGet وتأكد من أن `Aspose.OCR.Native.dll` (أو الملف الثنائي المناسب للمنصة) موجود بجوار الملف التنفيذي. + +### هل تعمل الطريقة على .NET Core 2.0؟ + +نعم، **Aspose OCR** يدعم .NET Standard 2.0 وما فوق، لذا أي نسخة من .NET Core تطبق هذا المعيار يمكنها استدعاء `OcrEngine.GetVersion()`. فقط تأكد من الإشارة إلى معرفات وقت التشغيل الصحيحة (`win‑x64`, `linux‑x64`, إلخ) إذا كنت تنشر تطبيقًا مستقلًا. + +### هل يمكنني استرجاع النسخة بدون ملف ترخيص؟ + +بالطبع. `GetVersion()` **لا** يتطلب ترخيصًا؛ فهو ببساطة يُبلغ عن رقم بناء المكتبة. ومع ذلك، إذا حاولت تنفيذ OCR بدون ترخيص صالح، ستحصل على استثناء وقت تشغيل. لهذا السبب فإن كتلة `try/catch` في المقتطف مفيدة — فهي تعزل فحص النسخة عن تدفق تنفيذ OCR. + +--- + +## مثال كامل جاهز للنسخ واللصق + +فيما يلي البرنامج بالكامل، جاهز للإدراج في مشروع console جديد. يتضمن كتلة التسجيل الاختيارية، بحيث يمكنك رؤية كل من مخرجات وحدة التحكم والسجلات المنظمة في العمل. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +شغّله باستخدام `dotnet run` وسترى سطرين يؤكدان النسخة، بالإضافة إلى سطر تصحيح إذا فعلت `LogLevel.Debug`. + +--- + +## الخلاصة + +لقد غطينا كل ما تحتاجه **للحصول على نسخة Aspose OCR** في بيئة C# — من تثبيت **مكتبة Aspose OCR**، واستدعاء طريقة **ocrengine getversion**، ومعالجة الأخطاء، إلى دمج النتيجة في سجلات الإنتاج. مسلحين بهذه المعرفة، يمكنك الآن التحقق بثقة من نسخة OCR الدقيقة التي يستخدمها تطبيقك، وتجنب الأخطاء المتعلقة بالنسخة، وتلبية متطلبات الامتثال دون عناء. + +الخطوات التالية؟ جرّب ربط فحص النسخة باستدعاء OCR فعلي (`OcrEngine` → `RecognizeImage`) وسجّل كل من النسخة ونتيجة التعرف. يمكنك أيضًا استكشاف نمط **retrieve aspose version** للمنتجات الأخرى من Aspose (PDF, Slides, Cells) للحفاظ على تزامن مجموعة الأدوات بالكامل. + +برمجة سعيدة، ولتظل خطوط أنابيب OCR حادة! + +--- + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [كيفية الحصول على نتائج OCR باستخدام Aspose.OCR لـ .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [كيفية معالجة مجموعة من صور OCR باستخدام List في Aspose.OCR لـ .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/arabic/net/ocr-optimization/_index.md index 1ca8c92a0..1794f50e2 100644 --- a/ocr/arabic/net/ocr-optimization/_index.md +++ b/ocr/arabic/net/ocr-optimization/_index.md @@ -73,6 +73,8 @@ weight: 25 حسّن دقة OCR مع Aspose.OCR for .NET. صحّح الأخطاء الإملائية، خصّص القواميس، واحصل على نص خالٍ من الأخطاء بسهولة. ### [حفظ النتيجة متعددة الصفحات كمستند في التعرف على الصور باستخدام OCR](./save-multipage-result-as-document/) افتح إمكانات Aspose.OCR for .NET. احفظ نتائج OCR متعددة الصفحات كمستندات بسهولة من خلال هذا الدليل الشامل خطوة بخطوة. +### [مثال Aspose OCR C# – تمكين GPU، ضبط حد الذاكرة ومعالجة صور TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +تعلم كيفية تمكين معالجة GPU، ضبط حد الذاكرة ومعالجة ملفات TIF باستخدام Aspose OCR في C#. ## الأسئلة المتكررة diff --git a/ocr/arabic/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/arabic/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..14feaaf8a --- /dev/null +++ b/ocr/arabic/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-03 +description: مثال Aspose OCR بلغة C# يوضح كيفية تعيين حد الذاكرة للـ GPU، تحميل الصورة + للتعرف الضوئي على الأحرف، والتعرف على النص من ملفات TIF مع الكود الكامل والنصائح. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: ar +og_description: 'تعلم مثالًا كاملاً لـ Aspose OCR بلغة C#: تمكين وحدة معالجة الرسومات، + تحديد حد الذاكرة لوحدة المعالجة الرسومية، تحميل صورة للتعرف الضوئي على الأحرف وتعرف + النص من ملفات TIF. يتضمن الكود الكامل.' +og_title: مثال Aspose OCR بلغة C# – تسريع GPU، حد الذاكرة ومعالجة TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: مثال Aspose OCR بلغة C# – تمكين وحدة معالجة الرسومات، تحديد حد الذاكرة ومعالجة + صور TIF +url: /ar/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# مثال Aspose OCR C# – تمكين GPU، تحديد حد الذاكرة ومعالجة صور TIF + +هل تساءلت يومًا كيف تستخرج أقصى أداء من كود **Aspose OCR C# example** عند التعامل مع مسحات TIFF الضخمة؟ لست وحدك. في العديد من المشاريع الواقعية—مثل رقمنة الأرشيفات أو استخراج البيانات من إيصالات عالية الدقة—العقبة ليست خوارزمية OCR نفسها، بل استغلال العتاد. + +الأمر هو أن Aspose OCR يدعم تسريع GPU، لكن عليك أن تخبره بالضبط مقدار الذاكرة التي يمكنه استهلاكها، وتحميل نوع الصورة الصحيح، وأخيرًا استخراج النص المعترف به من ملف .tif. هذا الدرس يشرح لك كل خطوة، من تثبيت SDK إلى تعديل إعدادات GPU، حتى تتمكن من تشغيل OCR بسرعة فائقة دون استنزاف ذاكرة GPU. + +سنضيف أيضًا بعض سيناريوهات “ماذا لو”—مثل معالجة ملفات TIFF متعددة الصفحات أو الرجوع إلى CPU عندما لا يتوفر GPU—حتى تحصل على حل قوي، وليس مجرد مقتطف واحد. + +## ما ستحتاجه + +| المتطلب | لماذا يهم | +|--------------|----------------| +| **.NET 6 SDK** (أو أحدث) | Aspose OCR يستهدف .NET Standard 2.0+، لذا أي نسخة .NET حديثة تعمل. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | المكتبة الأساسية التي توفر `OcrEngine`، `GpuSettings`، إلخ. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | مطلوب لتسريع GPU؛ سيتحقق SDK من وجود برنامج تشغيل متوافق أثناء التشغيل. | +| GPU بحد أدنى 2 GB VRAM** (سنحدد الحد عند 2048 MB) | بدون ذاكرة كافية، قد يعود المحرك إلى CPU بصمت. | +| صورة **TIFF عالية الدقة** تريد معالجتها | Aspose OCR يمكنه قراءة أي تنسيق نقطي تقريبًا، لكن TIF شائع للمسحات. | +| Visual Studio 2022 (أو أي محرر تفضله) | لبناء وتصحيح مشروع C#. | + +إذا كان أي من هذه مفقودًا، سيظل الكود يُترجم، لكنك لن ترى تحسينات الأداء التي نبحث عنها. + +## الخطوة 1: إنشاء محرك مثال Aspose OCR C# + +أول شيء في كل **Aspose OCR C# example** هو إنشاء مثيل لمحرك OCR. فكر في `OcrEngine` كمدير فيلم—ينسق كل شيء من تحميل الصورة إلى استخراج النص. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **نصيحة احترافية:** إذا كنت تخطط لمعالجة العديد من الصور متتالية، احتفظ بـ `OcrEngine` واحدًا نشطًا. إعادة إنشائه لكل صورة يضيف عبئًا قد يطغى على وقت الـ OCR. + +## الخطوة 2: تحديد حد ذاكرة GPU (وتفعيل التسريع) + +الآن يأتي الجزء الذي يربك الكثيرين: **تحديد حد ذاكرة GPU**. بشكل افتراضي، سيحاول Aspose OCR استخدام أكبر قدر ممكن من VRAM، مما قد يحرم التطبيقات الأخرى من الذاكرة على محطة عمل مشتركة. كائن `GpuSettings` يتيح لك تحديد الحد الأقصى للتخصيص. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### لماذا نحدد حدًا للذاكرة؟ + +- **الاستقرار:** يمنع تعطل الذاكرة عند معالجة صور ضخمة. +- **التعايش:** يسمح لتطبيقات أخرى تعتمد على GPU (مثل نماذج TensorFlow) بالعمل جنبًا إلى جنب. +- **القابلية للتنبؤ:** يجعل اختبار الأداء قابلًا للتكرار لأن GPU لن يبدأ في التبديل. + +إذا حذفت `MemoryLimitMb`، سيقوم Aspose بتخصيص ما يراه ضروريًا، وهذا قد يكون مناسبًا على خادم استدلال مخصص لكنه خطر على حاسوب مطور. + +## الخطوة 3: تحميل الصورة للـ OCR + +تحميل تنسيق الملف الصحيح هو الجزء الحاسم التالي. الطريقة `OcrImage.FromFile` تكتشف نوع الصورة تلقائيًا، لكن يجب عليك التأكد من وجود الملف وأنه نسخة TIFF مدعومة (مثل مضغوط LZW أو CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### معالجة ملفات TIFF متعددة الصفحات + +إذا كان ملف TIFF يحتوي على عدة صفحات، سيقرأ Aspose OCR الصفحة الأولى فقط بشكل افتراضي. لمعالجة جميع الصفحات، يمكنك التكرار عبر `image.Pages` (متاح في إصدارات SDK الأحدث) وإرسال كل صفحة إلى المحرك على حدة. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +المقتطف أعلاه يوضح نمط **تحميل الصورة للـ OCR** الذي يعمل مع الملفات ذات الصفحة الواحدة أو المتعددة. + +## الخطوة 4: التعرف على النص من TIF (أو أي صورة نقطية) + +الآن بعد أن أصبحت الصورة في الذاكرة، نطلب من Aspose تنفيذ سحره. طريقة `Recognize` تُعيد كائن `OcrResult` يحتوي على النص العادي، درجات الثقة، وحتى معلومات الصناديق المحيطة إذا احتجت إليها. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### لماذا يعمل هذا جيدًا مع TIF + +- **ضغط بدون فقدان:** غالبًا ما يخزن TIFF بيانات بكسل خام، مما يمنح محرك OCR أعلى دقة. +- **مساحات لونية متعددة:** يمكن لـ Aspose التعامل مع TIFF بالرمادي، RGB، أو حتى CMYK دون الحاجة إلى كود تحويل إضافي. + +إذا كنت بحاجة لتعديل حزم اللغات (مثل الفرنسية أو اليابانية)، اضبط `ocrEngine.Settings.Language = "fr"` قبل استدعاء `Recognize`. + +## الخطوة 5: عرض النص المعترف به + +أخيرًا، نطبع النص إلى وحدة التحكم. في تطبيق حقيقي قد تكتب إلى قاعدة بيانات، ملف JSON، أو تمرر السلسلة إلى خط أنابيب NLP لاحق. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### النتيجة المتوقعة + +تشغيل البرنامج على مسح واضح بدقة 300 dpi لصفحة مطبوعة عادةً ينتج شيء مثل: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +إذا كانت الصورة غير واضحة أو حد ذاكرة GPU منخفض جدًا، قد ترى أحرفًا مشوشة أو نتيجة مقطوعة. خفض `MemoryLimitMb` إلى أقل من حجم الصورة (غالبًا ~1 GB لتصوير TIFF بحجم 6000×8000 بكسل) قد يجعل المحرك يعود إلى CPU تلقائيًا. + +## مثال كامل يعمل + +فيما يلي البرنامج الكامل الجاهز للتنفيذ. انسخه والصقه في مشروع تطبيق Console جديد، استبدل `YOUR_DIRECTORY/large_photo.tif` بمسار ملف TIFF الخاص بك، واضغط **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### قائمة التحقق السريعة + +- ✅ **Aspose OCR C# example** تم تجميعه دون أخطاء. +- ✅ **GPU مفعّل** (`Enable = true`). +- ✅ **حد ذاكرة GPU** تم ضبطه على 2048 MB. +- ✅ **تم تحميل الصورة** من ملف TIF. +- ✅ **تم التعرف على النص** وطُبع. + +## المشكلات الشائعة وكيفية تجنبها + +| العَرَض | السبب المحتمل | الحل | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | لم يتم تثبيت runtime الخاص بـ CUDA أو هناك عدم توافق في الإصدار. | قم بتثبيت CUDA 11.x (أو 12.x) المتوافق مع برنامج التشغيل لديك. | +| OCR returns empty string | الصورة مظلمة جدًا أو DPI أقل من 150. | عالج مسبقًا باستخدام `image.AdjustContrast()` أو أعد التحويل إلى 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` منخفض جدًا بالنسبة للصورة. | رفع الحد أو تقسيم الصورة إلى قطع باستخدام `image.Crop`. | +| `Unsupported image format` error | يستخدم TIFF ضغطًا غريبًا (مثل JPEG‑2000). | حوّل TIFF إلى تنسيق مدعوم باستخدام ImageMagick قبل OCR. | + +## توسيع العرض التجريبي + +الآن بعد أن لديك **aspose ocr c# example** قويًا، قد ترغب في استكشاف: + +- **المعالجة الدفعية:** التكرار عبر مجلد من ملفات TIF، كتابة كل نتيجة إلى ملف `.txt`. +- **حزم اللغات:** `ocrEngine.Settings.Language = "es"` للإسبانية، أو تحميل قواميس مخصصة. +- **الصناديق المحيطة:** استخدم `ocrResult.Regions` للحصول على إحداثيات كل كلمة—مفيد لأدوات الحذف. +- **العودة إلى CPU:** غلف كتلة GPU بكتلة try/catch؛ عند الفشل، اضبط `ocrEngine.Settings.Gpu.Enable = false` وأعد المحاولة. + +These extensions keep the core pattern intact while adding value for specific use‑ + +## ماذا يجب أن تتعلم بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [استخراج النص من صورة باستخدام Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [استخراج النص من صورة – تحسين OCR باستخدام Aspose.OCR لـ .NET](/ocr/english/net/ocr-optimization/) +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/skew-angle-calculation/_index.md b/ocr/arabic/net/skew-angle-calculation/_index.md index 566ce602c..54c1a288e 100644 --- a/ocr/arabic/net/skew-angle-calculation/_index.md +++ b/ocr/arabic/net/skew-angle-calculation/_index.md @@ -40,9 +40,12 @@ url: /ar/net/skew-angle-calculation/ أطلق العنان لقوة Aspose.OCR لـ .NET، وهو حل قوي للتعرف على الصور. تعلم كيفية حساب زوايا الانحراف دون عناء. ### [حساب زاوية الانحراف من URI في التعرف على الصور OCR](./calculate-skew-angle-from-uri/) استكشف Aspose.OCR لـ .NET لحساب زوايا الانحراف بسهولة في التعرف على الصور باستخدام OCR. عزز مشاريعك بالدقة والكفاءة. +### [دورة مستند OCR المدور – إصلاح الانحراف التلقائي والدوران في C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +تعلم كيفية معالجة المستندات المدورة باستخدام Aspose.OCR لـ .NET وإصلاح الانحراف والدوران تلقائيًا في C#. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/arabic/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..6ac5cf200 --- /dev/null +++ b/ocr/arabic/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: دليل OCR للمستندات المدارة يوضح كيفية تصحيح الانحراف تلقائيًا واكتشاف + الدوران باستخدام Aspose OCR في C#. تعلم خطوة بخطوة مع الكود الكامل. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: ar +og_description: دورة OCR للوثائق المدوّرة تعلمك كيفية تصحيح الميل تلقائيًا واكتشاف + الدوران باستخدام Aspose OCR في C#. اتبع الدليل الكامل. +og_title: دليل OCR للمستندات المدوّرة – تصحيح الانحراف التلقائي وتدوير المستند في + C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: دليل OCR للمستندات المدوّرة – تصحيح الانحراف والتدوير تلقائيًا في C# +url: /ar/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# دليل OCR للمستندات المدوّرة – دليل كامل لمطوري C# + +هل صادفت يومًا **ocr rotated document tutorial** عندما يأتي نموذج ممسوح ضوئيًا مائلًا أو مائلًا؟ لست وحدك. تلك الصور المشوهة يمكن أن تفسد استخراج النص النظيف، لكن الخبر السار هو أن Aspose OCR يمكنه تصحيح الأمور تلقائيًا. + +في هذا الدليل خطوة بخطوة سننشئ `OcrEngine`، نفعّل **تصحيح الميل التلقائي** و**الكشف التلقائي عن الاتجاه**، نشغّل المحرك على صورة مدوّرة، ونطبع النص النظيف. في النهاية ستعرف بالضبط لماذا كل إعداد مهم، وكيفية ضبطه لحالات الحافة، وستحصل على برنامج C# جاهز للتنفيذ. + +## ما ستتعلمه + +* كيفية تثبيت وإشارة **Aspose OCR** في مشروع .NET. +* لماذا تمكين `AutoCorrectSkew` و `AutoDetectRotation` هو المفتاح لتطبيق **ocr rotated document tutorial** موثوق. +* كيفية تحميل أي صورة (JPG, PNG, TIFF) وترك المحرك يقوم بالعمل الشاق. +* نصائح لمعالجة ملفات PDF متعددة الصفحات، والمسحات منخفضة الدقة، وحزم اللغات المخصصة. + +> **المتطلبات المسبقة:** Visual Studio 2022 (أو أي بيئة تطوير C#)، .NET 6+ runtime، ورخصة Aspose OCR صالحة (أو النسخة التجريبية المجانية). لا حاجة لخبرة سابقة في OCR. + +--- + +## الخطوة 1 – تثبيت Aspose OCR وإعداد المشروع + +أولاً وقبل كل شيء. احصل على حزمة NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **نصيحة احترافية:** إذا كنت تستخدم ترخيصًا تجريبيًا، ضع ملف `Aspose.OCR.lic` في نفس مجلد الملف التنفيذي، أو سجّله برمجيًا باستخدام `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +أنشئ تطبيقًا جديدًا من نوع console: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +الآن لديك مساحة عمل نظيفة لتطبيق **ocr rotated document tutorial** الخاص بنا. + +## الخطوة 2 – تهيئة محرك OCR + +المحرك هو قلب العملية. فكر فيه كأداة سويسريّة متعددة الاستخدامات لاستخراج النص؛ كل ما عليك هو إخبارها بأي الحيل تريد تفعيلها. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**لماذا هذه الإعدادات؟** +* `AutoCorrectSkew` يحلل خط أساس الأحرف ويدور الصورة بما يكفي لجعل الخطوط أفقية. +* `AutoDetectRotation` ينظر إلى الاتجاه العام (0°, 90°, 180°, 270°) ويقلب الصفحة إذا كانت مقلوبة. بدونهما، سيقرأ المحرك “pɹᴉʍ” بدلاً من “word”. + +## الخطوة 3 – تحميل الصورة التي تريد معالجتها + +Aspose OCR يعمل مع أي تنسيق نقطي شائع. استبدل مسار العنصر النائب بالموقع الفعلي للنموذج المدوّر الخاص بك. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **حالة خاصة:** إذا استلمت ملف TIFF متعدد الصفحات، استخدم `OcrImage.FromMultiPageTiff(filePath)` وتكرار عبر `image.Pages`. + +## الخطوة 4 – تشغيل التعرف + +الآن يقوم المحرك بالسحر. سيقوم أولاً بتصحيح الصورة (بفضل علمي الميل/الاتجاه) ثم يستخرج الأحرف. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +إذا كنت تحتاج دعمًا للغات غير الإنجليزية، عيّن الإعداد قبل استدعاء `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## الخطوة 5 – إخراج النص المُعترف به + +أخيرًا، صبّ النص النظيف إلى وحدة التحكم—أو وجهه إلى ملف، قاعدة بيانات، أي شيء يناسب سير عملك. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**الناتج المتوقع** (بافتراض أن الصورة النموذجية تحتوي على “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +لاحظ كيف يظهر النص بشكل صحيح رغم أن الصورة الأصلية كانت مدوّرة 90° ومائلة قليلًا. + +--- + +## معالجة المشكلات الشائعة + +| المشكلة | لماذا يحدث | الحل | +|------|----------------|-----| +| **نص فارغ** | تم تعطيل تصحيح الميل أو الصورة مظلمة جدًا. | فعّل `AutoCorrectSkew` (مفعل بالفعل) وزد تباين الصورة عبر `image.AdjustContrast(1.2)`. | +| **حروف غير مفهومة** | إعداد اللغة غير صحيح. | عيّن `ocrEngine.Settings.Language` لتطابق لغة المستند. | +| **بطء الأداء على ملفات PDF الكبيرة** | المحرك يعالج كل صفحة على حدة. | استخدم `Parallel.ForEach` على `image.Pages` للاستفادة من المعالجات متعددة الأنوية. | +| **استثناء الترخيص** | انتهت الفترة التجريبية. | احصل على ترخيص دائم أو التزم بحدود النسخة التجريبية (5 صفحات لكل تشغيل). | + +--- + +## نصائح احترافية لتطبيق OCR للمستندات المدوّرة المتين + +* **معالجة دفعات:** غلف التدفق الكامل في طريقة تستقبل مسار مجلد، وتكرار على كل صورة، وتكتب كل نتيجة إلى ملف `.txt`. +* **ما قبل المعالجة:** أحيانًا يستفيد المسح الضوضائي من `image.Denoise()` قبل التعرف. +* **ما بعد المعالجة:** استخدم التعبيرات النمطية لتنظيف الأخطاء الشائعة في OCR، مثل استبدال “0” بـ “O” فقط عندما تكون محاطة بحروف. +* **التسجيل:** Aspose OCR يوفر `ocrEngine.Logger` – اربطه بموثق ملف لتسجيل التحذيرات حول درجات الثقة المنخفضة. + +--- + +## كود كامل وجاهز للتنفيذ + +احفظ ما يلي كملف `Program.cs` داخل مشروع الـ console الخاص بك. يتضمن جميع الخطوات، التعليقات، ومساعد صغير لمعالجة الدفعات. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +شغّله: + +```bash +dotnet run +``` + +يجب أن ترى النص المنقّح يُطبع على وحدة التحكم، مما يثبت أن **ocr rotated document tutorial** يعمل من البداية إلى النهاية. + +--- + +## الخلاصة + +الآن لديك دليل **ocr rotated document tutorial** كامل يُصحّح الميل تلقائيًا، يكتشف الاتجاه، ويستخرج نصًا نظيفًا باستخدام Aspose OCR في C#. الخلاصة الأساسية؟ تمكين `AutoCorrectSkew` **و** `AutoDetectRotation` يحوّل مسحًا مائلًا إلى مخرجات قابلة للقراءة تمامًا ببضع أسطر من الشيفرة. + +من هنا، يمكنك توسيع العمل إلى وظائف دفعات، دمج حزم اللغات، أو إمداد النتائج إلى خطوط أنابيب التحليل اللاحقة. هل تريد استكشاف **تصحيح الميل التلقائي** أكثر؟ اطلع على واجهة برمجة تطبيقات معالجة الصور في Aspose، أو جرّب عتبات مخصصة للمسحات الضوضائية. + +هل لديك أسئلة حول معالجة ملفات PDF، ملفات TIFF متعددة الصفحات، أو التكامل مع Azure Functions؟ اترك تعليقًا، وبرمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مصدر يتضمن أمثلة شيفرة كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [وضع مستند OCR – وضع اكتشاف المناطق في التعرف على صور OCR](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [دروس Aspose OCR – التعرف الضوئي على الأحرف](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/arabic/net/text-recognition/_index.md index 58e5dde95..bd0beb55a 100644 --- a/ocr/arabic/net/text-recognition/_index.md +++ b/ocr/arabic/net/text-recognition/_index.md @@ -53,11 +53,22 @@ url: /ar/net/text-recognition/ قم بتحسين تطبيقات .NET الخاصة بك باستخدام Aspose.OCR للتعرف الفعال على نص الصورة. استكشف وضع مناطق اكتشاف التعرف الضوئي على الحروف (OCR) للحصول على نتائج دقيقة. ### [التعرف على PDF في التعرف على الصور OCR](./recognize-pdf/) أطلق العنان لإمكانات التعرف الضوئي على الحروف في .NET باستخدام Aspose.OCR. استخراج النص من ملفات PDF دون عناء. قم بالتنزيل الآن للحصول على تجربة تكامل سلسة. +### [إجراء التعرف الضوئي على الحروف على ملف PDF باستخدام Aspose.OCR – دليل كامل بلغة C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +تعلم كيفية تنفيذ التعرف الضوئي على ملفات PDF باستخدام Aspose.OCR مع دليل شامل بلغة C#. ### [التعرف على الجدول في التعرف على الصور OCR](./recognize-table/) أطلق العنان لإمكانات Aspose.OCR لـ .NET من خلال دليلنا الشامل حول التعرف على الجداول في التعرف على الصور باستخدام OCR. +### [إجراء التعرف الضوئي على الحروف على صورة باستخدام Aspose OCR – دليل هندي](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +تعلم كيفية تنفيذ التعرف الضوئي على الحروف للصور باستخدام Aspose OCR مع إرشادات باللغة الهندية. +### [كيفية استخدام Aspose: تحويل الصورة إلى HTML باستخدام OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +تعلم كيفية تحويل الصور إلى ملفات HTML مع تضمين نصوص OCR باستخدام Aspose.OCR في .NET. +### [إجراء التعرف الضوئي على الحروف على صورة واكتشاف الكلمات المكتوبة خطأ في C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +تعلم كيفية تنفيذ التعرف الضوئي على الصور واكتشاف الأخطاء الإملائية باستخدام Aspose.OCR في C#. +### [التعرف الضوئي على ترجمات الفيديو في C# – دليل كامل](./video-subtitle-ocr-in-c-complete-guide/) +اكتشف كيفية استخراج نص ترجمات الفيديو باستخدام Aspose.OCR في C# عبر دليل شامل خطوة بخطوة. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/arabic/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..145b8ea1b --- /dev/null +++ b/ocr/arabic/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: كيفية استخدام Aspose لتحويل الصورة إلى HTML واستخراج النص من الصورة في + C#. تعلم كيفية إنشاء HTML من الصورة وتحويل الصورة إلى نص (OCR) إلى HTML بسرعة. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: ar +og_description: كيفية استخدام Aspose لتحويل الصورة إلى HTML، واستخراج النص من الصورة، + وإنشاء HTML من الصورة باستخدام OCR في C#. اتبع هذا الدليل الكامل. +og_title: 'كيفية استخدام Aspose: تحويل الصورة إلى HTML باستخدام OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'كيفية استخدام Aspose: تحويل الصورة إلى HTML باستخدام OCR' +url: /ar/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية استخدام Aspose: تحويل الصورة إلى HTML باستخدام OCR + +هل تساءلت **كيف تستخدم Aspose** حول تحويل صورة ممسوحة ضوئيًا إلى HTML منظم؟ ربما لديك صفحة مجلة، أو إيصال، أو ملاحظة مكتوبة يدويًا وتحتاج إلى الحفاظ على النص والتخطيط للنشر على الويب. الخبر السار هو أنك لست بحاجة إلى كتابة محلل مخصص أو التعامل مع معالجة الصور منخفضة المستوى—Aspose.OCR تقوم بالعمل الشاق نيابةً عنك. + +في هذا الدرس سنستعرض **مثالًا كاملاً وقابلًا للتنفيذ** يوضح لك كيفية **convert image to HTML**، **extract text from image**، و **generate HTML from image** باستخدام مكتبة Aspose OCR في C#. في النهاية ستحصل على تطبيق console صغير ينتج ملف HTML مع الحفاظ على تخطيط الصفحة الأصلي، جاهز لإدراجه في أي موقع ويب. + +## المتطلبات المسبقة + +- **.NET 6.0 SDK** أو أحدث (الكود يعمل مع .NET Core و .NET Framework على حد سواء). +- **Visual Studio 2022** (أو أي محرر تفضله). +- **Aspose.OCR for .NET** – تثبيت عبر NuGet: `dotnet add package Aspose.OCR`. +- ملف صورة (JPEG/PNG) ترغب في تحويله، مثال: `magazine_page.jpg`. + +لا تحتاج إلى ملفات تكوين إضافية؛ المكتبة تأتي مع كل ما يلزم للـ OCR وتوليد تخطيط HTML. + +## الخطوة 1: إعداد المشروع وإضافة Aspose.OCR + +أولاً، أنشئ مشروع console جديد وأضف حزمة Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **نصيحة احترافية:** إذا كنت تستخدم Visual Studio، ببساطة انقر بزر الماوس الأيمن على المشروع → *Manage NuGet Packages* → ابحث عن **Aspose.OCR** وقم بتثبيتها. هذه الخطوة تضمن أنك تستطيع **ocr image to html** دون أي مراجع مفقودة. + +## الخطوة 2: تهيئة محرك OCR + +جوهر العملية هو الفئة `OcrEngine`. فكر فيها كالعقل الذي يقرأ الصورة ويقرر كيفية إخراج النتيجة. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +هنا نقوم بإنشاء كائن `OcrEngine`. لا تحتاج إلى تمرير أي بيانات اعتماد للإصدار المجاني؛ المكتبة ستستخدم نماذج التعرف المدمجة. + +## الخطوة 3: تحميل الصورة المصدر + +بعد ذلك، وجه المحرك إلى الملف الذي تريد معالجته. توفر Aspose طريقة مريحة `OcrImage.FromFile` التي تدعم معظم صيغ الصور. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +استبدل `YOUR_DIRECTORY` بالمسار المطلق أو النسبي حيث توجد صورتك. إذا كانت الصورة في نفس مجلد الملف التنفيذي، يمكنك ببساطة استخدام `"magazine_page.jpg"`. + +## الخطوة 4: التعرف وطلب HTML مع التخطيط + +هذا هو جوهر الدرس. بتمرير `OutputFormat.HtmlWithLayout` نخبر Aspose بـ **generate HTML from image** مع الحفاظ على المواقع الأصلية لكتل النص، الصور، والجداول. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +الخاصية `recognitionResult.Text` الآن تحتوي على مستند HTML كامل. إذا كنت تحتاج فقط إلى نص عادي، يمكنك استخدام `OutputFormat.Text`، لكننا نركز على **convert image to html** مع الحفاظ على دقة التخطيط. + +## الخطوة 5: حفظ ملف HTML + +أخيرًا، اكتب سلسلة HTML إلى القرص. هذا يمنحك ملفًا جاهزًا للاستخدام يمكنك فتحه في أي متصفح. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +تشغيل البرنامج سيولد `magazine.html`. افتحه، وسترى نص الصفحة الأصلية موضعًا تمامًا كما ظهر في الصورة المصدر—مثالي للأرشفة أو النشر على الويب. + +## مثال كامل يعمل + +فيما يلي البرنامج **complete, copy‑paste‑ready**. لا توجد أجزاء محذوفة، لذا يمكنك تجميعه وتشغيله فورًا بعد ضبط المسارات الصحيحة. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### النتيجة المتوقعة + +عند فتح `magazine.html` في المتصفح، يجب أن ترى شيئًا مشابهًا لهذا (مبسط للتوضيح): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +ستختلف سمات `style` الدقيقة بناءً على الصورة الأصلية، لكن البنية تضمن أن **extract text from image** و **generate html from image** يحدثان في خطوة واحدة سلسة. + +## أسئلة شائعة وحالات خاصة + +### ماذا لو كانت الصورة منخفضة الدقة؟ + +يعمل Aspose.OCR بأفضل شكل مع الصور التي تحتوي على ما لا يقل عن **300 DPI**. إذا كان ملفك غير واضح، حاول معالجته مسبقًا باستخدام مكتبة تحسين الصور (مثل ImageSharp) قبل إرساله إلى محرك OCR. الجودة المنخفضة يمكن أن تؤثر على دقة **extract text from image** وعلى دقة تخطيط HTML المولد. + +### هل يمكنني التحكم بلغة OCR؟ + +نعم. اضبط الخاصية `Language` على `OcrEngine` قبل استدعاء `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +هذا يحسن التعرف عند التعامل مع أحرف غير إنجليزية. + +### كيف أحصل على نص عادي بدلاً من HTML؟ + +إذا كنت تحتاج فقط إلى السلسلة الخام، استبدل `OutputFormat.HtmlWithLayout` بـ `OutputFormat.Text`. الخاصية `recognitionResult.Text` ستحتوي حينها فقط على الأحرف المستخرجة. + +### هل هناك طريقة لتضمين الصور في HTML المولد؟ + +يمكن لـ Aspose.OCR تضمين الصورة الأصلية كـ base‑64 data URI عندما تستخدم `OutputFormat.HtmlWithLayoutAndImages`. هذا مفيد عندما تريد ملف HTML واحد دون موارد خارجية. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### ماذا عن معالجة دفعات كبيرة؟ + +للمعالجة الدفعية، غلف المنطق داخل حلقة `foreach` على قائمة مسارات الملفات. إعادة استخدام نفس كائن `OcrEngine` يقلل من الحمل ويسرّع خط أنابيب **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## نصائح لكتابة كود جاهز للإنتاج + +- **Dispose resources**: كل من `OcrEngine` و `OcrImage` يطبقان `IDisposable`. غلفهما داخل عبارات `using` لتحرير الذاكرة الأصلية بسرعة. +- **Error handling**: امسك `IOException` لمشكلات الملفات و `OcrException` لمشكلات التعرف. +- **Performance**: إذا كنت تعالج العديد من الصور، فكر في تمكين **parallelism** (`Parallel.ForEach`) لكن احذر من استهلاك المعالج—OCR يستهلك الكثير من CPU. +- **Logging**: دمج مسجل (مثل Serilog) لالتقاط درجات ثقة OCR (`recognitionResult.Confidence`) لمراقبة الجودة. + +## الخلاصة + +لقد غطينا للتو **how to use Aspose** لتحويل **image to HTML**، **extract text from image**، و **generate HTML from image** في بضع خطوات بسيطة. يوضح مثال الكود الكامل لك كيفية **ocr image to html** مع الحفاظ على التخطيط، مما يجعله أساسًا قويًا لأي مشروع رقمنة مستندات. + +من هنا يمكنك: + +- تجربة خيارات `OutputFormat` المختلفة لتناسب احتياجاتك. +- دمج مخرجات HTML مع إطار CSS لتصميم استجابة. +- إمداد النص المستخرج إلى فهرس بحث أو خط أنابيب تعلم آلي. + +جرّبه، عدّل الإعدادات، وشاهد كيف يحول Aspose الصور إلى محتوى جاهز للويب بسهولة. إذا واجهت أي مشاكل، اترك تعليقًا—برمجة سعيدة! + +![مخطط يوضح خط أنابيب OCR من الصورة إلى تخطيط HTML – كيفية استخدام Aspose](/images/ocr-pipeline.png "كيفية استخدام Aspose") + +--- + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [تحويل الصورة إلى نص – تنفيذ OCR على صورة من URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [التعرف على نص الصورة باستخدام 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/arabic/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/arabic/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..40d8c1198 --- /dev/null +++ b/ocr/arabic/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-03 +description: قم بإجراء التعرف الضوئي على الحروف (OCR) على الصورة واستخراج النص منها + باستخدام Aspose.OCR. تعلّم كيفية اكتشاف الكلمات المكتوبة بشكل خاطئ والحصول على اقتراحات + إملائية في عرض توضيحي واحد بلغة C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: ar +og_description: قم بإجراء OCR على الصورة لاستخراج النص منها، ثم اكتشف الكلمات المكتوبة + بشكل خاطئ واحصل على اقتراحات إملائية باستخدام Aspose.OCR في C#. +og_title: إجراء التعرف الضوئي على الأحرف في الصورة واكتشاف الكلمات المكتوبة بشكل خاطئ + في C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: إجراء التعرف الضوئي على الأحرف في الصورة واكتشاف الكلمات المكتوبة بشكل خاطئ + في C# +url: /ar/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إجراء OCR على الصورة واكتشاف الكلمات المكتوبة بشكل خاطئ في C# + +هل تساءلت يومًا كيف تقوم **perform OCR on image** للملفات دون أن تمزق شعرك؟ لست وحدك. سواءً كنت تقوم برقمنة رسائل قديمة، أو مسح الفواتير، أو بناء سير عمل مستندات ذكي، فإن استخراج نص نظيف من الصور هو العقبة الأولى. الخبر السار؟ مع Aspose.OCR يمكنك إنشاء حل خلال دقائق، والمكافأة هي أنك يمكنك أيضًا **detect misspelled words** و **get spelling suggestions** في نفس العملية. + +في هذا الدرس سنستعرض تطبيقًا كاملًا وجاهزًا للتنفيذ في وحدة تحكم C# يقوم **extracts text from image**، ويشغل مدقق إملائي للإنجليزية، ويطبع كل خطأ مع اقتراحات تصحيح مفيدة. بنهاية الدرس ستعرف بالضبط **how to extract text**، وكيفية ربط API المدقق الإملائي، وما هو شكل مخرجات وحدة التحكم المتوقعة. + +## ما ستبنيه + +- تحميل صورة bitmap (أو PNG) تحتوي على أخطاء إملائية. +- تشغيل Aspose.OCR لـ **perform OCR on image** والحصول على بيانات نصية خام. +- تهيئة مدقق الإملاء الإنجليزي المدمج. +- **Detect misspelled words** و **get spelling suggestions** لكل كلمة. +- طباعة تقرير منسق إلى وحدة التحكم. + +بدون خدمات خارجية، ولا مكالمات HTTP معقدة—فقط حزمة NuGet واحدة وقليل من أسطر الشيفرة. + +## المتطلبات المسبقة + +- .NET 6.0 SDK أو أحدث (الكود يعمل أيضًا على .NET Framework 4.7+). +- Visual Studio 2022 (أو أي محرر تفضله). +- حزمة NuGet Aspose.OCR لـ .NET (`Aspose.OCR`). +- ملف صورة (`letter_with_typos.png`) موجود في مكان يمكنك الإشارة إليه من المشروع. + +إذا لم تستخدم Aspose من قبل، لا تقلق—تثبيت الحزمة سهل كتشغيل: + +```bash +dotnet add package Aspose.OCR +``` + +الآن دعنا نغوص في التنفيذ. + +## الخطوة 1: إعداد المشروع وتثبيت Aspose.OCR + +أنشئ مشروع وحدة تحكم جديد وأدرج مكتبة OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +بعد انتهاء الاستعادة، افتح `Program.cs`. سنستبدل المحتوى الافتراضي بكود العرض الكامل لاحقًا، ولكن أولاً دعنا نتحدث عن سبب أهمية كل مساحة أسماء. + +- `Aspose.OCR` – محرك OCR الأساسي ومعالجة الصور. +- `Aspose.OCR.SpellCheck` – أدوات التدقيق الإملائي المرفقة بالمكتبة. +- `System` – فئات .NET الأساسية القياسية (مثل `Console`). + +## الخطوة 2: تحميل الصورة وإجراء OCR على الصورة + +العمل الحقيقي الأول هو تمرير الصورة إلى محرك OCR. Aspose.OCR يقرأ العديد من الصيغ (PNG، JPEG، TIFF). إليك المقتطف الذي يقوم بالعمل الشاق: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **لماذا هذا مهم:** `OcrImage.FromFile` يخفّف تفاصيل مستوى البكسل، بينما `OcrEngine.Recognize` يشغّل النموذج العصبي المدرب الذي يترجم الرموز البصرية إلى أحرف Unicode. خاصية `ocrResult.Text` الآن تحتوي على السلسلة الخام—بالضبط ما تحتاجه لـ **extract text from image**. +> **نصيحة احترافية:** إذا كانت صورتك تحتوي على لغات متعددة، يمكنك تعيين `ocrEngine.Language = OcrLanguage.Multilingual;` قبل استدعاء `Recognize`. + +## الخطوة 3: تهيئة مدقق الإملاء الإنجليزي + +Aspose.OCR يأتي مع محرك تدقيق إملائي مدمج يفهم الإنجليزية مباشرةً. تهيئته سطر واحد: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **لماذا هذه الخطوة حاسمة:** قد يتضمن ناتج OCR أحرفًا تم التعرف عليها بشكل خاطئ (مثل “l” مقابل “1”) أو أخطاء إملائية حقيقية من المستند الأصلي. سيقوم مدقق الإملاء بمسح السلسلة، وتحديد الرموز المشكوك فيها، واقتراح بدائل. + +## الخطوة 4: اكتشاف الكلمات المكتوبة بشكل خاطئ والحصول على اقتراحات إملائية + +الآن نقوم بتمرير نص OCR إلى المدقق: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` هي مجموعة حيث يحتوي كل إدخال على الكلمة الخاطئة ومصفوفة من التصحيحات المحتملة. + +## الخطوة 5: إخراج النتائج + +أخيرًا، نقوم بالتكرار عبر المجموعة وطباعة تقرير قابل للقراءة للإنسان: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### مخرجات وحدة التحكم المتوقعة + +بافتراض أن `letter_with_typos.png` يحتوي على الجملة: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +تشغيل العرض سيولد شيئًا مشابهًا لـ: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +لاحظ كيف يتم إقران كل خطأ إملائي بمجموعة من التصحيحات المحتملة—بالضبط ما تحتاجه عند بناء واجهة تصحيح صديقة للمستخدم. + +## مثال كامل يعمل + +فيما يلي البرنامج **complete, copy‑paste‑ready**. استبدل `YOUR_DIRECTORY` بالمسار الفعلي لملف الصورة الخاص بك. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **حالات الحافة التي يجب مراعاتها** +> - **Empty Image:** إذا أعاد محرك OCR سلسلة فارغة، فإن `spellChecker.Check` سيعيد ببساطة مجموعة فارغة—بدون تعطل. +> - **Non‑English Text:** استبدل `OcrLanguage.English` بـ `OcrLanguage.French` (أو أي لغة مدعومة) لـ **detect misspelled words** في لغات أخرى. +> - **Large Documents:** بالنسبة لملفات PDF متعددة الصفحات، ستقوم بالتكرار على كل صفحة، إجراء OCR، ثم تجميع النتائج قبل التدقيق الإملائي. + +## نظرة بصرية (نص بديل للصورة) + +![مخطط يوضح تدفق إجراء OCR على الصورة، استخراج النص من الصورة، ثم اكتشاف الكلمات المكتوبة بشكل خاطئ مع اقتراحات إملائية](perform-ocr-on-image-flow.png) + +*المخطط أعلاه يوضح خط الأنابيب من البداية إلى النهاية: صورة → محرك OCR → نص خام → مدقق إملائي → اقتراحات.* + +## أسئلة شائعة ونصائح احترافية + +| السؤال | الجواب | +|----------|--------| +| **هل أحتاج إلى اتصال بالإنترنت؟** | لا. Aspose.OCR يعمل بالكامل محليًا؛ مثالي للبيئات غير المتصلة أو الآمنة. | +| **ما مدى دقة مدقق الإملاء؟** | يستخدم قاموسًا يضم حوالي 150 ألف كلمة إنجليزية وتقنية المطابقة الضبابية، لذا يتم التقاط معظم الأخطاء الشائعة. | +| **هل يمكنني تخصيص القاموس؟** | نعم. `SpellChecker.AddUserDictionary("custom.txt")` يتيح لك تحميل مصطلحات خاصة بالمجال (مثل أسماء المنتجات). | +| **ماذا لو كانت الصورة مائلة؟** | محرك OCR يكتشف الاتجاه تلقائيًا، ولكن يمكنك استدعاء `ocrEngine.ImagePreprocessing.Rotate(angle)` يدويًا في الحالات الصعبة. | +| **هل هناك طريقة لتسليط الضوء على الاقتراحات في واجهة المستخدم؟** | بعد الحصول على مجموعة `misspellings`، يمكنك ربط كل `entry.Word` بموقعه في `ocrResult.Text` وتسطيره في RichTextBox أو عرض ويب. | + +## الخلاصة + +لقد أظهرنا لك الآن **how to perform OCR on image**، **extract text from image**، ثم **detect misspelled words** مع **getting spelling suggestions**—كل ذلك باستخدام تطبيق وحدة تحكم C# مختصر. الفكرة الأساسية بسيطة: دع Aspose.OCR يتولى الجزء الثقيل من التعرف على الأحرف، ثم دع مدقق الإملاء المدمج ينظف الناتج. من هنا يمكنك توسيع العرض إلى خدمة معالجة مستندات كاملة، دمجه مع API ويب، أو ربطه بمحرر سطح مكتب. + +هل أنت مستعد للخطوة التالية؟ جرّب تبديل اللغة إلى الإسبانية، أو معالجة PDF متعدد الصفحات، أو بناء واجهة WPF صغيرة تسمح للمستخدمين بالنقر على كلمة لقبول اقتراح. اللبنات الأساسية موجودة بالفعل—استمر في التجربة. + +إذا واجهت أي مشاكل أو كان لديك أفكار لتوسعات، اترك تعليقًا أدناه. برمجة سعيدة! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [استخراج النص من الصورة باستخدام Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [استخراج النص من الصورة – تحسين 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/arabic/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/arabic/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..fd43bc89b --- /dev/null +++ b/ocr/arabic/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: تنفيذ التعرف الضوئي على الأحرف (OCR) على صورة باستخدام Aspose OCR في + C#. تعلم كيفية تحميل الصورة للتعرف الضوئي واستخراج النص الهندي من الصورة دون اتصال + بخطوات برمجية مفصلة. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: ar +og_description: إجراء التعرف الضوئي على الحروف (OCR) على صورة باستخدام Aspose OCR + في C#. يوضح هذا الدرس كيفية تحميل الصورة للتعرف الضوئي على الحروف واستخراج النص + الهندي من الصورة دون اتصال، مع كود قابل للتنفيذ. +og_title: إجراء OCR على الصورة – دليل Aspose OCR للغة الهندية +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: تنفيذ التعرف الضوئي على الأحرف في الصورة باستخدام Aspose OCR – دليل هندي +url: /ar/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إجراء OCR على الصورة باستخدام Aspose OCR – دليل اللغة الهندية + +هل احتجت يومًا إلى **perform OCR on image** للملفات لكن واجهت صعوبة في استخراج الأحرف الهندية منها؟ لست وحدك—العديد من المطورين يواجهون هذه المشكلة عندما يحاولون قراءة النصوص غير اللاتينية لأول مرة. الخبر السار هو أن Aspose OCR يجعل العملية سهلة إلى حد كبير، ويمكنك حتى تنفيذها بالكامل دون اتصال. + +في هذا الدليل سنقوم **load image for OCR**، وتوجيه المحرك إلى حزم اللغة غير المتصلة بالإنترنت، وأخيرًا **extract Hindi text image** البيانات دون الحاجة إلى الاتصال بالإنترنت. في النهاية ستحصل على تطبيق C# Console جاهز للتشغيل يقرأ إيصالًا هنديًا ويطبع النص على وحدة التحكم. + +## ما ستحتاجه + +- **.NET 6.0** أو أحدث (الكود يعمل أيضًا على .NET Framework 4.7+) +- حزمة NuGet **Aspose.OCR for .NET** + `dotnet add package Aspose.OCR` +- مجلد يحتوي على **offline Hindi language resources** (قم بالتنزيل من بوابة Aspose) +- ملف صورة يحتوي على نص هندي، مثال: `receipt_hindi.png` + +هذا كل شيء—لا خدمات خارجية، لا مفاتيح API، فقط كود بسيط. + +## تنفيذ OCR على الصورة – خطوة بخطوة + +فيما يلي نقسم العملية إلى سبع خطوات واضحة. يتم شرح كل خطوة **لماذا** هي مهمة، وليس فقط **ماذا** تكتب. + +### الخطوة 1: إنشاء كائن محرك OCR + +المحرك هو قلب Aspose OCR. إنشاء كائن منه يمنحك الوصول إلى جميع الإعدادات التي ستقوم بتعديلها لاحقًا. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **لماذا؟** +> بدون `OcrEngine` لا يوجد كائن يمكنك استدعاء `Recognize` عليه. فكر فيه كـ “كاميرا” ستقوم لاحقًا بمسح صورتك. + +### الخطوة 2: توجيه المحرك إلى الموارد غير المتصلة + +Aspose توفر حزم لغات يمكنك تخزينها محليًا. ضبط `ResourcesFolder` يخبر المحرك بمكان البحث. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **نصيحة:** +> استخدم مسارًا مطلقًا أثناء التطوير، ثم انتقل إلى مسار نسبي أو إعداد تكوين للإنتاج. + +### الخطوة 3: فرض وضع غير متصل + +قد تتساءل، “هل أحتاج حقًا إلى تعطيل البحث عبر الإنترنت؟” إذا كنت تعمل خلف جدار حماية أو تريد نتائج حتمية، اضبط `UseOfflineResources` إلى `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **نصيحة احترافية:** +> ترك هذه العلامة `false` قد يتسبب في تحميل المحرك لبيانات إضافية، مما يزيد من زمن الاستجابة وقد ينتهك سياسات الأمان. + +### الخطوة 4: اختيار الهندية كلغة التعرف + +هنا نقوم **extract Hindi text image** عن طريق إخبار المحرك اللغة المتوقعة. هذا يحسن الدقة بشكل كبير. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **لماذا يساعد ذلك:** +> تستخدم محركات OCR نماذج أحرف مخصصة للغة. من خلال القفل على الهندية، تتجنب تخمين المحرك بين عشرات النصوص. + +### الخطوة 5: تحميل الصورة لـ OCR + +الآن نقوم فعليًا **load image for OCR**. طريقة `OcrImage.FromFile` تقرأ البت ماب إلى صيغة يفهمها المحرك. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **مشكلة شائعة:** +> توفير مسار باستخدام الشرط المائل للأمام على Windows يعمل، لكن استخدام `Path.Combine` يجعل الكود غير معتمد على منصة معينة. + +### الخطوة 6: تشغيل عملية التعرف + +مع إعداد كل شيء، أخيرًا **perform OCR on image** عن طريق استدعاء `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **ما الذي يحدث؟** +> يقوم المحرك بمسح كل بكسل، ومطابقة الأنماط مع قاعدة بيانات رموز الهندية، ويُنشئ سلسلة من أحرف Unicode. + +### الخطوة 7: إخراج النص المعترف به + +كائن النتيجة يحتوي على خاصية `Text` التي تحمل السلسلة المستخرجة. نكتبها ببساطة إلى وحدة التحكم. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **الناتج المتوقع:** +> إذا كان `receipt_hindi.png` يحتوي على “भुगतान सफल”، ستطبع وحدة التحكم هذا السطر بالضبط، مع الحفاظ على العلامات. + +## تحميل الصورة لـ OCR – تحضير المورد + +إذا كنت تتساءل ما إذا كان بإمكانك تزويد المحرك بتدفق بدلاً من ملف، الجواب نعم. استبدل `OcrImage.FromFile` بـ: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **لماذا استخدام تدفق؟** +> تسمح لك التدفقات بالعمل مع الصور المخزنة في قواعد البيانات، أو كائنات السحابة، أو الموارد المدمجة—مثالي للخدمات القابلة للتوسع. + +## استخراج نص الصورة الهندية – معالجة الحالات الخاصة + +1. **Missing language pack** – إذا لم يتم العثور على حزمة اللغة الهندية، سيُطلق `Recognize` استثناء. غلف الاستدعاء داخل try/catch وسجّل رسالة ودية. +2. **Low‑resolution images** – تنخفض دقة OCR عندما تكون أقل من 300 dpi. قم بمعالجة الصورة مسبقًا (تغيير الحجم، تحسين الحدة) قبل التحميل. +3. **Mixed‑language documents** – يمكنك تمكين عدة لغات: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +هذه التعديلات تضمن بقاء روتين **perform OCR on image** قويًا في بيئة الإنتاج. + +## تشغيل المثال الكامل + +احفظ الملف التالي باسم `Program.cs`، استبدل مسارات العنصر النائب، ثم شغّله: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +عند تنفيذ `dotnet run`، يجب أن ترى شيئًا مشابهًا لـ: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +إذا حصلت على سلسلة فارغة، تحقق مرة أخرى من أن **ResourcesFolder** يشير إلى المجلد الذي يحتوي على `Hindi.traineddata` وأن الصورة واضحة بما فيه الكفاية. + +## الخلاصة + +لقد استعرضنا كيفية **perform OCR on image** للملفات باستخدام Aspose OCR، مع تغطية كل شيء من **load image for OCR** إلى **extract Hindi text image** في سيناريو كامل غير متصل. يوفر لك الكود القابل للتنفيذ أعلاه أساسًا قويًا، وستساعدك النصائح حول التدفقات، ومعالجة الأخطاء، ودعم متعدد اللغات على تكييف الحل للمشاريع الواقعية. + +هل أنت مستعد للخطوة التالية؟ جرّب تغيير اللغة إلى **OcrLanguage.Tamil** أو إمداد الصور من تخزين Azure Blob. يمكنك أيضًا تجربة إعدادات `ImagePreprocessing` لزيادة الدقة على الإيصالات الضوضائية. + +هل لديك أسئلة أو واجهت مشكلة؟ اترك تعليقًا—برمجة سعيدة! + +![Perform OCR on image example + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات الموضحة في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [التعرف على نص الصورة باستخدام Aspose OCR لعدة لغات](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [استخراج النص من الصورة – تحسين 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/arabic/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/arabic/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..d38b9c205 --- /dev/null +++ b/ocr/arabic/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-03 +description: قم بتنفيذ OCR على ملفات PDF وتحويل PDF الممسوح ضوئياً إلى PDF قابل للبحث + باستخدام Aspose.OCR. تعلم كيفية التعرف على النص من PDF وإنشاء ملفات PDF قابلة للبحث + في دقائق. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: ar +og_description: قم بإجراء التعرف الضوئي على الحروف (OCR) على ملف PDF وإنشاء ملف PDF + قابل للبحث على الفور. يوضح هذا الدرس خطوة بخطوة كيفية التعرف على النص من ملف PDF + باستخدام Aspose.OCR. +og_title: إجراء OCR على PDF – دليل C# الكامل +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: إجراء التعرف الضوئي على الأحرف (OCR) على ملفات PDF باستخدام Aspose.OCR – دليل + C# الكامل +url: /ar/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إجراء OCR على PDF باستخدام Aspose.OCR – دليل C# كامل + +هل تساءلت يومًا **كيف تقوم بإجراء OCR على ملفات PDF** دون التعامل مع العشرات من أدوات سطر الأوامر؟ أنت لست وحدك. سواءً كنت تقوم برقمنة الفواتير، أو أرشفة التقارير القديمة، أو تحتاج فقط إلى نسخة قابلة للبحث من عقد ممسوح ضوئيًا، فإن تحويل PDF ثابت إلى شيء يمكنك البحث فيه فعليًا يُغيّر قواعد اللعبة. + +في هذا الدليل سنستعرض **كيفية إنشاء ملفات PDF قابلة للبحث** من ملفات PDF الممسوحة (وحتى الصور العادية) باستخدام Aspose.OCR لـ .NET. بحلول النهاية ستتمكن من **التعرف على النص من PDF** ببضع أسطر من كود C#، وستفهم سبب كل خطوة حتى تتمكن من تكييف الحل مع مشاريعك الخاصة. + +> **ملخص سريع:** العملية بأكملها تختصر في ثلاث خطوات—تهيئة محرك OCR، تزويده بالمصدر (PDF أو صورة)، وحفظ ناتج PDF القابل للبحث. لنبدأ. + +--- + +## ما ستحتاجه + +| المتطلب | لماذا يهم | +|--------------|----------------| +| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.OCR يستهدف بيئات تشغيل حديثة؛ قد تفقد الإصدارات القديمة تحديثات API. | +| **Aspose.OCR for .NET** NuGet package | يوفر فئة `OcrEngine` وأدوات معالجة PDF. | +| **A valid Aspose license** (or use the free evaluation) | بدون ترخيص ستواجه حد التقييم لمدة 30 يومًا وعلامات مائية. | +| **A scanned PDF** (or an image file) you want to make searchable | هذا هو المستند المصدر لعملية OCR. | +| **Visual Studio 2022** (or any C# editor) | يسهل عملية التصحيح، لكن أي بيئة تطوير متكاملة تعمل. | + +يمكنك تثبيت المكتبة باستخدام أمر NuGet التالي: + +```bash +dotnet add package Aspose.OCR +``` + +> **نصيحة احترافية:** إذا كنت تعمل على خط أنابيب CI، أضف ملف الترخيص إلى مخرجات البناء وحمّله أثناء وقت التشغيل لتجنب كتابة المسارات بشكل ثابت. + +## إجراء OCR على PDF – إعداد Aspose.OCR + +أول شيء نحتاجه هو نسخة جديدة من `OcrEngine`. فكر فيها كالعقل الذي سيقرأ مستندك. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +لماذا نسخة جديدة في كل مرة؟ يحتفظ المحرك بالإعدادات (مثل إعدادات اللغة) التي قد تختلف بين المستندات. إنشاء نسخة لكل تشغيل يضمن بداية نظيفة ويتجنب التداخل بين المهام. + +## كيفية إنشاء PDF قابل للبحث – تكوين كلمات المرور (اختياري) + +إذا كان ملف PDF محميًا، عليك إخبار المحرك بكلمة المرور قبل أن يتمكن من قراءة الصفحات: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +تخطي هذه الخطوة على ملف محمي سيؤدي إلى رفع استثناء `PdfPasswordException`. احرص دائمًا على وضعه داخل كتلة try‑catch إذا لم تكن متأكدًا من حالة الحماية. + +## تحويل PDF ممسوح إلى PDF قابل للبحث – تحميل المصدر + +يعمل Aspose.OCR مع تجريد `OcrImage`، الذي يمكنه تغليف ملفات PDF، TIFF، JPEG، وغيرها. إليك كيفية تحميل PDF ممسوح إلى الذاكرة: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +في الخلفية، تقوم `FromFile` بتحليل كل صفحة إلى صور نقطية يمكن لمحرك OCR معالجتها. إذا كان لديك PDF متعدد الصفحات، سيقوم المحرك تلقائيًا بالتنقل عبر كل صفحة. + +## التعرف على النص من PDF – تنفيذ OCR + +الآن جوهر الدرس: اطلب من المحرك التعرف على النص وإنتاج PDF قابل للبحث. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` يخبر المحرك بدمج طبقة نص غير مرئية فوق الصور الممسوحة الأصلية. يحتفظ PDF الناتج بجودة الصورة الأصلية بينما يصبح قابلًا للبحث بالكامل—وهو بالضبط ما تحتاجه لتدقيق الامتثال. + +## تحويل صورة إلى PDF قابل للبحث – حفظ النتيجة + +أخيرًا، اكتب البيانات الثنائية إلى القرص: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +خاصية `Binary` تحتفظ ببايتات PDF الخام. يمكنك أيضًا بثها مباشرةً إلى استجابة ويب إذا كنت تبني API. + +![مخطط يوضح تدفق تحويل OCR لإنشاء PDF قابل للبحث](https://example.com/ocr-flow.png "مخطط تدفق إجراء OCR على PDF") + +*Image alt text: Perform OCR on PDF flow diagram illustrating how a scanned PDF is turned into a searchable PDF.* + +## حالات الحافة والنصائح العملية + +### 1. الملفات الكبيرة وإدارة الذاكرة +إذا كنت تعالج ملفات PDF أكبر من 100 ميغابايت، فكر في استخدام `OcrEngineSettings.MemoryLimit` لتحديد حد لاستخدام الذاكرة. بالإضافة إلى ذلك، عالج الصفحات على دفعات لتجنب استثناء `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. دعم اللغات +بشكل افتراضي، يفترض Aspose.OCR اللغة الإنجليزية. للتعرف على لغات أخرى، اضبط خاصية `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. السيناريوهات متعددة الخيوط +`OcrEngine` **ليس** آمنًا للاستخدام المتعدد الخيوط. إذا كنت تحتاج إلى معالجة متوازية، أنشئ محركًا منفصلًا لكل خيط. + +### 4. تصحيح دقة OCR +يمكنك استخراج النص العادي من `ocrResult` للتصحيح: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +إذا كان الناتج غير واضح، جرب تعديل `PreprocessSettings` (مثل تصحيح الميل، إزالة الضوضاء) لتحسين الجودة. + +### 5. مشكلات الترخيص +عند تشغيل النسخة التجريبية، يضيف Aspose علامة مائية إلى PDF الناتج. سجّل ترخيصك مبكرًا في التطبيق: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +## مثال عملي كامل – من البداية إلى النهاية + +فيما يلي البرنامج الكامل الجاهز للتنفيذ والذي يدمج جميع النصائح السابقة. لا تتردد في نسخه ولصقه في مشروع وحدة تحكم جديد. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**الناتج المتوقع:** بعد التشغيل، سترى سطرًا في وحدة التحكم يؤكد موقع الملف. افتح `output.pdf` في أي عارض PDF؛ حاول كتابة كلمة تعرف أنها موجودة في المسح الأصلي. إذا تم تظليل النص، فقد نجحت في **إجراء OCR على PDF** وإنشاء مستند قابل للبحث. + +## الأسئلة المتكررة + +**س: هل يمكنني استخدام هذا لتحويل صورة واحدة (PNG/JPEG) إلى PDF قابل للبحث؟** +ج: بالتأكيد. استبدل `OcrImage.FromFile("input.pdf")` بمسار ملف الصورة الخاص بك. سيقوم المحرك بتحويل الصورة إلى نقطية ودمج طبقة OCR بنفس الطريقة. + +**س: ماذا لو كان PDF يحتوي على صفحات ممسوحة ونص أصلي؟** +ج: سيضيف المحرك نص OCR فوق المحتوى الموجود، لذا يبقى النص الأصلي قابلًا للتحديد بينما تصبح الصفحات الممسوحة قابلة للبحث. + +**س: ما مدى دقة OCR؟** +ج: الدقة تعتمد على جودة المصدر. المسحات النظيفة وعالية الدقة (>300 dpi) تعطي دقة >95 %. بالنسبة للوثائق الضوضائية، فعّل `PreprocessSettings` (تصحيح الميل، إزالة الضوضاء) قبل استدعاء `Recognize`. + +## الخطوات التالية – توسيع مجموعة أدوات OCR الخاصة بك + +الآن بعد أن يمكنك **التعرف على النص من PDF** و**تحويل PDF ممسوح إلى PDF قابل للبحث**، فكر في المواضيع التالية: + +- **معالجة دفعات**: تكرار عبر مجلد من ملفات PDF وإنشاء نسخ قابلة للبحث تلقائيًا. +- **استخراج النص**: استخدم `ocrResult.Text` لتغذية فهرس بحث (مثل Elasticsearch). +- **حزم لغات مخصصة**: حمّل بيانات لغات إضافية من Aspose لدعم النصوص الآسيوية. +- **امتثال PDF/A**: دمج Aspose.PDF مع ناتج OCR لإنشاء ملفات PDF جاهزة للأرشفة. + +كل من هذه يبني على الخطوات الأساسية التي غطيناها، لذا أنت في موقع جيد لتوسيع حلك. + +## الخلاصة + +لقد أظهرنا لك للتو **كيفية إجراء OCR على ملفات PDF** باستخدام Aspose.OCR، وحولنا ملفات PDF الممسوحة إلى ملفات PDF قابلة للبحث بالكامل، وحتى تناولنا تحويل الصور العادية إلى ملفات PDF قابلة للبحث. الكود + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف أساليب تنفيذ بديلة في مشاريعك. + +- [التعرف على نص PDF – عمليات OCR باستخدام Aspose.OCR للـ Java](/ocr/english/java/ocr-operations/) +- [كيفية إجراء 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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/arabic/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..98616c1bc --- /dev/null +++ b/ocr/arabic/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: دورة تعليمية للتعرف الضوئي على النصوص في ترجمات الفيديو تُظهر كيفية استخراج + الإطارات من الفيديو وقراءة النص من ملفات الفيديو مثل MP4 باستخدام Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: ar +og_description: تعلم تقنية التعرف الضوئي على الأحرف للترجمة المصاحبة للفيديو باستخدام + Aspose.OCR. استخرج الإطارات من الفيديو، اقرأ النص من الفيديو، واستخرج النص من ملفات + MP4 في بضع دقائق. +og_title: التعرف الضوئي على الأحرف في ترجمات الفيديو باستخدام C# – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: دليل شامل للتعرف الضوئي على الأحرف في ترجمات الفيديو باستخدام C# +url: /ar/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# التعرف الضوئي على الأحرف (OCR) للترجمات في الفيديو باستخدام C# – دليل كامل + +هل احتجت يومًا إلى **video subtitle ocr** لكنك لم تكن متأكدًا من أين تبدأ؟ لست وحدك. سواءً كنت تقوم برقمنة تسجيلات المحاضرات، أو استخراج الترجمات من مقاطع الفيديو التدريبية، أو مجرد فضول حول قراءة النص من الفيديو، فإن هذا الدليل يوضح لك بالضبط كيفية القيام بذلك باستخدام C# و Aspose.OCR. + +في الدقائق القليلة القادمة سنستخرج إطارات من الفيديو، نشغّل OCR على تلك الإطارات، وأخيرًا نعرض نص الترجمة إطارًا بإطار. في النهاية ستتمكن من **read text from video** للملفات—including MP4—دون الحاجة للبحث عن أدوات طرف ثالث. + +## ما ستبنيه + +سننشئ تطبيقًا صغيرًا من نوع console يقوم بـ: + +1. فك تشفير ملف MP4 (أو أي صيغة مدعومة) إلى إطارات `Bitmap` منفصلة. +2. حصر منطقة OCR على شريط الترجمة حتى لا يتشتت المحرك مع الصورة بالكامل. +3. معالجة كل إطار باستخدام `VideoOcrProcessor` من Aspose. +4. طباعة نص الترجمة المعترف به إلى وحدة التحكم. + +لا إطالة، مجرد مثال عملي من البداية إلى النهاية يمكنك دمجه في مشروع حقيقي. + +## المتطلبات المسبقة + +- **.NET 6.0** أو أحدث (الكود يعمل أيضًا على .NET Framework 4.7+). +- **Aspose.OCR for .NET** – تثبيت عبر NuGet: `Install-Package Aspose.OCR`. +- ملف فيديو (MP4 يعمل بشكل ممتاز). +- طريقة لفك تشفير إطارات الفيديو – العرض التجريبي يستخدم طريقة placeholder، لكن يمكنك ربط FFmpeg أو OpenCV أو أي مكتبة تُعيد كائنات `Bitmap`. + +> **نصيحة احترافية:** إذا كنت على Windows، حزمة `System.Drawing.Common` تعمل جيدًا مع `Bitmap`. على Linux/macOS ستحتاج إلى تبعية `libgdiplus` الأصلية. + +## الخطوة 1 – استخراج إطارات من الفيديو + +العقبة الأولى هي تحويل الصورة المتحركة إلى صور ثابتة. الطريقة `GetVideoFrames` أدناه تركت فارغة عمدًا؛ استبدلها بالمفكك المفضل لديك. إليك مخططًا سريعًا باستخدام FFmpeg‑Core (فقط لتوضيح شكل البيانات): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **لماذا هذا مهم:** استخراج الإطارات يوفّر لمحرك OCR صورة ثابتة للعمل عليها، مما يحسّن الدقة بشكل كبير مقارنةً بمحاولة القراءة مباشرةً من تدفق الفيديو. + +## الخطوة 2 – إعداد VideoOcrProcessor + +الآن بعد أن لدينا تسلسلًا من كائنات `Bitmap`، يمكننا تمريرها إلى Aspose.OCR. يتيح لنا `VideoOcrProcessor` تعريف **منطقة الاهتمام (ROI)** – مثالي للترجمات التي عادةً ما تكون في أعلى أو أسفل الإطار. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **لماذا نحدّ الـ ROI؟** بتجاهل باقي الصورة نقلل الضوضاء، نقلل زمن المعالجة، ونتجنب الإيجابيات الزائفة من الرسومات الخلفية. + +## الخطوة 3 – تشغيل OCR على تسلسل الإطارات + +مع جاهزية المعالج، إطعام الإطارات يصبح سطرًا واحدًا. طريقة `Process` تُعيد مجموعة من كائنات `OcrResult`، كل منها يحتوي على النص المعترف به للإطار المقابل. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **ما الذي يحدث خلف الكواليس؟** Aspose.OCR يُعيد تطبيع كل bitmap داخليًا، يُشغّل مُعرّفًا قائمًا على الشبكات العصبية، ثم يُجري معالجة لاحقة لتحسين علامات الترقيم وفواصل الأسطر. + +## الخطوة 4 – عرض النص المستخرج + +أخيرًا، نُكرّر النتائج ونطبع كل سطر ترجمة. يمكنك أيضًا كتابة النتائج إلى ملف SRT، قاعدة بيانات، أو تمريرها إلى خدمة ترجمة. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### مثال كامل يعمل + +دمج كل ما سبق ينتج برنامج console مستقل: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**الناتج المتوقع (عينة)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +إذا واجه OCR صعوبة مع إطار معين، ستظهر سلسلة فارغة – وهذا إشارة لتعديل الـ ROI أو زيادة معدل استخراج الإطارات. + +## المشكلات الشائعة وكيفية إصلاحها + +| المشكلة | لماذا يحدث | الحل | +|-------|----------------|-----| +| **حروف غير مفهومة** | إطارات منخفضة الدقة أو ضغط عالي | استخراج الإطارات بمعدل بت أعلى، أو تكبير الـ bitmap قبل OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **عدم إرجاع نص** | الـ ROI لا يغطي شريط الترجمة فعليًا | تحقق من إحداثيات المستطيل (استخدم أداة لقطة شاشة للقياس). | +| **عنق زجاجة الأداء** | معالجة كل إطار بـ 30 fps تُعد مبالغة | خفض العينة إلى 1‑2 fps لمعظم تدفقات الترجمات؛ لا يزال بإمكانك التقاط كل تغيير في الترجمة. | +| **FFmpeg غير موجود** | `ffmpeg.exe` غير موجود في `PATH` | قدّم المسار الكامل في `ProcessStartInfo.FileName` أو ثبّت FFmpeg عالميًا. | + +## توسيع الحل + +- **تصدير إلى SRT** – دمج الطوابع الزمنية مع نص OCR وكتابة ملف SubRip. +- **دعم متعدد اللغات** – ضبط `ocrProcessor.Language = OcrLanguage.Spanish` (أو أي لغة مدعومة). +- **معالجة في الوقت الفعلي** – تمرير الإطارات مباشرةً من تدفق مباشر بدلاً من القراءة من القرص. + +كل هذه الاختلافات لا تزال تدور حول الأفكار الأساسية لـ **extract frames from video**, **read text from video**, و **extract text from mp4**. + +## الخلاصة + +لقد استعرضنا للتو سير عمل كامل للـ **video subtitle ocr** باستخدام C#. من خلال استخراج إطارات الفيديو، تركيز OCR على شريط الترجمة، وتكرار النتائج، يمكنك بثقة **read text from video** للملفات مثل MP4. الكود جاهز للنسخ واللصق، والتصميم المعياري يتيح لك استبدال أي مُفكك إطارات تفضله. + +ما الخطوة التالية؟ جرّب تصدير النتائج إلى ملف SRT، جرب أحجام ROI مختلفة، أو مرّر الترجمات إلى واجهة برمجة تطبيقات ترجمة للحصول على تسميات متعددة اللغات. السماء هي الحد عندما تتقن أساسيات استخراج النص من الفيديو. + +برمجة سعيدة، ولتظل ترجماتك دائمًا واضحة كالكريستال! + +## ما الذي يجب أن تتعلمه بعد ذلك؟ + +الدروس التالية تغطي مواضيع ذات صلة وثيقة تبني على التقنيات التي تم توضيحها في هذا الدليل. كل مورد يتضمن أمثلة كود كاملة مع شروحات خطوة بخطوة لمساعدتك على إتقان ميزات API إضافية واستكشاف نهج تنفيذ بديلة في مشاريعك الخاصة. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/chinese/net/ocr-configuration/_index.md index 130a84dce..635b33967 100644 --- a/ocr/chinese/net/ocr-configuration/_index.md +++ b/ocr/chinese/net/ocr-configuration/_index.md @@ -59,7 +59,8 @@ weight: 24 ### [使用语言选择进行 OCR 图像识别的 OCROperation](./ocr-operation-with-language-selection/) 利用 Aspose.OCR for .NET 的强大 OCR 功能,流畅地从图像中提取文本。 ### [使用列表进行 OCR 图像识别的 OCROperation](./ocr-operation-with-list/) -发挥 Aspose.OCR for .NET 的潜力,轻松实现基于列表的 OCR 图像识别,提高应用的生产力和数据提取效率。 +发挥 Aspose.OCR for .NET 的潜力,轻松实现基于列表的 OCR 图像识别,提高应用的生产力和数据提取效率。 +### [在 C# 中获取 Aspose OCR 版本 – 完整指南](./get-aspose-ocr-version-in-c-complete-guide/) ### 常见使用场景 - **从扫描发票中提取文本**,实现自动化会计。 @@ -100,4 +101,4 @@ weight: 24 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/chinese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..2ac0c6dac --- /dev/null +++ b/ocr/chinese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: 使用简单代码片段在 C# 中获取 Aspose OCR 版本。了解如何使用 OcrEngine.GetVersion 检索 Aspose + OCR 库的版本。 +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: zh +og_description: 快速获取 C# 中的 Aspose OCR 版本。本教程准确演示如何使用 OcrEngine.GetVersion 检索 Aspose + OCR 库的版本。 +og_title: 获取 Aspose OCR 版本(C#)——完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: 在 C# 中获取 Aspose OCR 版本 – 完整指南 +url: /zh/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中获取 Aspose OCR 版本 – 完整指南 + +是否曾想过如何在 .NET 项目中 **获取 Aspose OCR 版本**?也许你在排查版本不匹配,或只是想记录生产环境中运行的库的确切构建版本。无论出于何种原因,你都来对地方了。 + +在本教程中,我们将演示一个小巧、独立的 C# 程序,调用 `OcrEngine.GetVersion()` 并打印结果。结束时,你不仅会知道 *如何* 获取版本,还会明白在升级 **Aspose OCR library** 时,检查版本为何能帮你避免许多麻烦。 + +## 你将学到 + +- 将 Aspose.OCR NuGet 包添加到 C# 项目中 +- 使用 `OcrEngine.GetVersion()` 方法(**ocrengine getversion** 入口点) +- 处理可能的异常并验证输出 +- 将代码片段扩展到实际场景,如日志记录或条件功能开关 + +无需任何 OCR 经验——只要具备基本的 C# 和 Visual Studio(或你喜欢的 IDE)使用经验即可。让我们开始吧。 + +--- + +## 第一步:设置项目并引入 Aspose OCR 库 + +在调用任何 OCR 相关 API 之前,需要在项目中引用 **Aspose OCR library**。 + +1. 打开终端或 Visual Studio 中的 Package Manager Console。 +2. 运行以下命令以安装最新的稳定版本: + +```bash +dotnet add package Aspose.OCR +``` + +> **专业提示:** 如果你针对的是 .NET Framework 而非 .NET Core,请使用 NuGet 包管理器 UI,并选择与你运行时匹配的版本。该包包含我们后面会使用的 `OcrEngine` 类。 + +### 为什么这很重要 + +安装包后,磁盘上的程序集版本可能与运行时库报告的版本不同。通过代码查询版本可以确保读取到 CLR 实际加载的构建版本,这对调试和合规审计至关重要。 + +--- + +## 第二步:编写最小代码以 **获取 Aspose OCR 版本** + +创建一个新控制台应用(`dotnet new console -n OcrVersionDemo`),并用以下内容替换默认的 `Program.cs`: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**每部分说明** + +- `using Aspose.OCR;` 将 OCR 命名空间引入作用域,使我们能够调用 `OcrEngine`。 +- `OcrEngine.GetVersion()` 是 **ocrengine getversion** 静态方法,返回类似 `"24.5.7"` 的字符串。 +- 将调用包装在 `try/catch` 块中,可防止运行时意外——例如目标机器上找不到本机二进制文件。 +- 插值字符串 `$"Aspose OCR version: {version}"` 打印出一行清晰、易读的结果。 + +### 预期输出 + +在项目文件夹内运行 `dotnet run`,你应该会看到类似如下的输出: + +``` +Aspose OCR version: 24.5.7 +``` + +如果库无法加载,错误分支会输出简洁的提示信息,帮助你快速定位问题。 + +--- + +## 第三步:验证版本是否与 NuGet 包一致 + +很多人会默认安装的 NuGet 版本就是运行时使用的版本,但环境因素可能导致差异。为再次确认: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +运行此额外代码片段会打印类似: + +``` +Assembly file version: 24.5.7.0 +``` + +如果两个值不一致,可能是从全局程序集缓存(GAC)或旧的构建文件夹加载了旧 DLL。此时请执行 `dotnet clean` 并重新构建。 + +--- + +## 第四步:将版本检查写入生产日志 + +真实项目通常不会仅在控制台打印,而是写入日志文件或遥测系统。下面是使用 `Microsoft.Extensions.Logging` 的快速示例: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +现在版本信息会出现在结构化日志中,后续可以通过 `{Version}` 轻松过滤。该模式在你有多个微服务,各自可能加载不同 OCR DLL 时尤为实用。 + +--- + +## 常见问题与边缘情况 + +### 如果 `GetVersion()` 返回空字符串怎么办? + +这通常表示安装损坏或缺少本机依赖。请重新安装 NuGet 包,并确保 `Aspose.OCR.Native.dll`(或相应平台的二进制文件)与可执行文件位于同一目录。 + +### 该方法在 .NET Core 2.0 上可用吗? + +可以,**Aspose OCR** 支持 .NET Standard 2.0 及以上,因此任何实现该标准的 .NET Core 版本都能调用 `OcrEngine.GetVersion()`。发布自包含应用时,请确保引用正确的运行时标识符(`win-x64`、`linux-x64` 等)。 + +### 能在没有许可证文件的情况下获取版本吗? + +完全可以。`GetVersion()` **不需要** 许可证,它仅返回库的构建号。不过,如果在没有有效许可证的情况下尝试执行 OCR,会抛出运行时异常。因此,代码片段中的 `try/catch` 能将版本检查与实际 OCR 执行流程分离。 + +--- + +## 完整可运行示例(复制粘贴即用) + +下面是完整程序,可直接放入新建的控制台项目中。它包含可选的日志块,既能看到控制台输出,也能在结构化日志中看到相同信息。 + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +使用 `dotnet run` 运行,你会看到两行确认版本的输出,若将日志级别设为 `LogLevel.Debug`,还会多出一行调试信息。 + +--- + +## 结论 + +我们已经覆盖了在 C# 环境中 **获取 Aspose OCR 版本** 的全部步骤——从安装 **Aspose OCR library**、调用 **ocrengine getversion** 方法、处理错误,到将结果嵌入生产级日志。掌握这些技巧后,你可以可靠地验证应用使用的 OCR 构建,避免因版本不匹配导致的 bug,并轻松满足合规要求。 + +下一步?尝试将此版本检查与实际的 OCR 调用(`OcrEngine` → `RecognizeImage`)结合,并同时记录版本和识别结果。你也可以探索 **retrieve aspose version** 模式在其他 Aspose 产品(PDF、Slides、Cells)中的使用,以保持整个套件同步。 + +祝编码愉快,愿你的 OCR 流程保持锋利! + +## 接下来你可以学习什么? + +以下教程围绕本指南中演示的技术,提供更深入的案例和替代实现方式,每篇都包含完整可运行的代码示例和逐步说明,帮助你掌握更多 API 功能。 + +- [如何使用 Aspose.OCR for .NET 获取 OCR 结果](/ocr/english/net/text-recognition/get-recognition-result/) +- [使用 Aspose.OCR 在 C# 中提取图像文字并选择语言](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [如何在 Aspose.OCR for .NET 中使用 List 批量 OCR 图像](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/chinese/net/ocr-optimization/_index.md index 48aeacf55..b974c93c0 100644 --- a/ocr/chinese/net/ocr-optimization/_index.md +++ b/ocr/chinese/net/ocr-optimization/_index.md @@ -72,6 +72,9 @@ weight: 25 ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) 释放 Aspose.OCR for .NET 的潜能。通过本综合一步一步的指南,轻松将多页 OCR 结果保存为文档。 +### [Aspose OCR C# 示例 – 启用 GPU、设置内存限制并处理 TIF 图像](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +演示如何在 C# 中启用 GPU 加速、限制内存使用并处理 TIF 格式图像的 OCR 操作。 + ## 常见问题 **Q: 我可以从包含多种语言的图像文件中提取文本吗?** diff --git a/ocr/chinese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/chinese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..ae6acfc32 --- /dev/null +++ b/ocr/chinese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# 示例,展示如何设置 GPU 内存限制、加载图像进行 OCR 并识别 TIF 文件中的文本,附完整代码和技巧。 +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: zh +og_description: 学习完整的 Aspose OCR C# 示例:启用 GPU、设置 GPU 内存限制、加载图像进行 OCR 并识别 TIF 文件中的文本。完整代码已包含。 +og_title: Aspose OCR C# 示例 – GPU 加速、内存限制与 TIF 处理 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# 示例 – 启用 GPU,设置内存限制并处理 TIF 图像 +url: /zh/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# 示例 – 启用 GPU、设置内存限制并处理 TIF 图像 + +有没有想过在处理巨大的 TIFF 扫描时,如何让 **Aspose OCR C# 示例** 代码发挥最大的性能?你并不孤单。在许多实际项目中——比如数字化档案或从高分辨率收据中提取数据——瓶颈并不是 OCR 算法本身,而是硬件利用率。 + +事实是:Aspose OCR 支持 GPU 加速,但你必须明确告诉它可以使用多少内存,加载正确的图像类型,最后从 .tif 文件中提取识别的文本。本教程将逐步演示从安装 SDK 到微调 GPU 设置的每一步,让你在不耗尽 GPU RAM 的情况下,以闪电般的速度运行 OCR。 + +我们还会穿插一些 “如果…” 场景——比如处理多页 TIFF 或在没有 GPU 时回退到 CPU——帮助你构建一个稳健的解决方案,而不是一次性代码片段。 + +## 您需要的准备 + +在开始之前,请确保您的机器上具备以下条件: + +| 前置条件 | 为什么重要 | +|--------------|----------------| +| **.NET 6 SDK**(或更高) | Aspose OCR 目标为 .NET Standard 2.0+,任何近期的 .NET 版本均可。 | +| **Aspose.OCR NuGet 包** (`Install-Package Aspose.OCR`) | 提供 `OcrEngine`、`GpuSettings` 等核心类库。 | +| **CUDA 11+**(NVIDIA)**或 ROCm 5+**(AMD) | GPU 加速所必需;SDK 会在运行时检查兼容的驱动。 | +| **至少 2 GB VRAM 的 GPU**(我们将上限设为 2048 MB) | 内存不足时,引擎会静默回退到 CPU。 | +| **一张高分辨率 TIFF 图像**,是你想要处理的对象 | Aspose OCR 能读取几乎所有光栅格式,但 TIF 是扫描件的常用格式。 | +| Visual Studio 2022(或你喜欢的任意编辑器) | 用于构建和调试 C# 项目。 | + +如果缺少上述任意项,代码仍能编译,但你将看不到我们追求的性能提升。 + +## 第一步:创建 Aspose OCR C# 示例引擎 + +每个 **Aspose OCR C# 示例** 的第一步都是实例化 OCR 引擎。把 `OcrEngine` 想象成电影导演——它负责从图像加载到文本提取的全部流程。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **小贴士:** 如果你计划连续处理多张图像,建议保持单个 `OcrEngine` 实例存活。每张图像重新创建会产生额外开销,往往超过 OCR 本身的耗时。 + +## 第二步:设置 GPU 内存限制(并启用加速) + +接下来是经常让人卡住的环节:**设置 GPU 内存限制**。默认情况下,Aspose OCR 会尝试占用尽可能多的显存,这在共享工作站上可能会导致其他应用被饿死。`GpuSettings` 对象可以让你限定分配量。 + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### 为什么要设置内存限制? + +- **稳定性:** 防止在处理超大图像时出现内存不足崩溃。 +- **共存性:** 让其他 GPU 密集型应用(例如 TensorFlow 模型)能够并行运行。 +- **可预测性:** 使性能测试可复现,因为 GPU 不会因内存争用而开始换页。 + +如果省略 `MemoryLimitMb`,Aspose 将根据需要分配内存,这在专用推理服务器上可能没问题,但在开发者笔记本上就很危险。 + +## 第三步:加载 OCR 图像 + +加载正确的文件格式是下一关键步骤。`OcrImage.FromFile` 方法会自动检测图像类型,但仍需确认文件是否存在以及它是否是受支持的 TIFF 变体(例如 LZW‑压缩或 CCITT‑G4)。 + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### 处理多页 TIFF + +如果你的 TIFF 包含多页,Aspose OCR 默认只读取第一页。要处理全部页面,可以遍历 `image.Pages`(在新版 SDK 中可用),并将每页分别送入引擎。 + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +上面的代码演示了一个 **加载 OCR 图像** 的模式,既适用于单页文件,也适用于多页文件。 + +## 第四步:从 TIF(或任意光栅图)识别文本 + +图像已经在内存中后,我们让 Aspose 开始工作。`Recognize` 方法返回一个 `OcrResult`,其中包含纯文本、置信度分数,甚至还有需要时的边界框信息。 + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### 为什么 TIF 表现良好 + +- **无损压缩:** TIFF 通常存储原始像素数据,为 OCR 引擎提供最高保真度。 +- **多种色彩空间:** Aspose 能直接处理灰度、RGB,甚至 CMYK TIFF,无需额外转换代码。 + +如果需要切换语言包(例如法语或日语),在调用 `Recognize` 前设置 `ocrEngine.Settings.Language = "fr"` 即可。 + +## 第五步:显示识别的文本 + +最后,我们将文本输出到控制台。在实际应用中,你可能会把结果写入数据库、JSON 文件,或将字符串传递给下游的 NLP 流程。 + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### 预期输出 + +在一张清晰、300 dpi 的打印页扫描上运行程序,通常会得到类似如下的结果: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +如果图像模糊或 GPU 内存限制设置过低,可能会出现乱码或结果被截断。将 `MemoryLimitMb` 设置低于图像占用的显存(例如 6000×8000 像素的 TIFF 大约需要 1 GB)会导致引擎自动回退到 CPU。 + +## 完整可运行示例 + +下面是完整的、可直接运行的程序。复制粘贴到新的 Console App 项目中,将 `YOUR_DIRECTORY/large_photo.tif` 替换为你自己的 TIFF 路径,然后按 **F5** 运行。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### 快速检查清单 + +- ✅ **Aspose OCR C# 示例** 编译无误。 +- ✅ **GPU 已启用**(`Enable = true`)。 +- ✅ **GPU 内存限制** 设置为 2048 MB。 +- ✅ **图像已从 TIF 文件加载**。 +- ✅ **文本已识别并打印**。 + +## 常见陷阱及规避方法 + +| 症状 | 可能原因 | 解决方案 | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | 未安装 CUDA 运行时或版本不匹配。 | 安装与驱动匹配的 CUDA 11.x(或 12.x)。 | +| OCR 返回空字符串 | 图像过暗或 DPI < 150。 | 使用 `image.AdjustContrast()` 预处理,或将分辨率重采样至 300 dpi。 | +| GPU 内存溢出崩溃 | `MemoryLimitMb` 对图像而言过低。 | 提高限制或使用 `image.Crop` 将图像切块。 | +| `Unsupported image format` 错误 | TIFF 使用了罕见压缩(如 JPEG‑2000)。 | 先用 ImageMagick 将 TIFF 转换为受支持的格式再进行 OCR。 | + +## 扩展演示 + +有了稳固的 **aspose ocr c# example**,你可以进一步探索: + +- **批量处理:** 遍历文件夹中的 TIF,分别将结果写入 `.txt` 文件。 +- **语言包:** `ocrEngine.Settings.Language = "es"` 可切换到西班牙语,或加载自定义词典。 +- **边界框:** 使用 `ocrResult.Regions` 获取每个单词的坐标——对脱敏工具非常有用。 +- **CPU 回退:** 将 GPU 代码块包裹在 try/catch 中;若失败,设置 `ocrEngine.Settings.Gpu.Enable = false` 并重新尝试。 + +这些扩展保持核心模式不变,同时为特定需求提供了额外价值。 + +## 接下来该学习什么? + +以下教程与本指南紧密相关,帮助你进一步掌握 API 功能并探索在项目中的其他实现方式。 + +- [使用 Aspose.OCR .NET 提取图像文字](/ocr/english/net/image-and-drawing-recognition/) +- [使用 Aspose.OCR for .NET 进行 OCR 优化](/ocr/english/net/ocr-optimization/) +- [使用 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/net/skew-angle-calculation/_index.md b/ocr/chinese/net/skew-angle-calculation/_index.md index b1dbc548a..a9c1bf0a9 100644 --- a/ocr/chinese/net/skew-angle-calculation/_index.md +++ b/ocr/chinese/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ url: /zh/net/skew-angle-calculation/ 释放 Aspose.OCR for .NET 的强大功能,这是一种强大的图像识别解决方案。了解如何轻松计算倾斜角度。 ### [OCR 图像识别中根据 URI 计算倾斜角度](./calculate-skew-angle-from-uri/) 探索 Aspose.OCR for .NET,轻松计算 OCR 图像识别中的倾斜角度。精准高效地增强您的项目。 +### [OCR 旋转文档教程 – 自动倾斜与旋转修复(C#)](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/chinese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..65d725ae7 --- /dev/null +++ b/ocr/chinese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose OCR 在 C# 中的 OCR 旋转文档教程,展示如何自动校正倾斜并检测旋转。一步一步学习完整代码。 +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: zh +og_description: OCR 旋转文档教程教您如何使用 Aspose OCR 在 C# 中自动纠正倾斜并检测旋转。请遵循完整指南。 +og_title: OCR 旋转文档教程 – C# 自动去倾斜与旋转修正 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR 旋转文档教程 – C# 自动去倾斜与旋转修正 +url: /zh/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 旋转文档教程 – C# 开发者完整指南 + +是否曾在扫描的表单横向或倾斜时偶然看到 **ocr rotated document tutorial**?你并不孤单。这些歪斜的图像会破坏干净的文本提取,但好消息是 Aspose OCR 可以自动为你校正。 + +在本分步指南中,我们将实例化一个 `OcrEngine`,开启 **automatic skew correction** 和 **auto detect rotation**,对旋转的图像运行引擎,并打印出干净的文本。结束时,你将明确每个设置的作用,了解如何针对特殊情况进行微调,并拥有一个可直接运行的 C# 程序。 + +## 你将学到 + +* 如何在 .NET 项目中安装和引用 **Aspose OCR**。 +* 为什么启用 `AutoCorrectSkew` 和 `AutoDetectRotation` 是实现可靠 **ocr rotated document tutorial** 的关键。 +* 如何加载任何图像(JPG、PNG、TIFF),让引擎完成繁重的工作。 +* 处理多页 PDF、低分辨率扫描以及自定义语言包的技巧。 + +> **先决条件:** Visual Studio 2022(或任何 C# IDE)、.NET 6+ 运行时,以及有效的 Aspose OCR 许可证(或免费试用)。无需先前的 OCR 经验。 + +--- + +## 第一步 – 安装 Aspose OCR 并设置项目 + +首先,获取 NuGet 包: + +```bash +dotnet add package Aspose.OCR +``` + +> **小贴士:** 如果使用试用许可证,请将 `Aspose.OCR.lic` 文件放在可执行文件同一文件夹下,或通过代码注册:`License license = new License(); license.SetLicense("Aspose.OCR.lic");`。 + +创建一个新的控制台应用程序: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +现在,你已经为我们的 **ocr rotated document tutorial** 准备了一个干净的起点。 + +## 第二步 – 初始化 OCR 引擎 + +引擎是整个过程的核心。可以把它看作是文本提取的瑞士军刀;你只需告诉它需要启用哪些功能。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**为什么要这样设置?** +* `AutoCorrectSkew` 分析字符的基线并将图像旋转到足以使行水平的程度。 +* `AutoDetectRotation` 检查整体方向(0°、90°、180°、270°),如果页面颠倒则翻转。若不启用,它会把 “pɹᴉʍ” 读取为 “word”。 + +## 第三步 – 加载要处理的图像 + +Aspose OCR 支持任何常见的光栅图像格式。将占位路径替换为实际的旋转表单所在位置。 + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **特殊情况:** 如果收到多页 TIFF,请使用 `OcrImage.FromMultiPageTiff(filePath)` 并遍历 `image.Pages`。 + +## 第四步 – 运行识别 + +现在引擎开始工作。它会先校正图像(得益于我们的倾斜/旋转标志),随后提取字符。 + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +如果需要除英语之外的语言支持,请在调用 `Recognize` 之前进行设置: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## 第五步 – 输出识别文本 + +最后,将干净的文本输出到控制台——或重定向到文件、数据库,任意符合工作流的方式。 + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**预期输出**(假设示例图像包含 “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +请注意,即使源图像旋转了 90° 且略有倾斜,文本仍能正确显示。 + +--- + +## 处理常见陷阱 + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **空白输出** | 倾斜校正被禁用或图像过暗。 | 启用 `AutoCorrectSkew`(已开启),并通过 `image.AdjustContrast(1.2)` 提高图像对比度。 | +| **乱码字符** | 语言设置错误。 | 将 `ocrEngine.Settings.Language` 设置为与文档语言相匹配。 | +| **大 PDF 性能延迟** | 引擎顺序处理每页。 | 对 `image.Pages` 使用 `Parallel.ForEach`,利用多核 CPU。 | +| **许可证异常** | 试用期已到。 | 获取永久许可证或在试用限制内使用(每次运行最多 5 页)。 | + +--- + +## 稳健 OCR 旋转文档教程的专业技巧 + +* **批量处理:** 将整个流程封装在接受文件夹路径的方法中,遍历每个图像,并将结果写入 `.txt` 文件。 +* **预处理:** 有时嘈杂的扫描在识别前使用 `image.Denoise()` 会有帮助。 +* **后处理:** 使用正则表达式清理常见的 OCR 误读,例如仅在字母之间时将 “0” 替换为 “O”。 +* **日志记录:** Aspose OCR 提供 `ocrEngine.Logger`——将其连接到文件日志记录器,以捕获低置信度分数的警告。 + +## 完整、可直接运行的代码 + +将以下代码保存为控制台项目中的 `Program.cs`。它包含所有步骤、注释以及一个用于批量处理的小助手。 + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +运行它: + +```bash +dotnet run +``` + +你应该会在控制台看到已清理的文本,证明我们的 **ocr rotated document tutorial** 能端到端工作。 + +--- + +## 结论 + +现在你拥有完整的 **ocr rotated document tutorial**,它使用 Aspose OCR 在 C# 中自动校正倾斜、检测旋转并提取干净的文本。关键要点是?启用 `AutoCorrectSkew` **和** `AutoDetectRotation` 能将极度倾斜的扫描件转化为可读的输出,仅需几行代码。 + +接下来,你可以扩展为批处理任务、集成语言包,或将结果输送到下游分析管道。想进一步了解 **automatic skew correction** 吗?查看 Aspose 的图像预处理 API,或尝试为嘈杂扫描设置自定义阈值。 + +关于处理 PDF、多页 TIFF 或与 Azure Functions 集成有疑问吗?留下评论,祝编码愉快! + +## 接下来你应该学习什么? + +以下教程涵盖与本指南技术密切相关的主题。每个资源都提供完整的可运行代码示例和分步说明,帮助你掌握更多 API 功能并在项目中探索替代实现方式。 + +- [ocr 文档模式 – OCR 图像识别中的检测区域模式](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [使用 Aspose.OCR 的语言选择提取图像文本 C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR 教程 – 光学字符识别](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/chinese/net/text-recognition/_index.md index 9a3154c26..a3f8a93b2 100644 --- a/ocr/chinese/net/text-recognition/_index.md +++ b/ocr/chinese/net/text-recognition/_index.md @@ -53,11 +53,22 @@ url: /zh/net/text-recognition/ 使用 Aspose.OCR 增强您的 .NET 应用程序,以实现高效的图像文本识别。探索 OCR 检测区域模式以获得精确结果。 ### [OCR图像识别中识别PDF](./recognize-pdf/) 使用 Aspose.OCR 释放 .NET 中 OCR 的潜力。轻松从 PDF 中提取文本。立即下载以获得无缝集成体验。 +### [使用 Aspose OCR 对 PDF 进行 OCR – 完整 C# 指南](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +本指南详细演示如何使用 Aspose.OCR 在 .NET 中通过 C# 对 PDF 文件执行 OCR,提取文本并集成到应用程序。 ### [OCR图像识别中的识别表](./recognize-table/) 通过我们关于 OCR 图像识别中表格识别的综合指南,释放 Aspose.OCR for .NET 的潜力。 +### [使用 Aspose OCR 对图像进行 OCR – 印地语指南](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +本教程指导您使用 Aspose OCR 对图像进行 OCR 处理,并提供印地语语言支持的完整步骤。 +### [如何使用 Aspose:将图像转换为带 OCR 的 HTML](./how-to-use-aspose-convert-image-to-html-with-ocr/) +本教程演示如何使用 Aspose.OCR 将图像转换为 HTML,并在其中嵌入 OCR 识别的文本。 +### [使用 C# 对图像进行 OCR 并检测拼写错误的单词](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +本教程展示如何使用 Aspose.OCR 在 .NET 中对图像进行 OCR,并识别并标记拼写错误的单词。 +### [使用 C# 对视频字幕进行 OCR – 完整指南](./video-subtitle-ocr-in-c-complete-guide/) +本完整指南展示如何使用 Aspose.OCR 在 C# 中对视频字幕进行 OCR,提取文本并集成到应用程序。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/chinese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..177da18f4 --- /dev/null +++ b/ocr/chinese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: 如何使用 Aspose 将图像转换为 HTML 并在 C# 中提取图像中的文本。快速学习将图像生成 HTML 以及将图像 OCR 为 HTML。 +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: zh +og_description: 如何使用 Aspose 将图像转换为 HTML、从图像中提取文本,并在 C# 中使用 OCR 从图像生成 HTML。请阅读完整指南。 +og_title: 如何使用 Aspose:将图像转换为带 OCR 的 HTML +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 如何使用 Aspose:将图像转换为带 OCR 的 HTML +url: /zh/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Aspose:将图像转换为带 OCR 的 HTML + +是否曾想过 **how to use Aspose** 将扫描的图片转换为整洁的 HTML?也许你有一页杂志、收据或手写笔记,并且需要保留文本和布局以用于网页发布。好消息是,你不需要编写自定义解析器或与底层图像处理搏斗——Aspose.OCR 为你完成繁重的工作。 + +在本教程中,我们将逐步演示一个 **complete, runnable example**,展示如何使用 C# 中的 Aspose OCR 库 **convert image to HTML**、**extract text from image** 和 **generate HTML from image**。完成后,你将拥有一个小型控制台应用程序,生成的 HTML 文件保留原始页面布局,可直接嵌入任何网站。 + +## 前置条件 + +- **.NET 6.0 SDK** 或更高版本(代码在 .NET Core 和 .NET Framework 上均可运行)。 +- **Visual Studio 2022**(或你喜欢的任何编辑器)。 +- **Aspose.OCR for .NET** – 通过 NuGet 安装:`dotnet add package Aspose.OCR`。 +- 要转换的图像文件(JPEG/PNG),例如 `magazine_page.jpg`。 + +无需额外的配置文件;库已自带进行 OCR 和 HTML 布局生成所需的一切。 + +## 步骤 1:设置项目并添加 Aspose.OCR + +首先,创建一个新的控制台项目并引入 Aspose OCR 包。 + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** 如果你使用 Visual Studio,只需右键单击项目 → *Manage NuGet Packages* → 搜索 **Aspose.OCR** 并安装。此步骤可确保你能够 **ocr image to html** 而不会缺少引用。 + +## 步骤 2:初始化 OCR 引擎 + +该过程的核心是 `OcrEngine` 类。可以把它看作读取图片并决定输出结果的大脑。 + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +这里我们实例化 `OcrEngine`。对于免费版,你无需传递任何凭证;库会使用内置的识别模型。 + +## 步骤 3:加载源图像 + +接下来,将引擎指向你想要处理的文件。Aspose 提供了便利的 `OcrImage.FromFile` 方法,支持大多数图像格式。 + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +将 `YOUR_DIRECTORY` 替换为图像所在的绝对或相对路径。如果图像与可执行文件在同一文件夹,只需使用 `"magazine_page.jpg"` 即可。 + +## 步骤 4:识别并请求带布局的 HTML + +这是本教程的核心。通过传入 `OutputFormat.HtmlWithLayout`,我们告诉 Aspose **generate HTML from image**,同时保留文本块、图像和表格的原始位置。 + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text` 属性现在包含完整的 HTML 文档。如果只需要纯文本,可以使用 `OutputFormat.Text`,但我们专注于 **convert image to html**,并保持布局精度。 + +## 步骤 5:保存 HTML 文件 + +最后,将 HTML 字符串写入磁盘。这会生成一个可直接在任意浏览器中打开的可用文件。 + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +运行程序后会生成 `magazine.html`。打开它,你会看到原始页面的文本位置与源图像完全一致——非常适合归档或网页发布。 + +## 完整可运行示例 + +下面是 **complete, copy‑paste‑ready** 程序。未省略任何部分,设置正确路径后即可编译运行。 + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### 预期输出 + +在浏览器中打开 `magazine.html` 时,你应看到类似如下的效果(为说明简化): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +具体的 `style` 属性会因原始图像而异,但结构保证 **extract text from image** 与 **generate html from image** 在一次无缝的步骤中完成。 + +## 常见问题与边缘情况 + +### 如果图像分辨率低怎么办? + +Aspose.OCR 在至少 **300 DPI** 的图像上表现最佳。如果文件模糊,可在将其送入 OCR 引擎前使用图像增强库(例如 ImageSharp)进行预处理。低质量会影响 **extract text from image** 的准确性以及生成的 HTML 布局的保真度。 + +### 我可以控制 OCR 的语言吗? + +是的。在调用 `Recognize` 之前设置 `OcrEngine` 的 `Language` 属性: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +这在处理非英文字符时可提升识别效果。 + +### 如何获取纯文本而不是 HTML? + +如果只需要原始字符串,将 `OutputFormat.HtmlWithLayout` 替换为 `OutputFormat.Text`。此时相同的 `recognitionResult.Text` 将仅包含提取的字符。 + +### 有办法将图像嵌入生成的 HTML 吗? + +Aspose.OCR 在使用 `OutputFormat.HtmlWithLayoutAndImages` 时可以将原始图像嵌入为 base‑64 数据 URI。当你希望生成单个不依赖外部资源的 HTML 文件时,这非常方便。 + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### 如何处理大批量文件? + +对于批量处理,可将逻辑包装在遍历文件路径列表的 `foreach` 循环中。复用同一个 `OcrEngine` 实例可减少开销,加速 **convert image to html** 流程。 + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## 生产环境代码提示 + +- **Dispose resources**:`OcrEngine` 和 `OcrImage` 都实现了 `IDisposable`。使用 `using` 语句包装,以及时释放本机内存。 +- **Error handling**:捕获 `IOException` 处理文件相关问题,捕获 `OcrException` 处理识别问题。 +- **Performance**:如果处理大量图像,考虑启用 **parallelism**(`Parallel.ForEach`),但要注意 CPU 使用率——OCR 对 CPU 负载较高。 +- **Logging**:集成日志记录器(例如 Serilog),捕获 OCR 置信度分数(`recognitionResult.Confidence`),用于质量监控。 + +## 结论 + +我们刚刚介绍了 **how to use Aspose** 将 **convert image to HTML**、**extract text from image** 和 **generate HTML from image** 的简明步骤。完整的代码示例展示了如何 **ocr image to html** 并保留布局,为任何文档数字化项目提供了坚实基础。 + +从这里你可能: + +- 尝试不同的 `OutputFormat` 选项以满足你的需求。 +- 将 HTML 输出与 CSS 框架结合,实现响应式样式。 +- 将提取的文本导入搜索索引或机器学习流水线。 + +动手试一试,调整设置,看看 Aspose 如何轻松将图片转换为可用于网页的内容。如果遇到任何问题,欢迎留言——祝编码愉快! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## 接下来该学习什么? + +以下教程涵盖与本指南紧密相关的主题,基于本教程展示的技术。每个资源都包含完整的可运行代码示例和逐步说明,帮助你掌握更多 API 功能并在项目中探索替代实现方案。 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/chinese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..75b5ec9b4 --- /dev/null +++ b/ocr/chinese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose.OCR 对图像执行 OCR 并提取图像中的文本。在一个 C# 示例中学习如何检测拼写错误并获取拼写建议。 +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: zh +og_description: 使用 Aspose.OCR 在 C# 中对图像执行 OCR 以提取文本,然后检测拼写错误并获取拼写建议。 +og_title: 在 C# 中对图像进行 OCR 并检测拼写错误的单词 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: 在 C# 中对图像执行 OCR 并检测拼写错误的单词 +url: /zh/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中对图像执行 OCR 并检测拼写错误的单词 + +有没有想过如何 **对图像执行 OCR** 而不抓狂?你并不是唯一的。无论是数字化旧信件、扫描收据,还是构建智能文档工作流,从图片中提取干净的文本都是第一道难关。好消息是?使用 Aspose.OCR,你可以在几分钟内搭建一个解决方案,而且还能 **检测拼写错误的单词** 并 **获取拼写建议**,一次完成。 + +在本教程中,我们将演示一个完整、可直接运行的 C# 控制台应用程序,它 **从图像提取文本**、运行英文拼写检查器,并将每个错误以及相应的纠正建议打印出来。阅读完毕后,你将清楚 **如何提取文本**、**如何调用拼写检查 API**,以及预期的控制台输出是什么样子。 + +## 你将构建的内容 + +- 加载包含拼写错误的位图(或 PNG)。 +- 使用 Aspose.OCR **对图像执行 OCR** 并获取原始字符串数据。 +- 初始化内置的英文拼写检查器。 +- **检测拼写错误的单词** 并 **获取每个单词的拼写建议**。 +- 将整洁的报告打印到控制台。 + +无需外部服务,无需繁琐的 HTTP 调用——只需一个 NuGet 包和几行代码。 + +## 前置条件 + +- .NET 6.0 SDK 或更高版本(代码同样适用于 .NET Framework 4.7+)。 +- Visual Studio 2022(或任意你喜欢的编辑器)。 +- Aspose.OCR for .NET NuGet 包(`Aspose.OCR`)。 +- 一张图片文件(`letter_with_typos.png`),放在项目可以引用的位置。 + +如果你从未使用过 Aspose,别担心——安装包就像运行下面的命令一样简单: + +```bash +dotnet add package Aspose.OCR +``` + +现在让我们深入实现细节。 + +## 第一步:创建项目并安装 Aspose.OCR + +创建一个新的控制台项目并引入 OCR 库: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +恢复完成后,打开 `Program.cs`。我们稍后会用完整的演示代码替换默认内容,但先来聊聊每个命名空间的作用。 + +- `Aspose.OCR` – 核心 OCR 引擎和图像处理。 +- `Aspose.OCR.SpellCheck` – 随库提供的拼写检查工具。 +- `System` – 标准 .NET 基础类(例如 `Console`)。 + +## 第二步:加载图像并对图像执行 OCR + +真正的工作是把图像喂给 OCR 引擎。Aspose.OCR 支持多种格式(PNG、JPEG、TIFF)。下面的代码片段完成了这项重活: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **为什么重要:** `OcrImage.FromFile` 抽象掉像素级细节,而 `OcrEngine.Recognize` 则运行训练好的神经模型,将可视字符转换为 Unicode。`ocrResult.Text` 属性现在保存了原始字符串——这正是你需要的 **从图像提取文本**。 + +> **小技巧:** 如果图像包含多种语言,可以在调用 `Recognize` 之前设置 `ocrEngine.Language = OcrLanguage.Multilingual;`。 + +## 第三步:初始化英文拼写检查器 + +Aspose.OCR 自带的拼写检查引擎开箱即用英文。初始化只需一行代码: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **为什么这一步至关重要:** OCR 输出可能包含误识别的字符(例如 “l” 与 “1”)或源文档本身的拼写错误。拼写检查器会扫描字符串,定位可疑词并提供替代方案。 + +## 第四步:检测拼写错误的单词并获取拼写建议 + +现在把 OCR 文本传给检查器: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` 是一个集合,每个条目包含错误单词以及可能的纠正数组。 + +## 第五步:输出结果 + +最后,遍历集合并打印出人类可读的报告: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### 预期的控制台输出 + +假设 `letter_with_typos.png` 包含以下句子: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +运行演示后会得到类似下面的输出: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +可以看到每个拼写错误都配有若干合理的修正——这正是构建用户友好纠正 UI 时所需要的。 + +## 完整可运行示例 + +下面是 **完整、可直接复制粘贴** 的程序。将 `YOUR_DIRECTORY` 替换为你的图片实际路径。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **需要考虑的边界情况** +> - **空图像:** 如果 OCR 引擎返回空字符串,`spellChecker.Check` 将返回空集合——不会崩溃。 +> - **非英文文本:** 将 `OcrLanguage.English` 替换为 `OcrLanguage.French`(或任何受支持的语言),即可 **检测其他语言的拼写错误**。 +> - **大文档:** 对于多页 PDF,需要遍历每页,执行 OCR,然后在拼写检查前聚合结果。 + +## 可视化概览(图片替代文字) + +![展示对图像执行 OCR、从图像提取文本,然后检测拼写错误并提供拼写建议的流程图](perform-ocr-on-image-flow.png) + +*上图展示了端到端的流水线:图像 → OCR 引擎 → 原始文本 → 拼写检查器 → 建议。* + +## 常见问题 & 专业技巧 + +| 问题 | 答案 | +|----------|--------| +| **是否需要互联网连接?** | 不需要。Aspose.OCR 完全本地运行,适合离线或安全环境。 | +| **拼写检查器的准确度如何?** | 使用约 15 万英文单词的词典并结合模糊匹配,能够捕获大多数常见错别字。 | +| **可以自定义词典吗?** | 可以。`SpellChecker.AddUserDictionary("custom.txt")` 允许加载领域专用词汇(例如产品名称)。 | +| **如果图像倾斜怎么办?** | OCR 引擎会自动检测方向,但对于顽固情况,你可以手动调用 `ocrEngine.ImagePreprocessing.Rotate(angle)`。 | +| **有没有办法在 UI 中高亮建议?** | 获得 `misspellings` 集合后,可将每个 `entry.Word` 映射回 `ocrResult.Text` 中的位置,并在 RichTextBox 或网页视图中下划线标记。 | + +## 结论 + +我们已经演示了 **如何对图像执行 OCR**、**从图像提取文本**,以及随后 **检测拼写错误的单词** 并 **获取拼写建议**——全部使用简洁的 C# 控制台应用。核心思路很简单:让 Aspose.OCR 完成字符识别的重活,再让其内置的拼写检查器清理输出。接下来,你可以把演示扩展为完整的文档处理服务,集成到 Web API,或嵌入桌面编辑器。 + +准备好下一步了吗?尝试切换语言为西班牙语,处理多页 PDF,或构建一个小型 WPF 前端,让用户点击单词接受建议。构建块已经就位——尽情实验吧。 + +如果在使用过程中遇到任何问题或有扩展想法,欢迎在下方留言。祝编码愉快! + +## 接下来你可以学习什么? + +以下教程与本指南紧密相关,帮助你进一步掌握 API 功能并探索在项目中的其他实现方式,每篇都包含完整可运行的代码示例和逐步解释。 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/chinese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..253808c12 --- /dev/null +++ b/ocr/chinese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose OCR 在 C# 中对图像执行 OCR。学习如何加载图像进行 OCR,并离线提取印地语文本,提供一步一步的代码示例。 +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: zh +og_description: 使用 Aspose OCR 在 C# 中对图像执行 OCR。本教程展示了如何加载图像进行 OCR 并离线提取印地语文本图像,提供完整的可运行代码。 +og_title: 在图像上执行 OCR – Aspose OCR 印地语指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: 使用 Aspose OCR 对图像进行 OCR – 印地语指南 +url: /zh/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在图像上执行 OCR – Aspose OCR(印地语指南) + +是否曾需要 **在图像上执行 OCR**,但不知道如何提取其中的印地语字符?你并不孤单——很多开发者在首次读取非拉丁文字时都会遇到这个难题。好消息是 Aspose OCR 让这变得相当轻松,而且完全可以离线完成。 + +在本指南中,我们将 **加载图像进行 OCR**,指向离线语言包,然后 **提取印地语文本图像** 数据,整个过程无需联网。完成后,你将拥有一个可直接运行的 C# 控制台应用,读取印地语收据并将文本打印到控制台。 + +## 你需要准备的环境 + +- **.NET 6.0** 或更高(代码同样适用于 .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet 包 + `dotnet add package Aspose.OCR` +- 包含 **离线印地语语言资源** 的文件夹(从 Aspose 门户下载) +- 一张包含印地语文字的图像文件,例如 `receipt_hindi.png` + +就这些——无需外部服务、无需 API 密钥,纯代码直达。 + +## 在图像上执行 OCR – 步骤实现 + +下面我们把整个过程拆分为七个清晰的步骤。每一步不仅说明 **做什么**,更解释 **为什么**。 + +### 步骤 1:创建 OCR 引擎实例 + +引擎是 Aspose OCR 的核心。实例化它后,你就可以访问后续要调整的所有设置。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **为什么?** +> 没有 `OcrEngine`,就没有对象可以调用 `Recognize`。把它想象成后面要扫描图片的“相机”。 + +### 步骤 2:指向离线资源文件夹 + +Aspose 提供可本地存放的语言包。设置 `ResourcesFolder` 告诉引擎去哪里寻找资源。 + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **提示:** +> 开发时使用绝对路径,生产环境再切换为相对路径或配置项。 + +### 步骤 3:强制离线模式 + +你可能会想,“真的需要关闭在线查询吗?” +如果你在防火墙后工作或希望结果可预期,请将 `UseOfflineResources` 设为 `true`。 + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **专业提示:** +> 将此标志保持为 `false` 会导致引擎下载额外数据,增加延迟并可能违反安全策略。 + +### 步骤 4:选择印地语作为识别语言 + +这里我们 **提取印地语文本图像**,通过告知引擎预期的语言来显著提升准确率。 + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **为何有效:** +> OCR 引擎使用特定语言的字符模型。锁定为印地语后,避免了在数十种脚本间猜测。 + +### 步骤 5:加载图像进行 OCR + +现在我们真正 **加载图像进行 OCR**。`OcrImage.FromFile` 方法将位图读取为引擎可理解的格式。 + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **常见陷阱:** +> 在 Windows 上使用正斜杠路径是可行的,但使用 `Path.Combine` 能让代码跨平台。 + +### 步骤 6:运行识别 + +所有准备就绪后,我们通过调用 `Recognize` **在图像上执行 OCR**。 + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **发生了什么?** +> 引擎扫描每个像素,将模式与印地语字形数据库匹配,并生成 Unicode 字符串。 + +### 步骤 7:输出识别结果 + +结果对象的 `Text` 属性保存了提取的字符串。我们只需将其写入控制台。 + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **预期输出:** +> 若 `receipt_hindi.png` 包含 “भुगतान सफल”,控制台将完整打印该行,保留所有变音符号。 + +## 加载图像进行 OCR – 准备资源 + +如果你想使用流而不是文件来喂给引擎,答案是肯定的。将 `OcrImage.FromFile` 替换为: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **为何使用流?** +> 流可以处理存储在数据库、云 Blob 或嵌入资源中的图像——非常适合可扩展服务。 + +## 提取印地语文本图像 – 处理边缘情况 + +1. **缺少语言包** – 若未找到印地语包,`Recognize` 会抛出异常。请使用 try/catch 包裹调用并记录友好提示。 +2. **低分辨率图像** – OCR 准确率在低于 300 dpi 时会下降。加载前先对图像进行预处理(如缩放、锐化)。 +3. **混合语言文档** – 可以启用多语言: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +这些调整能让你的 **在图像上执行 OCR** 过程在生产环境中更稳健。 + +## 运行完整示例 + +将以下代码保存为 `Program.cs`,替换占位路径后运行: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +执行 `dotnet run` 时,你应看到类似下面的输出: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +如果得到空字符串,请再次确认 **ResourcesFolder** 指向包含 `Hindi.traineddata` 的文件夹,并确保图像足够清晰。 + +## 结论 + +我们已经完整演示了如何使用 Aspose OCR **在图像上执行 OCR**,涵盖了从 **加载图像进行 OCR** 到 **提取印地语文本图像** 的全部离线流程。上面的可运行代码为你提供了坚实的基础,而关于流、错误处理以及多语言支持的技巧则帮助你将方案应用到真实项目中。 + +准备好下一步了吗?尝试切换语言为 **OcrLanguage.Tamil**,或从 Azure Blob 存储读取图像。你也可以实验 `ImagePreprocessing` 设置,以提升噪声收据的识别率。 + +有问题或遇到卡点?欢迎留言——祝编码愉快! + +![Perform OCR on image example + + +## 接下来该学习什么? + +以下教程与本指南紧密相关,帮助你进一步掌握 API 功能并探索替代实现方式: + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/chinese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..4c7bd1e36 --- /dev/null +++ b/ocr/chinese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose.OCR 对 PDF 执行 OCR 并将扫描的 PDF 转换为可搜索的 PDF。了解如何从 PDF 识别文本,并在几分钟内创建可搜索的 + PDF。 +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: zh +og_description: 对 PDF 执行 OCR 并立即生成可搜索的 PDF。本教程逐步演示如何使用 Aspose.OCR 从 PDF 中识别文本。 +og_title: 对 PDF 进行 OCR – 完整 C# 指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: 使用 Aspose.OCR 对 PDF 进行 OCR – 完整 C# 指南 +url: /zh/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose.OCR 对 PDF 执行 OCR – 完整 C# 指南 + +是否曾经想过 **如何对 PDF 执行 OCR**,却不想与数十个命令行工具斗争?你并不孤单。无论是数字化发票、归档旧报告,还是仅仅需要一个可搜索的扫描合同版本,将静态 PDF 转换为可搜索的内容都是改变游戏规则的关键。 + +在本指南中,我们将逐步演示 **如何使用 Aspose.OCR for .NET 将扫描的 PDF(甚至普通图像)创建为可搜索的 PDF**。完成后,你只需几行 C# 代码即可 **从 PDF 中识别文本**,并且了解每一步背后的原因,以便将该方案适配到自己的项目中。 + +> **快速要点:** 整个过程归结为三件事——初始化 OCR 引擎、提供源文件(PDF 或图像),以及保存可搜索的 PDF 输出。让我们开始吧。 + +--- + +## 你需要准备什么 + +在开始之前,请确保你拥有以下条件: + +| 前置条件 | 为什么重要 | +|--------------|----------------| +| **.NET 6.0+**(或 .NET Framework 4.6+) | Aspose.OCR 面向现代运行时;旧版本可能缺少 API 更新。 | +| **Aspose.OCR for .NET** NuGet 包 | 提供 `OcrEngine` 类和 PDF 处理工具。 | +| **有效的 Aspose 许可证**(或使用免费评估版) | 没有许可证会触发 30 天评估限制并出现水印。 | +| **需要转换为可搜索的扫描 PDF**(或图像文件) | 这是 OCR 的源文档。 | +| **Visual Studio 2022**(或任意 C# 编辑器) | 便于调试,但任何 IDE 都可使用。 | + +你可以使用以下 NuGet 命令安装库: + +```bash +dotnet add package Aspose.OCR +``` + +> **专业提示:** 若在 CI 流水线中使用,请将许可证文件加入构建产物,并在运行时加载,以避免硬编码路径。 + +--- + +## 在 Aspose.OCR 中执行 OCR – 环境搭建 + +我们首先需要一个全新的 `OcrEngine` 实例。可以把它想象成读取文档的大脑。 + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +为什么每次都要创建新实例?引擎会保存配置(如语言设置),这些配置可能因文档而异。每次运行时实例化可以保证一个干净的状态,避免作业之间的相互影响。 + +--- + +## 如何创建可搜索的 PDF – 配置密码(可选) + +如果你的 PDF 受密码保护,需要在引擎读取页面之前提供密码: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +在受保护的文件上跳过此步骤会抛出 `PdfPasswordException`。如果不确定文件是否受保护,请务必使用 try‑catch 包裹。 + +--- + +## 将扫描的 PDF 转换为可搜索 PDF – 加载源文件 + +Aspose.OCR 使用 `OcrImage` 抽象,可以包装 PDF、TIFF、JPEG 等。下面演示如何将扫描的 PDF 加载到内存中: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +在内部,`FromFile` 会将每一页解析为光栅图像,供 OCR 引擎处理。如果是多页 PDF,引擎会自动遍历每一页。 + +--- + +## 从 PDF 中识别文本 – 执行 OCR + +现在进入教程的核心:让引擎识别文本并输出可搜索的 PDF。 + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` 告诉引擎在原始扫描图像之上嵌入一个不可见的文本层。生成的 PDF 保留扫描的视觉保真度,同时实现完整的可搜索性——这正是合规审计所需的。 + +--- + +## 将图像转换为可搜索的 PDF – 保存结果 + +最后,将二进制数据写入磁盘: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary` 属性保存了原始 PDF 字节。如果你在构建 API,也可以直接将其流式返回给网页响应。 + +--- + +![展示 OCR 转换流程以创建可搜索 PDF 的示意图](https://example.com/ocr-flow.png "执行 OCR 于 PDF 的流程图") + +*图片替代文字:执行 OCR 于 PDF 的流程图,说明如何将扫描的 PDF 转换为可搜索的 PDF。* + +--- + +## 边缘情况与实用技巧 + +### 1. 大文件与内存管理 +如果处理的 PDF 大于 100 MB,考虑使用 `OcrEngineSettings.MemoryLimit` 来限制内存使用。此外,分批处理页面以避免 `OutOfMemoryException`。 + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. 语言支持 +默认情况下 Aspose.OCR 假设英文。若要识别其他语言,请设置 `Language` 属性: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. 多线程场景 +`OcrEngine` **不是**线程安全的。如果需要并行处理,请为每个线程创建独立的引擎实例。 + +### 4. 调试 OCR 准确度 +你可以从 `ocrResult` 中提取纯文本用于调试: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +如果输出出现乱码,可尝试调整 `PreprocessSettings`(例如去倾斜、去噪点)以提升质量。 + +### 5. 许可证注意事项 +使用评估版时,Aspose 会在输出 PDF 上添加水印。请在应用程序启动时尽早注册许可证: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## 完整工作示例 – 从头到尾 + +下面是完整、可直接运行的程序,已整合上述所有技巧。复制粘贴到新的控制台项目中即可使用。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**预期输出:** 运行后,控制台会显示确认文件位置的行。使用任意 PDF 查看器打开 `output.pdf`,尝试输入原始扫描中出现的词语。如果文字被高亮,说明你已经成功 **对 PDF 执行 OCR** 并创建了可搜索文档。 + +--- + +## 常见问题 + +**问:我可以用它将单张图片(PNG/JPEG)转换为可搜索的 PDF 吗?** +答:完全可以。将 `OcrImage.FromFile("input.pdf")` 替换为你的图像文件路径即可。引擎会对图像进行光栅化并嵌入 OCR 层。 + +**问:如果我的 PDF 同时包含扫描页和原生文本怎么办?** +答:引擎会在已有内容上叠加 OCR 文本,原生文本保持可选择,扫描页则变为可搜索。 + +**问:OCR 的准确率如何?** +答:准确率取决于源文件质量。干净的高分辨率扫描(>300 dpi)可达 >95 % 的准确率。对于噪声较大的文档,可在调用 `Recognize` 前启用 `PreprocessSettings`(去倾斜、去噪点)来提升效果。 + +--- + +## 后续步骤 – 扩展你的 OCR 工具箱 + +既然已经能够 **从 PDF 中识别文本** 并 **将扫描 PDF 转换为可搜索 PDF**,可以进一步探索以下主题: + +- **批量处理**:遍历文件夹中的 PDF,自动生成可搜索版本。 +- **文本提取**:使用 `ocrResult.Text` 将内容写入搜索索引(如 Elasticsearch)。 +- **自定义语言包**:从 Aspose 下载额外语言数据,以支持亚洲文字。 +- **PDF/A 合规**:结合 Aspose.PDF 与 OCR 输出,创建符合归档标准的 PDF。 + +这些都基于我们已覆盖的核心步骤,你已经具备了进一步扩展解决方案的能力。 + +--- + +## 小结 + +我们已经向你展示了 **如何使用 Aspose.OCR 对 PDF 执行 OCR**,将扫描的 PDF 转换为完整可搜索的 PDF,并且还介绍了将普通图像转换为可搜索 PDF 的方法。代码 + + +## 接下来该学习什么? + +以下教程涵盖了与本指南技术紧密相关的主题,帮助你进一步掌握 API 功能并在项目中探索替代实现方式,每篇资源均提供完整可运行的代码示例和逐步解释。 + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/chinese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..cd3a2ea14 --- /dev/null +++ b/ocr/chinese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: 视频字幕 OCR 教程,展示如何从视频中提取帧并使用 Aspose.OCR 读取 MP4 等视频文件中的文本。 +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: zh +og_description: 使用 Aspose.OCR 学习视频字幕 OCR。提取视频帧,读取视频中的文字,并在几分钟内从 MP4 中提取文本。 +og_title: C# 视频字幕 OCR – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: C# 视频字幕 OCR 完整指南 +url: /zh/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 视频字幕 OCR(C#)完整指南 + +是否曾需要 **video subtitle ocr** 却不知从何入手?你并不孤单。无论是数字化课堂录音、从培训视频中提取字幕,还是仅仅好奇如何从视频中读取文字,本教程将手把手教你使用 C# 和 Aspose.OCR 完成整个过程。 + +在接下来的几分钟里,我们将从视频中提取帧,对这些帧进行 OCR,最后逐帧显示字幕文本。完成后,你将能够 **read text from video** 文件(包括 MP4),无需再寻找第三方工具。 + +## 你将构建的内容 + +我们将创建一个小型控制台应用程序,能够: + +1. 将 MP4(或任何受支持的格式)解码为单独的 `Bitmap` 帧。 +2. 将 OCR 区域限制在字幕带上,避免引擎被整幅画面干扰。 +3. 使用 Aspose 的 `VideoOcrProcessor` 处理每一帧。 +4. 将识别出的字幕文本打印到控制台。 + +没有冗余,只提供一个可直接投入实际项目的端到端示例。 + +## 前置条件 + +- **.NET 6.0** 或更高(代码同样适用于 .NET Framework 4.7+)。 +- **Aspose.OCR for .NET** – 通过 NuGet 安装:`Install-Package Aspose.OCR`。 +- 一个视频文件(MP4 效果最佳)。 +- 用于解码视频帧的方式——演示中使用占位方法,你可以接入 FFmpeg、OpenCV 或任何返回 `Bitmap` 对象的库。 + +> 小技巧:如果你在 Windows 上,`System.Drawing.Common` 包可以很好地处理 `Bitmap`。在 Linux/macOS 上则需要本地的 `libgdiplus` 依赖。 + +## 步骤 1 – 从视频中提取帧 + +首要任务是把动态图像转为静态图像。下面的 `GetVideoFrames` 方法故意留空;请用你喜欢的解码器替换它。以下是使用 FFmpeg‑Core 的简要示例(仅用于说明数据结构): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **为何重要:** 提取帧后 OCR 引擎得到的是静态图像,这比直接从视频流读取文字要准确得多。 + +## 步骤 2 – 设置 VideoOcrProcessor + +现在我们已经拥有一系列 `Bitmap` 对象,可以将它们交给 Aspose.OCR。`VideoOcrProcessor` 允许我们定义 **Region of Interest (ROI)**——非常适合通常位于画面顶部或底部的字幕。 + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **为何要限制 ROI?** 忽略画面其余部分可以降低噪声、缩短处理时间,并避免背景图形产生的误识别。 + +## 步骤 3 – 对帧序列运行 OCR + +处理器准备就绪后,喂入帧只需一行代码。`Process` 方法返回 `OcrResult` 对象的可枚举集合,每个对象包含对应帧的识别文本。 + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **内部发生了什么?** Aspose.OCR 会先对每个 bitmap 进行归一化处理,随后使用基于神经网络的识别器,最后进行后处理以改善标点和换行。 + +## 步骤 4 – 显示提取的文本 + +最后,我们遍历结果并打印每行字幕。你也可以将它们写入 SRT 文件、数据库,或喂给翻译服务。 + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### 完整可运行示例 + +将所有代码组合在一起,即得到一个自包含的控制台程序: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**预期输出(示例)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +如果 OCR 在某帧上表现不佳,你会看到空字符串——这时可以调整 ROI 或提升帧提取率。 + +## 常见坑点及解决方案 + +| 问题 | 产生原因 | 解决办法 | +|------|----------|----------| +| **乱码字符** | 帧分辨率低或压缩严重 | 提高帧的比特率提取,或在 OCR 前对 bitmap 进行放大 (`Bitmap.Clone(new Size(...), ...)`)。 | +| **未返回文字** | ROI 实际上未覆盖字幕带 | 核实矩形坐标(使用截图工具测量)。 | +| **性能瓶颈** | 以 30 fps 处理每帧,工作量过大 | 将帧率降至 1‑2 fps,仍能捕获所有字幕变化。 | +| **找不到 FFmpeg** | `ffmpeg.exe` 未在 `PATH` 中 | 在 `ProcessStartInfo.FileName` 中写入完整路径,或全局安装 FFmpeg。 | + +## 扩展方案 + +- **导出为 SRT** – 将时间戳与 OCR 文本拼接,写入 SubRip 文件。 +- **多语言支持** – 设置 `ocrProcessor.Language = OcrLanguage.Spanish`(或任意受支持语言)。 +- **实时处理** – 直接从直播流中获取帧,而不是从磁盘读取。 + +所有这些变体仍围绕核心思路:**extract frames from video**、**read text from video**、**extract text from mp4**。 + +## 结论 + +我们已经完整演示了在 C# 中实现 **video subtitle ocr** 工作流的全部步骤。通过从视频中提取帧、将 OCR 聚焦于字幕带并遍历结果,你可以可靠地 **read text from video**(如 MP4)文件。代码已准备好直接复制粘贴,模块化设计也方便你替换任意帧解码器。 + +接下来可以尝试将结果导出为 SRT 文件,实验不同的 ROI 大小,或将字幕喂给翻译 API 实现多语言字幕。掌握了从视频中提取文字的基础后,想象空间无限。 + +祝编码愉快,愿你的字幕永远清晰可辨! + +## 接下来该学习什么? + +以下教程涵盖与本指南紧密相关的主题,帮助你进一步掌握 API 功能并探索替代实现方式: + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/ocr-configuration/_index.md b/ocr/czech/net/ocr-configuration/_index.md index c7b6c9546..a2e6bc404 100644 --- a/ocr/czech/net/ocr-configuration/_index.md +++ b/ocr/czech/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Odemkněte sílu rozpoznávání OCR obrázků v .NET s Aspose.OCR. Snadno extra Odemkněte výkonné OCR schopnosti s Aspose.OCR pro .NET. Plynule extrahujte text z obrázků. ### [OCROperation se seznamem v rozpoznávání OCR obrázků](./ocr-operation-with-list/) Odemkněte potenciál Aspose.OCR pro .NET. Snadno provádějte rozpoznávání OCR obrázků pomocí seznamů. Zvyšte produktivitu a extrakci dat ve svých aplikacích. +### [Získání verze Aspose OCR v C# – Kompletní průvodce](./get-aspose-ocr-version-in-c-complete-guide/) +Zjistěte, jak získat verzi Aspose.OCR v C# a ověřit kompatibilitu knihovny během vývoje. ### Běžné případy použití - **Extrahovat text z obrázků** ze skenovaných faktur pro automatizované účetnictví. @@ -98,4 +100,4 @@ A: Ano, objekt `OcrResult` poskytuje hodnoty důvěry, které můžete programov {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/czech/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..1e964ded0 --- /dev/null +++ b/ocr/czech/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Získejte verzi Aspose OCR v C# pomocí jednoduchého úryvku. Naučte se, + jak získat verzi knihovny Aspose OCR pomocí OcrEngine.GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: cs +og_description: Rychle získáte verzi Aspose OCR v C#. Tento tutoriál přesně ukazuje, + jak získat verzi knihovny Aspose OCR pomocí OcrEngine GetVersion. +og_title: Získejte verzi Aspose OCR v C# – Kompletní průvodce +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Získejte verzi Aspose OCR v C# – Kompletní průvodce +url: /cs/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Získání verze Aspose OCR v C# – Kompletní průvodce + +Už jste se někdy zamýšleli, jak **získat verzi Aspose OCR** z vašeho .NET projektu? Možná řešíte nesoulad verzí, nebo jen chcete zaznamenat přesnou verzi knihovny, která běží v produkci. Ať už je důvod jakýkoli, jste na správném místě. + +V tomto tutoriálu projdeme malý, samostatný C# program, který volá `OcrEngine.GetVersion()` a vypíše výsledek. Na konci nejenže budete vědět *jak* verzi získat, ale také *proč* kontrola verze může ušetřit spoustu starostí při aktualizaci **Aspose OCR library**. + +## Co se naučíte + +- Přidat NuGet balíček Aspose.OCR do C# projektu +- Použít metodu `OcrEngine.GetVersion()` (vstupní bod **ocrengine getversion**) +- Ošetřit možné výjimky a ověřit výstup +- Rozšířit úryvek pro reálné scénáře, jako je logování nebo podmíněné zapínání funkcí + +Žádná předchozí zkušenost s OCR není vyžadována – stačí základní znalost C# a Visual Studia (nebo vašeho oblíbeného IDE). Pojďme na to. + +--- + +## Krok 1: Nastavení projektu a načtení knihovny Aspose OCR + +Než budete moci volat jakékoli OCR‑souvislé API, musíte mít **Aspose OCR library** referencovanou ve svém projektu. + +1. Otevřete terminál nebo Package Manager Console ve Visual Studiu. +2. Spusťte následující příkaz pro instalaci nejnovější stabilní verze: + +```bash +dotnet add package Aspose.OCR +``` + +> **Tip:** Pokud cílíte na .NET Framework místo .NET Core, použijte UI NuGet Package Manageru a vyberte verzi, která odpovídá vašemu runtime. Balíček obsahuje třídu `OcrEngine`, kterou později použijeme. + +### Proč je to důležité + +Když nainstalujete balíček, verze sestavení na disku se může lišit od verze, kterou knihovna vrátí za běhu. Dotazování verze pomocí kódu zajišťuje, že čtete přesně to sestavení, které CLR načetl, což je klíčové pro ladění i pro audity shody. + +## Krok 2: Napsat minimální kód pro **získání verze Aspose OCR** + +Vytvořte novou konzolovou aplikaci (`dotnet new console -n OcrVersionDemo`) a nahraďte výchozí `Program.cs` následujícím kódem: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Vysvětlení jednotlivých částí** + +- `using Aspose.OCR;` přináší OCR jmenný prostor do dosahu, což nám umožňuje volat `OcrEngine`. +- `OcrEngine.GetVersion()` je statická metoda **ocrengine getversion**, která vrací řetězec jako `"24.5.7"`. +- Zabalit volání do bloku `try/catch` vás chrání před neočekávanými chybami během běhu – například pokud se nenašly nativní binárky na cílovém stroji. +- Interpolovaný řetězec `$"Aspose OCR version: {version}"` vypíše jasnou, lidsky čitelnou zprávu. + +### Očekávaný výstup + +Když spustíte `dotnet run` ve složce projektu, měli byste vidět něco podobného: + +``` +Aspose OCR version: 24.5.7 +``` + +Pokud se knihovna nepodaří načíst, větev s chybou vypíše stručnou zprávu, která vám rychle pomůže problém lokalizovat. + +## Krok 3: Ověřit, že verze odpovídá vašemu NuGet balíčku + +Je snadné předpokládat, že verze NuGetu, kterou jste nainstalovali, je ta, která se používá za běhu, ale mohou se objevit nečekané vlivy prostředí. Pro dvojí kontrolu: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Spuštěním tohoto doplňkového úryvku se vypíše něco jako: + +``` +Assembly file version: 24.5.7.0 +``` + +Pokud se dvě hodnoty liší, možná načítáte starší DLL z Global Assembly Cache (GAC) nebo ze staré složky sestavení. V takovém případě vyčistěte řešení (`dotnet clean`) a znovu sestavte. + +## Krok 4: Vložit kontrolu verze do produkčního logování + +Většina reálných aplikací nevyplívá jen do konzole; zapisuje do souboru logu nebo telemetrického systému. Zde je rychlý příklad s použitím `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Nyní se verze objeví ve vašich strukturovaných logech, což usnadní pozdější filtrování podle `{Version}`. Tento vzor je zvláště užitečný, když máte více mikro‑služeb, z nichž každá může načítat jinou verzi OCR DLL. + +## Časté otázky a okrajové případy + +### Co když `GetVersion()` vrátí prázdný řetězec? + +To obvykle signalizuje poškozenou instalaci nebo chybějící nativní závislost. Znovu nainstalujte NuGet balíček a ověřte, že `Aspose.OCR.Native.dll` (nebo odpovídající platformově specifický binární soubor) leží vedle vašeho spustitelného souboru. + +### Funguje metoda na .NET Core 2.0? + +Ano, **Aspose OCR** podporuje .NET Standard 2.0 a vyšší, takže jakákoli verze .NET Core implementující tento standard může volat `OcrEngine.GetVersion()`. Jen se ujistěte, že odkazujete na správné runtime identifikátory (`win-x64`, `linux-x64`, atd.), pokud publikujete samostatnou aplikaci. + +### Můžu získat verzi bez licenčního souboru? + +Rozhodně. `GetVersion()` **nevyžaduje** licenci; pouze vrací číslo sestavení knihovny. Pokud se však pokusíte provést OCR bez platné licence, dostanete výjimku za běhu. Proto je `try/catch` v našem úryvku užitečný – odděluje kontrolu verze od samotného OCR procesu. + +## Kompletní funkční příklad (připravený ke zkopírování) + +Níže je celý program, připravený k vložení do nové konzolové aplikace. Obsahuje volitelný blok logování, takže můžete vidět jak výstup do konzole, tak strukturované logy v akci. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Spusťte jej pomocí `dotnet run` a uvidíte dva řádky potvrzující verzi, plus ladicí řádek, pokud povolíte `LogLevel.Debug`. + +## Závěr + +Probrali jsme vše, co potřebujete k **získání verze Aspose OCR** v C# prostředí – od instalace **Aspose OCR library**, přes volání metody **ocrengine getversion**, ošetření chyb, až po začlenění výsledku do produkčního logování. S tímto know‑how můžete spolehlivě ověřit přesné OCR sestavení, které vaše aplikace používá, vyhnout se chybám souvisejícím s verzí a splnit požadavky na shodu bez zbytečného stresu. + +Další kroky? Zkuste spojit tuto kontrolu verze se skutečným OCR voláním (`OcrEngine` → `RecognizeImage`) a logovat jak verzi, tak výsledek rozpoznání. Můžete také prozkoumat vzor **retrieve aspose version** pro další Aspose produkty (PDF, Slides, Cells), abyste udrželi celou sadu synchronizovanou. + +Šťastné kódování a ať jsou vaše OCR pipeline vždy ostré! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/czech/net/ocr-optimization/_index.md index 73afa8ddc..788a7063f 100644 --- a/ocr/czech/net/ocr-optimization/_index.md +++ b/ocr/czech/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Prozkoumejte Aspose.OCR pro .NET. Zvyšte přesnost OCR pomocí předzpracovatel Zvyšte přesnost OCR s Aspose.OCR pro .NET. Opravujte pravopis, přizpůsobujte slovníky a dosáhněte bezchybného rozpoznávání textu s lehkostí. ### [Uložit vícestránkový výsledek jako dokument v OCR rozpoznávání obrázků](./save-multipage-result-as-document/) Odemkněte potenciál Aspose.OCR pro .NET. Jednoduše uložte vícestránkové OCR výsledky jako dokumenty s tímto komplexním krok‑za‑krokem průvodcem. +### [Aspose OCR C# příklad – povolení GPU, nastavení limitu paměti a zpracování TIF obrázků](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Naučte se povolit GPU, nastavit limit paměti a zpracovat TIF soubory pomocí Aspose.OCR v C#. ## Často kladené otázky diff --git a/ocr/czech/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/czech/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..beca47220 --- /dev/null +++ b/ocr/czech/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-03 +description: Příklad Aspose OCR v C#, který ukazuje, jak nastavit limit paměti GPU, + načíst obrázek pro OCR a rozpoznat text z TIF souborů, včetně kompletního kódu a + tipů. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: cs +og_description: 'Naučte se kompletní příklad Aspose OCR v C#: povolte GPU, nastavte + limit paměti GPU, načtěte obrázek pro OCR a rozpoznávejte text z TIF souborů. Kompletní + kód je zahrnut.' +og_title: Příklad Aspose OCR v C# – Akcelerace GPU, limit paměti a zpracování TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# příklad – povolit GPU, nastavit limit paměti a zpracovat TIF + obrázky +url: /cs/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# příklad – povolení GPU, nastavení limitu paměti a zpracování TIF obrázků + +Už jste se někdy zamýšleli, jak získat maximální výkon z **Aspose OCR C# příkladu** při práci s obrovskými TIFF skeny? Nejste sami. V mnoha reálných projektech — například digitalizace archivů nebo extrakce dat z vysoce rozlišených účtenek — úzkým místem není samotný OCR algoritmus, ale využití hardwaru. + +Aspose OCR podporuje akceleraci pomocí GPU, ale musíte mu přesně říct, kolik paměti může použít, načíst správný typ obrázku a nakonec získat rozpoznaný text ze souboru .tif. Tento tutoriál vás provede každým krokem, od instalace SDK až po ladění nastavení GPU, takže můžete spustit OCR na šílenou rychlost, aniž byste přetížili RAM vaší grafické karty. + +Navíc přidáme několik „co‑když“ scénářů — například zpracování více‑stránkových TIFFů nebo přepnutí na CPU, pokud GPU není k dispozici — aby výsledek byl robustní řešení, ne jen jednorázový útržek kódu. + +## Co budete potřebovat + +Než se pustíme dál, ujistěte se, že máte na svém počítači následující komponenty: + +| Předpoklad | Proč je důležitý | +|------------|-------------------| +| **.NET 6 SDK** (nebo novější) | Aspose OCR cílí na .NET Standard 2.0+, takže funguje s jakoukoliv aktuální verzí .NET. | +| **Aspose.OCR NuGet balíček** (`Install-Package Aspose.OCR`) | Hlavní knihovna, která poskytuje `OcrEngine`, `GpuSettings` atd. | +| **CUDA 11+** (NVIDIA) **nebo ROCm 5+** (AMD) | Požadováno pro akceleraci GPU; SDK během běhu zkontroluje kompatibilní driver. | +| GPU s alespoň **2 GB VRAM** (nastavíme limit na 2048 MB) | Bez dostatečné paměti může engine tiše přejít na CPU. | +| **Vysoké rozlišení TIFF** obrázek, který chcete zpracovat | Aspose OCR dokáže číst prakticky jakýkoliv rastrový formát, ale TIF je běžný pro skeny. | +| Visual Studio 2022 (nebo jakýkoliv oblíbený editor) | Pro sestavení a ladění C# projektu. | + +Pokud některý z těchto komponent chybí, kód se stále zkompiluje, ale nebudete vidět požadované zrychlení. + +## Krok 1: Vytvoření Aspose OCR C# příkladového enginu + +Prvním krokem v každém **Aspose OCR C# příkladu** je vytvořit instanci OCR enginu. `OcrEngine` je jako režisér filmu — koordinuje vše od načtení obrázku po extrakci textu. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Tip:** Pokud plánujete zpracovávat mnoho obrázků po sobě, nechte jeden `OcrEngine` běžet po celou dobu. Opakované vytváření nového enginu pro každý obrázek přidává režii, která může převýšit samotný čas OCR. + +## Krok 2: Nastavení limitu paměti GPU (a povolení akcelerace) + +Nyní přichází část, která často lidi zaskočí: **nastavení limitu paměti GPU**. Ve výchozím nastavení se Aspose OCR pokusí využít co nejvíce VRAM, což na sdílené pracovní stanici může odepřit jiné aplikace. Objekt `GpuSettings` vám umožní omezit alokaci. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Proč nastavit limit paměti? + +- **Stabilita:** Zabrání pádům kvůli nedostatku paměti při zpracování obrovských obrázků. +- **Spolupráce:** Umožní ostatním aplikacím náročným na GPU (např. TensorFlow modely) běžet současně. +- **Předvídatelnost:** Zajistí opakovatelnost testování výkonu, protože GPU nebude začínat swapovat. + +Pokud `MemoryLimitMb` vynecháte, Aspose alokuje tolik, kolik považuje za nutné – což může být v pořádku na dedikovaném inference serveru, ale riskantní na vývojářském notebooku. + +## Krok 3: Načtení obrázku pro OCR + +Načtení správného formátu souboru je další klíčový krok. Metoda `OcrImage.FromFile` automaticky detekuje typ obrázku, ale stále byste měli ověřit, že soubor existuje a že jde o podporovanou variantu TIFF (např. LZW‑komprimovaný nebo CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Zpracování více‑stránkových TIFFů + +Pokud váš TIFF obsahuje několik stránek, Aspose OCR ve výchozím nastavení načte jen první. Pro zpracování všech stránek můžete iterovat přes `image.Pages` (k dispozici v novějších verzích SDK) a každou stránku předat enginu zvlášť. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Ukázkový úryvek výše představuje **načtení obrázku pro OCR** vzor, který funguje jak pro jednostránkové, tak pro více‑stránkové soubory. + +## Krok 4: Rozpoznání textu z TIF (nebo libovolného rastrového formátu) + +Jakmile je obrázek v paměti, požádáme Aspose, aby udělal své kouzlo. Metoda `Recognize` vrací `OcrResult`, který obsahuje čistý text, skóre důvěry a dokonce i informace o ohraničujících rámečcích, pokud je potřebujete. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Proč to funguje dobře s TIF + +- **Bezeztrátová komprese:** TIFF často ukládá surová pixelová data, což dává OCR enginu nejvyšší věrnost. +- **Různé barevné prostory:** Aspose zvládne grayscale, RGB i CMYK TIFFy bez nutnosti další konverze. + +Pokud potřebujete nastavit jazykové balíčky (např. francouzštinu nebo japonštinu), nastavte `ocrEngine.Settings.Language = "fr"` před voláním `Recognize`. + +## Krok 5: Zobrazení rozpoznaného textu + +Nakonec vypíšeme text do konzole. Ve skutečné aplikaci byste ho možná uložili do databáze, JSON souboru nebo předali dál do NLP pipeline. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Očekávaný výstup + +Spuštění programu na čistém, 300 dpi skenu tištěné stránky obvykle vrátí něco jako: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Pokud je obrázek rozmazaný nebo je limit paměti GPU nastaven příliš nízko, můžete vidět poškozené znaky nebo zkrácený výsledek. Snížení `MemoryLimitMb` pod velikost obrázku (často ~1 GB pro 6000×8000 pixelový TIFF) může způsobit automatické přepnutí na CPU. + +## Kompletní funkční příklad + +Níže je kompletní, připravený k spuštění program. Zkopírujte jej do nového Console App projektu, nahraďte `YOUR_DIRECTORY/large_photo.tif` cestou k vašemu TIFF souboru a stiskněte **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Rychlý kontrolní seznam + +- ✅ **Aspose OCR C# příklad** zkompilován bez chyb. +- ✅ **GPU povoleno** (`Enable = true`). +- ✅ **Limit paměti GPU** nastaven na 2048 MB. +- ✅ **Obrázek načten** z TIF souboru. +- ✅ **Text rozpoznán** a vytištěn. + +## Časté problémy a jak se jim vyhnout + +| Příznak | Pravděpodobná příčina | Oprava | +|---------|-----------------------|--------| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA runtime není nainstalován nebo verze nesedí. | Nainstalujte CUDA 11.x (nebo 12.x) odpovídající vašemu driveru. | +| OCR vrací prázdný řetězec | Obrázek je příliš tmavý nebo DPI < 150. | Předzpracujte pomocí `image.AdjustContrast()` nebo převeďte na 300 dpi. | +| Pád kvůli nedostatku paměti na GPU | `MemoryLimitMb` je příliš nízký pro daný obrázek. | Zvyšte limit nebo rozdělte obrázek na dlaždice pomocí `image.Crop`. | +| Chyba `Unsupported image format` | TIFF používá exotickou kompresi (např. JPEG‑2000). | Před OCR konvertujte TIFF do podporovaného formátu pomocí ImageMagick. | + +## Rozšíření demo + +Nyní, když máte solidní **aspose ocr c# příklad**, můžete zkusit: + +- **Dávkové zpracování:** Procházet složku s TIFy a výsledek ukládat do `.txt` souboru. +- **Jazykové balíčky:** `ocrEngine.Settings.Language = "es"` pro španělštinu nebo načíst vlastní slovníky. +- **Ohraničující rámečky:** Použít `ocrResult.Regions` k získání souřadnic pro každé slovo — užitečné např. pro nástroje na redakci. +- **Přepnutí na CPU:** Obalit GPU blok do `try/catch`; při selhání nastavit `ocrEngine.Settings.Gpu.Enable = false` a zopakovat. + +Tyto rozšíření zachovávají základní vzor, ale přidávají hodnotu pro specifické použití. + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční kódové příklady s podrobným krok‑za‑krokem vysvětlením, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Extrahovat text z obrázku pomocí Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extrahovat text z obrázku – optimalizace OCR s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/czech/net/skew-angle-calculation/_index.md index 1a88f2f3e..01de3ad71 100644 --- a/ocr/czech/net/skew-angle-calculation/_index.md +++ b/ocr/czech/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Prozkoumejte Aspose.OCR for .NET, výkonné řešení OCR pro přesné rozpozná Uvolněte sílu Aspose.OCR pro .NET, robustního řešení pro rozpoznávání obrázků. Naučte se bez námahy vypočítat úhly zkosení. ### [Vypočítat úhel zkosení z URI v rozpoznávání obrazu OCR](./calculate-skew-angle-from-uri/) Prozkoumejte Aspose.OCR for .NET, abyste mohli snadno vypočítat úhly zkosení při rozpoznávání obrazu OCR. Vylepšete své projekty s přesností a efektivitou. +### [OCR tutoriál pro otočený dokument – automatické opravy zkosení a rotace v C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Naučte se automaticky odhalit a opravit zkosení a rotaci dokumentů pomocí Aspose.OCR pro .NET v C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/czech/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..3f073fd85 --- /dev/null +++ b/ocr/czech/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: Návod na OCR otočených dokumentů, který ukazuje, jak automaticky opravit + zkosení a detekovat rotaci pomocí Aspose OCR v C#. Naučte se krok za krokem s kompletním + kódem. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: cs +og_description: Návod na OCR otočených dokumentů vás naučí, jak automaticky opravit + zkosení a detekovat rotaci pomocí Aspose OCR v C#. Sledujte kompletní průvodce. +og_title: Návod na OCR otočeného dokumentu – automatické vyrovnání a oprava rotace + v C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Návod na OCR otočených dokumentů – Automatické vyrovnání a oprava rotace v + C# +url: /cs/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Rotated Document Tutorial – Kompletní průvodce pro vývojáře C# + +Už jste někdy narazili na **ocr rotated document tutorial**, když byl naskenovaný formulář otočený nebo šikmý? Nejste v tom sami. Tyto podivné obrázky mohou zkazit čistý výstup textu, ale dobrá zpráva je, že Aspose OCR může vše automaticky narovnat. + +V tomto krok‑za‑krokem průvodci spustíme `OcrEngine`, zapneme **automatic skew correction** a **auto detect rotation**, spustíme engine na otočeném obrázku a vytiskneme čistý text. Na konci přesně pochopíte, proč každé nastavení je důležité, jak jej upravit pro okrajové případy, a budete mít připravený spustitelný C# program. + +## Co se naučíte + +* Jak nainstalovat a odkazovat na **Aspose OCR** v .NET projektu. +* Proč povolení `AutoCorrectSkew` a `AutoDetectRotation` je klíčem k spolehlivému **ocr rotated document tutorial**. +* Jak načíst libovolný obrázek (JPG, PNG, TIFF) a nechat engine udělat těžkou práci. +* Tipy pro práci s více‑stránkovými PDF, nízkokvalitními skeny a vlastními jazykovými balíčky. + +> **Požadavky:** Visual Studio 2022 (nebo jakékoli C# IDE), .NET 6+ runtime a platná licence Aspose OCR (nebo bezplatná zkušební verze). Předchozí zkušenost s OCR není vyžadována. + +--- + +## Krok 1 – Instalace Aspose OCR a nastavení projektu + +Nejprve. Stáhněte NuGet balíček: + +```bash +dotnet add package Aspose.OCR +``` + +> **Tip:** Pokud používáte zkušební licenci, umístěte soubor `Aspose.OCR.lic` do stejné složky jako váš spustitelný soubor, nebo jej zaregistrujte programově pomocí `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Vytvořte novou konzolovou aplikaci: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Nyní máte čistý start pro náš **ocr rotated document tutorial**. + +## Krok 2 – Inicializace OCR Engine + +Engine je srdcem procesu. Představte si ho jako švýcarský armádní nůž pro extrakci textu; stačí mu říct, jaké triky má povolit. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Proč tato nastavení?** +* `AutoCorrectSkew` analyzuje základní linii znaků a otočí obrázek právě natolik, aby byly řádky vodorovné. +* `AutoDetectRotation` zkoumá celkovou orientaci (0°, 90°, 180°, 270°) a převrátí stránku, pokud je vzhůru nohama. Bez nich by engine četl „pɹᴉʍ“ místo „word“. + +## Krok 3 – Načtení obrázku, který chcete zpracovat + +Aspose OCR pracuje s jakýmkoli běžným rastrovým formátem. Nahraďte zástupnou cestu skutečnou polohou vašeho otočeného formuláře. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Okrajový případ:** Pokud obdržíte více‑stránkový TIFF, použijte `OcrImage.FromMultiPageTiff(filePath)` a procházejte `image.Pages`. + +## Krok 4 – Spuštění rozpoznávání + +Nyní engine provádí kouzlo. Nejprve narovná obrázek (díky našim flagům pro sklon/rotaci) a poté vytáhne znaky. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Pokud potřebujete jazykovou podporu nad rámec angličtiny, nastavte ji před voláním `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Krok 5 – Výstup rozpoznaného textu + +Nakonec vypište čistý text do konzole – nebo jej přesměrujte do souboru, databáze, cokoliv, co vyhovuje vašemu workflow. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Očekávaný výstup** (předpokládáme, že ukázkový obrázek obsahuje „Invoice #1234“): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Všimněte si, že text se zobrazuje správně, i když byl zdrojový obrázek otočen o 90° a mírně nakloněn. + +--- + +## Řešení běžných problémů + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Prázdný výstup** | Oprava sklonu je vypnutá nebo je obrázek příliš tmavý. | Povolte `AutoCorrectSkew` (již zapnuto) a zvyšte kontrast obrázku pomocí `image.AdjustContrast(1.2)`. | +| **Neplatné znaky** | Nesprávné nastavení jazyka. | Nastavte `ocrEngine.Settings.Language` tak, aby odpovídal jazyku dokumentu. | +| **Zpomalení výkonu u velkých PDF** | Engine zpracovává každou stránku sekvenčně. | Použijte `Parallel.ForEach` na `image.Pages` pro využití vícejádrových CPU. | +| **Výjimka licence** | Zkušební verze vypršela. | Získejte trvalou licenci nebo se držte limitů zkušební verze (5 stránek na běh). | + +## Profesionální tipy pro robustní OCR Rotated Document Tutorial + +* **Dávkové zpracování:** Zabalte celý tok do metody, která přijímá cestu ke složce, prochází každý obrázek a zapíše výsledek do souboru `.txt`. +* **Předzpracování:** Někdy špinavý sken těží z `image.Denoise()` před rozpoznáním. +* **Post‑zpracování:** Použijte regulární výrazy k vyčištění běžných chyb OCR, např. nahraďte „0“ písmenem „O“ pouze když je obklopeno písmeny. +* **Logování:** Aspose OCR poskytuje `ocrEngine.Logger` – připojte jej k souborovému loggeru pro zachycení varování o nízkých skórech důvěry. + +## Kompletní, připravený k spuštění kód + +Uložte následující jako `Program.cs` ve vašem konzolovém projektu. Obsahuje všechny kroky, komentáře a malý pomocník pro dávkové zpracování. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Spusťte: + +```bash +dotnet run +``` + +Měli byste vidět vyčištěný text vytištěný do konzole, což dokazuje, že náš **ocr rotated document tutorial** funguje od začátku do konce. + +## Závěr + +Nyní máte kompletní **ocr rotated document tutorial**, který automaticky koriguje sklon, detekuje rotaci a extrahuje čistý text pomocí Aspose OCR v C#. Hlavní závěr? Povolení `AutoCorrectSkew` **a** `AutoDetectRotation` promění beznadějně nakloněný sken na dokonale čitelný výstup pomocí několika řádků kódu. + +Odtud můžete rozšířit na dávkové úlohy, integrovat jazykové balíčky nebo předat výsledky do následných analytických pipeline. Chcete dále zkoumat **automatic skew correction**? Prohlédněte si API pro předzpracování obrázků od Aspose nebo experimentujte s vlastními prahy pro špinavé skeny. + +Máte otázky ohledně práce s PDF, více‑stránkovými TIFFy nebo integrace s Azure Functions? Zanechte komentář a šťastné kódování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [ocr document mode – Detekce oblastí v OCR rozpoznávání obrazu](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extrahování textu z obrázku v C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optické rozpoznávání znaků](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/czech/net/text-recognition/_index.md index b178a0c01..1b655e1cd 100644 --- a/ocr/czech/net/text-recognition/_index.md +++ b/ocr/czech/net/text-recognition/_index.md @@ -55,9 +55,20 @@ Vylepšete své aplikace .NET pomocí Aspose.OCR pro efektivní rozpoznávání Odemkněte potenciál OCR v .NET s Aspose.OCR. Extrahujte text z PDF bez námahy. Stáhněte si nyní pro bezproblémovou integraci. ### [Rozpoznat tabulku v OCR rozpoznávání obrazu](./recognize-table/) Odemkněte potenciál Aspose.OCR pro .NET pomocí našeho komplexního průvodce rozpoznáváním tabulek při rozpoznávání obrázků OCR. +### [Provést OCR na obrázku s Aspose OCR – hindský průvodce](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Naučte se, jak pomocí Aspose OCR provést rozpoznávání textu v hindštině na obrázcích ve vašich .NET aplikacích. +### [Provést OCR na PDF s Aspose.OCR – Kompletní průvodce C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Naučte se, jak pomocí Aspose.OCR provést kompletní OCR na PDF v C# a integrovat výsledek do vašich aplikací. +### [Jak použít Aspose: převod obrázku do HTML s OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Naučte se, jak pomocí Aspose.OCR převést obrázek na HTML a zachovat rozpoznaný text. +### [Provést OCR na obrázku a detekovat překlepy v C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Naučte se, jak pomocí Aspose.OCR provést rozpoznání textu na obrázku a identifikovat překlepy ve vašich C# aplikacích. +### [OCR titulků videa v C# – Kompletní průvodce](./video-subtitle-ocr-in-c-complete-guide/) +Naučte se pomocí Aspose.OCR extrahovat a rozpoznávat titulky z videí v C# a integrovat výsledky do vašich aplikací. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/czech/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..d3a0a3bf6 --- /dev/null +++ b/ocr/czech/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: Jak použít Aspose k převodu obrázku na HTML a extrahování textu z obrázku + v C#. Naučte se rychle generovat HTML z obrázku a provádět OCR obrázku do HTML. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: cs +og_description: Jak použít Aspose k převodu obrázku na HTML, extrakci textu z obrázku + a generování HTML z obrázku pomocí OCR v C#. Sledujte tento kompletní návod. +og_title: 'Jak používat Aspose: převést obrázek na HTML s OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Jak používat Aspose: převést obrázek na HTML s OCR' +url: /cs/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak používat Aspose: Převod obrázku na HTML s OCR + +Už jste se někdy zamýšleli **jak používat Aspose** k převodu naskenovaného obrázku na úhledné HTML? Možná máte stránku z časopisu, účtenku nebo ručně psanou poznámku a potřebujete zachovat text a rozvržení pro publikaci na webu. Dobrou zprávou je, že nemusíte psát vlastní parser ani se zabývat nízkoúrovňovým zpracováním obrazu — Aspose.OCR za vás udělá těžkou práci. + +V tomto tutoriálu projdeme **kompletní, spustitelný příklad**, který vám ukáže, jak **převést obrázek na HTML**, **extrahovat text z obrázku** a **generovat HTML z obrázku** pomocí knihovny Aspose OCR v C#. Na konci budete mít malou konzolovou aplikaci, která vytvoří soubor HTML s původním rozvržením stránky zachovaným, připravený k nasazení na jakýkoli web. + +## Požadavky + +- **.NET 6.0 SDK** nebo novější (kód funguje jak s .NET Core, tak s .NET Framework). +- **Visual Studio 2022** (nebo jakýkoli editor, který máte rádi). +- **Aspose.OCR for .NET** – nainstalujte přes NuGet: `dotnet add package Aspose.OCR`. +- Obrázkový soubor (JPEG/PNG), který chcete převést, např. `magazine_page.jpg`. + +Žádné další konfigurační soubory nejsou potřeba; knihovna obsahuje vše potřebné pro OCR a generování HTML rozvržení. + +## Krok 1: Nastavte projekt a přidejte Aspose.OCR + +Nejprve vytvořte nový konzolový projekt a přidejte balíček Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Tip:** Pokud používáte Visual Studio, stačí kliknout pravým tlačítkem na projekt → *Manage NuGet Packages* → vyhledat **Aspose.OCR** a nainstalovat jej. Tento krok zajistí, že můžete **ocr image to html** bez chybějících odkazů. + +## Krok 2: Inicializujte OCR Engine + +Jádrem procesu je třída `OcrEngine`. Představte si ji jako mozek, který čte obrázek a rozhoduje, jaký výstup vytvořit. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Zde vytváříme instanci `OcrEngine`. Pro bezplatnou verzi nemusíte předávat žádné přihlašovací údaje; knihovna použije své vestavěné rozpoznávací modely. + +## Krok 3: Načtěte zdrojový obrázek + +Dále nasměrujte engine na soubor, který chcete zpracovat. Aspose poskytuje pohodlnou metodu `OcrImage.FromFile`, která zvládne většinu formátů obrázků. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Nahraďte `YOUR_DIRECTORY` absolutní nebo relativní cestou, kde se váš obrázek nachází. Pokud je obrázek ve stejné složce jako spustitelný soubor, můžete použít jen `"magazine_page.jpg"`. + +## Krok 4: Rozpoznání a požadavek na HTML s rozvržením + +Toto je jádro tutoriálu. Předáním `OutputFormat.HtmlWithLayout` říkáme Aspose, aby **generoval HTML z obrázku** při zachování původního umístění textových bloků, obrázků a tabulek. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Vlastnost `recognitionResult.Text` nyní obsahuje kompletní HTML dokument. Pokud byste potřebovali jen prostý text, můžete použít `OutputFormat.Text`, ale zaměřujeme se na **convert image to html** s věrností rozvržení. + +## Krok 5: Uložte soubor HTML + +Nakonec zapíšete řetězec HTML na disk. Získáte tak připravený soubor, který můžete otevřít v libovolném prohlížeči. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Spuštěním programu vznikne `magazine.html`. Otevřete jej a uvidíte text původní stránky umístěný přesně tak, jak byl v zdrojovém obrázku — ideální pro archivaci nebo publikaci na webu. + +## Kompletní funkční příklad + +Níže je **kompletní, připravený ke zkopírování** program. Žádné části nejsou vynechány, takže jej můžete ihned po nastavení správných cest zkompilovat a spustit. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Očekávaný výstup + +Když otevřete `magazine.html` v prohlížeči, měli byste vidět něco podobného (zjednodušeně pro ilustraci): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Přesné atributy `style` se budou lišit podle původního obrázku, ale struktura zaručuje, že **extract text from image** a **generate html from image** proběhnou v jediném, plynulém kroku. + +## Časté otázky a okrajové případy + +### Co když je obrázek nízkého rozlišení? + +Aspose.OCR funguje nejlépe s obrázky, které mají alespoň **300 DPI**. Pokud je soubor rozmazaný, zkuste jej před předáním OCR engine předzpracovat knihovnou pro vylepšení obrazu (např. ImageSharp). Nízká kvalita může ovlivnit jak přesnost **extract text from image**, tak věrnost generovaného HTML rozvržení. + +### Můžu ovládat jazyk OCR? + +Ano. Nastavte vlastnost `Language` na `OcrEngine` před voláním `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Tím se zlepší rozpoznávání při práci s neanglickými znaky. + +### Jak získám prostý text místo HTML? + +Pokud potřebujete jen surový řetězec, nahraďte `OutputFormat.HtmlWithLayout` za `OutputFormat.Text`. Pak bude `recognitionResult.Text` obsahovat pouze extrahované znaky. + +### Existuje způsob, jak vložit obrázky do generovaného HTML? + +Aspose.OCR může vložit původní obrázek jako base‑64 data URI, když použijete `OutputFormat.HtmlWithLayoutAndImages`. To je užitečné, pokud chcete jediný HTML soubor bez externích zdrojů. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Jak řešit velké dávky? + +Pro dávkové zpracování zabalte logiku do smyčky `foreach` přes seznam cest k souborům. Opakované používání stejné instance `OcrEngine` snižuje režii a urychluje pipeline **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tipy pro produkční kód + +- **Uvolňujte zdroje**: Jak `OcrEngine`, tak `OcrImage` implementují `IDisposable`. Zabalte je do `using` bloků, aby se rychle uvolnila nativní paměť. +- **Zpracování chyb**: Zachyťte `IOException` pro problémy související se soubory a `OcrException` pro problémy s rozpoznáním. +- **Výkon**: Pokud zpracováváte mnoho obrázků, zvažte povolení **paralelismu** (`Parallel.ForEach`), ale dbejte na využití CPU — OCR je náročné na procesor. +- **Logování**: Integrovat logger (např. Serilog) pro zachycení skóre důvěry OCR (`recognitionResult.Confidence`) pro monitorování kvality. + +## Závěr + +Právě jsme prošli **jak používat Aspose** k **převodu obrázku na HTML**, **extrahování textu z obrázku** a **generování HTML z obrázku** v několika jednoduchých krocích. Kompletní ukázkový kód vám ukazuje, jak **ocr image to html** při zachování rozvržení, což je solidní základ pro jakýkoli projekt digitalizace dokumentů. + +Od sem můžete: + +- Experimentovat s různými možnostmi `OutputFormat`, aby vyhovovaly vašim potřebám. +- Spojit výstup HTML s CSS frameworkem pro responzivní stylování. +- Poslat extrahovaný text do vyhledávacího indexu nebo do pipeline strojového učení. + +Vyzkoušejte to, upravte nastavení a uvidíte, jak snadno Aspose převádí obrázky na obsah připravený pro web. Pokud narazíte na problémy, zanechte komentář — šťastné kódování! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Extrahovat text z obrázku C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Převést obrázek na text – provést OCR na obrázku z URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [rozpoznat textový obrázek pomocí Aspose OCR pro více jazyků](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/czech/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..fbdfce589 --- /dev/null +++ b/ocr/czech/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-06-03 +description: Proveďte OCR na obrázku a extrahujte text z obrázku pomocí Aspose.OCR. + Naučte se, jak detekovat chybně napsaná slova a získat návrhy na opravu pravopisu + v jednom C# demu. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: cs +og_description: Proveďte OCR na obrázku, abyste extrahovali text, poté detekujte nesprávně + napsaná slova a získejte návrhy pravopisu pomocí Aspose.OCR v C#. +og_title: Provést OCR na obrázku a detekovat pravopisně nesprávná slova v C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Proveďte OCR na obrázku a detekujte pravopisně chybné slova v C# +url: /cs/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Proveďte OCR na obrázku a detekujte pravopisné chyby v C# + +Už jste se někdy zamysleli, jak **perform OCR on image** soubory bez toho, aby vám to vytrhávalo vlasy? Nejste jediní. Ať už digitalizujete staré dopisy, skenujete účtenky nebo budujete inteligentní workflow dokumentů, získání čistého textu z obrázků je první překážkou. Dobrá zpráva? S Aspose.OCR můžete během několika minut vytvořit řešení a navíc můžete také **detect misspelled words** a **get spelling suggestions** během jednoho běhu. + +V tomto tutoriálu vás provedeme kompletní, připravenou k spuštění C# konzolovou aplikací, která **extracts text from image**, spustí anglický spell‑checker a vytiskne každou chybu s užitečnými návrhy oprav. Na konci přesně budete vědět **how to extract text**, jak připojit spell‑check API a jak vypadá očekávaný výstup v konzoli. + +## Co vytvoříte + +- Načtěte bitmapu (nebo PNG), která obsahuje typografické chyby. +- Spusťte Aspose.OCR k **perform OCR on image** a získejte surová data řetězce. +- Inicializujte vestavěný anglický spell‑checker. +- **Detect misspelled words** a **get spelling suggestions** pro každé. +- Vytiskněte přehledný report do konzole. + +Žádné externí služby, žádné komplikované HTTP volání – jen jediný NuGet balíček a několik řádků kódu. + +## Požadavky + +- .NET 6.0 SDK nebo novější (kód také funguje na .NET Framework 4.7+). +- Visual Studio 2022 (nebo jakýkoli editor, který máte rádi). +- Aspose.OCR pro .NET NuGet balíček (`Aspose.OCR`). +- Obrázkový soubor (`letter_with_typos.png`) umístěný na místě, na které můžete odkazovat z projektu. + +Pokud jste ještě nikdy nepoužili Aspose, nebojte se – instalace balíčku je tak jednoduchá jako spuštění: + +```bash +dotnet add package Aspose.OCR +``` + +Nyní se ponořme do implementace. + +## Krok 1: Nastavte projekt a nainstalujte Aspose.OCR + +Vytvořte nový konzolový projekt a přidejte OCR knihovnu: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Po dokončení obnovení otevřete `Program.cs`. Později nahradíme výchozí obsah plným demonstračním kódem, ale nejprve si povíme, proč je každý jmenný prostor důležitý. + +- `Aspose.OCR` – jádro OCR enginu a zpracování obrázků. +- `Aspose.OCR.SpellCheck` – nástroje pro pravopisnou kontrolu, které jsou součástí knihovny. +- `System` – standardní .NET základní třídy (např. `Console`). + +## Krok 2: Načtěte obrázek a proveďte OCR na obrázku + +První skutečná práce je předat obrázek OCR enginu. Aspose.OCR čte mnoho formátů (PNG, JPEG, TIFF). Zde je úryvek, který dělá těžkou práci: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Proč je to důležité:** `OcrImage.FromFile` abstrahuje podrobnosti na úrovni pixelů, zatímco `OcrEngine.Recognize` spouští natrénovaný neuronový model, který převádí vizuální glyfy na Unicode znaky. Vlastnost `ocrResult.Text` nyní obsahuje surový řetězec – přesně to, co potřebujete k **extract text from image**. +> **Tip:** Pokud váš obrázek obsahuje více jazyků, můžete před voláním `Recognize` nastavit `ocrEngine.Language = OcrLanguage.Multilingual;`. + +## Krok 3: Inicializujte anglický Spell‑Checker + +Aspose.OCR obsahuje vestavěný engine pro pravopisnou kontrolu, který rozumí angličtině ihned po instalaci. Jeho inicializace je jednorázová: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Proč je tento krok zásadní:** Výstup OCR může obsahovat nesprávně rozpoznané znaky (např. „l“ vs „1“) nebo skutečné překlepy ze zdrojového dokumentu. Spell‑checker prohledá řetězec, najde podezřelé tokeny a navrhne alternativy. + +## Krok 4: Detekujte pravopisné chyby a získejte návrhy oprav + +Nyní předáme OCR text kontroleru: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` je kolekce, kde každý záznam obsahuje chybné slovo a pole možných oprav. + +## Krok 5: Výstup výsledků + +Nakonec projdeme kolekci a vytiskneme čitelný report: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Očekávaný výstup v konzoli + +Předpokládejme, že `letter_with_typos.png` obsahuje větu: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Spuštěním dema získáte něco jako: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +## Kompletní funkční příklad + +Níže je **kompletní, připravený ke zkopírování** program. Nahraďte `YOUR_DIRECTORY` skutečnou cestou k vašemu obrázku. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Okrajové případy k úvaze** +> - **Prázdný obrázek:** Pokud OCR engine vrátí prázdný řetězec, `spellChecker.Check` jednoduše vrátí prázdnou kolekci – žádná havárie. +> - **Neanglický text:** Vyměňte `OcrLanguage.English` za `OcrLanguage.French` (nebo jakýkoli podporovaný jazyk), abyste **detect misspelled words** v jiných locale. +> - **Velké dokumenty:** Pro více‑stránkové PDF byste prošli každou stránku, provedli OCR a poté agregovali výsledky před pravopisnou kontrolou. + +## Vizualizace (Alt text obrázku) + +![Diagram zobrazující tok provedení OCR na obrázku, extrakci textu z obrázku a následnou detekci pravopisných chyb s návrhy oprav](perform-ocr-on-image-flow.png) + +*Diagram výše ilustruje kompletní pipeline: obrázek → OCR engine → surový text → spell‑checker → návrhy.* + +## Časté otázky a tipy + +| Question | Answer | +|----------|--------| +| **Potřebuji internetové připojení?** | Ne. Aspose.OCR běží zcela lokálně; ideální pro offline nebo zabezpečená prostředí. | +| **Jak přesný je spell‑checker?** | Používá slovník přibližně 150 000 anglických slov a fuzzy porovnávání, takže většina běžných překlepů je zachycena. | +| **Mohu si přizpůsobit slovník?** | Ano. `SpellChecker.AddUserDictionary("custom.txt")` vám umožní načíst termíny specifické pro doménu (např. názvy produktů). | +| **Co když je obrázek nakřivený?** | OCR engine automaticky detekuje orientaci, ale v obtížných případech můžete ručně zavolat `ocrEngine.ImagePreprocessing.Rotate(angle)`. | +| **Existuje způsob, jak zvýraznit návrhy v UI?** | Po získání kolekce `misspellings` můžete mapovat každé `entry.Word` zpět na jeho pozici v `ocrResult.Text` a podtrhnout jej v RichTextBoxu nebo webovém zobrazení. | + +## Závěr + +Právě jsme vám ukázali **how to perform OCR on image**, **extract text from image**, a pak **detect misspelled words** při **getting spelling suggestions** – vše pomocí stručné C# konzolové aplikace. Základní myšlenka je jednoduchá: nechte Aspose.OCR udělat těžkou práci rozpoznávání znaků a nechte jeho vestavěný spell‑checker vyčistit výstup. Odtud můžete rozšířit demo na plnohodnotnou službu zpracování dokumentů, integrovat ji s webovým API nebo zapojit do desktopového editoru. + +Jste připraveni na další krok? Zkuste změnit jazyk na španělštinu, načíst více‑stránkový PDF, nebo vytvořit malý WPF front‑end, který uživatelům umožní kliknout na slovo a přijmout návrh. Stavební bloky už jsou na místě – jen dál experimentujte. + +Pokud narazíte na problémy nebo máte nápady na rozšíření, zanechte komentář níže. Šťastné programování! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobnými vysvětleními, které vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Extrahovat text z obrázku v C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extrahovat text z obrázku pomocí Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extrahovat text z obrázku – optimalizace OCR s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/czech/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..8499afdf2 --- /dev/null +++ b/ocr/czech/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Proveďte OCR na obrázku pomocí Aspose OCR v C#. Naučte se, jak načíst + obrázek pro OCR a offline extrahovat hindský text z obrázku pomocí krok‑za‑krokem + kódu. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: cs +og_description: Proveďte OCR na obrázku pomocí Aspose OCR v C#. Tento tutoriál ukazuje, + jak načíst obrázek pro OCR a offline extrahovat hindský text z obrázku, včetně spustitelného + kódu. +og_title: Proveďte OCR na obrázku – Aspose OCR Hindi průvodce +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Provést OCR na obrázku pomocí Aspose OCR – průvodce v hindštině +url: /cs/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Provést OCR na obrázku s Aspose OCR – Průvodce v hindštině + +Už jste někdy potřebovali **provést OCR na obrázku** soubory, ale nevedeli jste, jak z nich získat hindské znaky? Nejste sami — mnoho vývojářů narazí na tuto překážku, když poprvé zkouší číst ne‑latinské skripty. Dobrou zprávou je, že Aspose OCR to dělá poměrně snadno a můžete to provést zcela offline. + +V tomto průvodci **načteme obrázek pro OCR**, nasměrujeme engine na vaše offline jazykové balíčky a nakonec **extrahujeme hindský text z obrázku** bez jakéhokoli připojení k internetu. Na konci budete mít připravenou C# konzolovou aplikaci, která načte hindskou účtenku a vypíše text do konzole. + +## Co budete potřebovat + +- **.NET 6.0** nebo novější (kód také funguje na .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet balíček + `dotnet add package Aspose.OCR` +- Složka obsahující **offline hindské jazykové zdroje** (stáhněte z portálu Aspose) +- Obrázkový soubor s hindským textem, např. `receipt_hindi.png` + +A to je vše — žádné externí služby, žádné API klíče, jen přímočarý kód. + +## Provést OCR na obrázku – Krok za krokem implementace + +Níže rozdělíme proces do sedmi jasných kroků. Každý krok je vysvětlen **proč** je důležitý, ne jen **co** napsat. + +### Krok 1: Vytvořte instanci OCR enginu + +Engine je srdcem Aspose OCR. Jeho vytvoření vám poskytne přístup ke všem nastavením, která později upravíte. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +**Proč?** +> Bez `OcrEngine` nemáte objekt, na kterém byste mohli zavolat `Recognize`. Považujte ho za „kameru“, která později naskenuje váš obrázek. + +### Krok 2: Nasmerujte engine na offline zdroje + +Aspose poskytuje jazykové balíčky, které můžete uložit lokálně. Nastavením `ResourcesFolder` řeknete engine, kde má hledat. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +**Tip:** +> Používejte během vývoje absolutní cestu, poté přepněte na relativní cestu nebo konfigurační nastavení pro produkci. + +### Krok 3: Vynutit offline režim + +Možná se ptáte, „Opravdu potřebuji zakázat online vyhledávání?“ +Pokud pracujete za firewallem nebo chcete deterministické výsledky, nastavte `UseOfflineResources` na `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +**Pro tip:** +> Pokud ponecháte tento příznak na `false`, engine může stáhnout další data, což zvyšuje latenci a může porušovat bezpečnostní politiky. + +### Krok 4: Vyberte hindštinu jako rozpoznávací jazyk + +Zde **extrahujeme hindský text z obrázku** tím, že řekneme engine, jaký jazyk očekávat. To dramaticky zvyšuje přesnost. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +**Proč to pomáhá:** +> OCR enginy používají jazykově specifické modely znaků. Uzamčením na hindštinu zabráníte engine, aby hádal mezi desítkami skriptů. + +### Krok 5: Načíst obrázek pro OCR + +Nyní skutečně **načteme obrázek pro OCR**. Metoda `OcrImage.FromFile` načte bitmapu do formátu, který engine rozumí. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +**Častá chyba:** +> Zadání cesty s lomítky vpřed na Windows funguje, ale použití `Path.Combine` učiní váš kód platformově nezávislým. + +### Krok 6: Spustit rozpoznávání + +Se vším nastaveným konečně **provedeme OCR na obrázku** voláním `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +**Co se děje?** +> Engine skenuje každý pixel, porovnává vzory s databází hindských glyfů a vytváří řetězec znaků Unicode. + +### Krok 7: Výstup rozpoznaného textu + +Objekt výsledku obsahuje vlastnost `Text`, která drží extrahovaný řetězec. Jednoduše jej vypíšeme do konzole. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +**Očekávaný výstup:** +> Pokud `receipt_hindi.png` obsahuje „भुगतान सफल“, konzole vytiskne přesně tento řádek se zachováním diakritiky. + +## Načíst obrázek pro OCR – Příprava zdroje + +Pokud se ptáte, zda můžete engine napájet streamem místo souboru, odpověď je ano. Nahraďte `OcrImage.FromFile` následujícím: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +**Proč použít stream?** +> Streamy vám umožňují pracovat s obrázky uloženými v databázích, cloudových blobech nebo vložených zdrojích — ideální pro škálovatelné služby. + +## Extrahovat hindský text z obrázku – Řešení okrajových případů + +1. **Chybějící jazykový balíček** – Pokud není hindský balíček nalezen, `Recognize` vyhodí výjimku. Zabalte volání do try/catch a zaznamenejte přátelskou zprávu. +2. **Obrázky s nízkým rozlišením** – Přesnost OCR klesá pod 300 dpi. Před načtením předzpracujte obrázek (změňte velikost, zaostřete). +3. **Dokumenty s více jazyky** – Můžete povolit více jazyků: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Tyto úpravy zajistí, že vaše **perform OCR on image** rutina zůstane v produkci robustní. + +## Spuštění kompletního příkladu + +Uložte následující soubor jako `Program.cs`, nahraďte zástupné cesty a spusťte: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Když spustíte `dotnet run`, měli byste vidět něco jako: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Pokud získáte prázdný řetězec, zkontrolujte, že **ResourcesFolder** ukazuje na složku obsahující `Hindi.traineddata` a že obrázek je dostatečně čistý. + +## Závěr + +Prošli jsme, jak **perform OCR on image** soubory s Aspose OCR, pokrývajíc vše od **load image for OCR** po **extract Hindi text image** v zcela offline scénáři. Kompletní spustitelný kód výše vám poskytuje pevný základ a tipy na streamy, zpracování chyb a podporu více jazyků vám pomohou přizpůsobit řešení reálným projektům. + +Jste připraveni na další krok? Zkuste přepnout jazyk na **OcrLanguage.Tamil** nebo načítat obrázky z Azure Blob úložiště. Můžete také experimentovat s nastavením `ImagePreprocessing`, abyste zvýšili přesnost na špinavých účtenkách. + +Máte otázky nebo jste narazili na problém? Zanechte komentář — šťastné kódování! + +![Perform OCR on image example + + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s krok‑za‑krokem vysvětleními, která vám pomohou zvládnout další funkce API a prozkoumat alternativní přístupy k implementaci ve vašich projektech. + +- [Extrahovat text z obrázku C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [rozpoznat text z obrázku s Aspose OCR pro více jazyků](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Extrahovat text 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/czech/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/czech/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..a436b3ed5 --- /dev/null +++ b/ocr/czech/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-03 +description: Proveďte OCR na PDF a převěďte naskenovaný PDF na prohledávatelný PDF + pomocí Aspose.OCR. Naučte se rozpoznávat text z PDF a během několika minut vytvářet + prohledávatelná PDF. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: cs +og_description: Proveďte OCR na PDF a okamžitě vytvořte prohledávatelný PDF. Tento + tutoriál ukazuje krok za krokem, jak rozpoznat text z PDF pomocí Aspose.OCR. +og_title: Proveďte OCR v PDF – Kompletní průvodce C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Proveďte OCR na PDF pomocí Aspose.OCR – Kompletní průvodce C# +url: /cs/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Proveďte OCR na PDF pomocí Aspose.OCR – Kompletní průvodce v C# + +Už jste se někdy zamýšleli **jak provést OCR na PDF** souborech, aniž byste se museli potýkat s desítkami nástrojů příkazové řádky? Nejste v tom sami. Ať už digitalizujete faktury, archivujete staré zprávy, nebo jen potřebujete prohledávat naskenovanou smlouvu, převod statického PDF na něco, co lze skutečně vyhledávat, je obrovskou výhodou. + +V tomto průvodci vás provedeme **tím, jak vytvořit prohledávatelné PDF** soubory ze skenovaných PDF (a dokonce i z běžných obrázků) pomocí Aspose.OCR pro .NET. Na konci budete schopni **rozpoznat text z PDF** pomocí několika řádků C# kódu a pochopíte, proč se každý krok provádí, abyste mohli řešení přizpůsobit svým projektům. + +> **Rychlý výtah:** Celý proces se redukuje na tři věci — inicializaci OCR enginu, předání zdroje (PDF nebo obrázek) a uložení výstupu jako prohledávatelné PDF. Pojďme na to. + +--- + +## Co budete potřebovat + +Než začneme, ujistěte se, že máte: + +| Předpoklad | Proč je důležitý | +|------------|------------------| +| **.NET 6.0+** (nebo .NET Framework 4.6+) | Aspose.OCR cílí na moderní runtime; starší verze mohou postrádat aktualizace API. | +| **Aspose.OCR for .NET** NuGet balíček | Poskytuje třídu `OcrEngine` a utility pro práci s PDF. | +| **Platná licence Aspose** (nebo použijte bezplatnou zkušební verzi) | Bez licence narazíte na 30‑denní limit zkušební verze a vodoznaky. | +| **Skenovaný PDF** (nebo soubor s obrázkem), který chcete učinit prohledávatelným | Toto je zdrojový dokument pro OCR. | +| **Visual Studio 2022** (nebo jakýkoli C# editor) | Usnadňuje ladění, ale funguje i jakékoli IDE. | + +Knihovnu můžete nainstalovat následujícím NuGet příkazem: + +```bash +dotnet add package Aspose.OCR +``` + +> **Tip:** Pokud pracujete v CI pipeline, přidejte licenční soubor do artefaktů buildu a načtěte jej za běhu, abyste se vyhnuli hard‑coded cestám. + +--- + +## Proveďte OCR na PDF – Nastavení Aspose.OCR + +Prvním krokem potřebujeme čerstvou instanci `OcrEngine`. Představte si ji jako mozek, který bude číst váš dokument. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Proč novou instanci pokaždé? Engine drží konfiguraci (např. nastavení jazyka), která se může lišit mezi dokumenty. Vytvoření nové instance při každém spuštění zaručuje čistý stav a zabraňuje vzájemnému ovlivňování úloh. + +--- + +## Jak vytvořit prohledávatelné PDF – Nastavení hesel (volitelné) + +Pokud je váš PDF chráněn, musíte enginu předat heslo, než bude moci číst stránky: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Přeskočení tohoto kroku u chráněného souboru vyvolá `PdfPasswordException`. Vždy to obalte try‑catch blokem, pokud si nejste jisti stavem ochrany. + +--- + +## Převod skenovaného PDF na prohledávatelné PDF – Načtení zdroje + +Aspose.OCR pracuje s abstrakcí `OcrImage`, která může obalit PDF, TIFF, JPEG atd. Zde je, jak načíst skenovaný PDF do paměti: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Za scénou `FromFile` parsuje každou stránku na rastrové obrázky, které OCR engine může zpracovat. Pokud máte více‑stránkový PDF, engine automaticky iteruje přes všechny stránky. + +--- + +## Rozpoznání textu z PDF – Provádění OCR + +Nyní k jádru tutoriálu: požádejte engine, aby rozpoznal text a vytvořil prohledávatelné PDF. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` říká enginu, aby do původních skenovaných obrázků vložil neviditelnou textovou vrstvu. Výsledné PDF si zachová vizuální věrnost skenu a zároveň bude plně prohledávatelné — právě to, co potřebujete pro audity souladu. + +--- + +## Převod obrázku na prohledávatelné PDF – Uložení výsledku + +Nakonec zapíšeme binární data na disk: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Vlastnost `Binary` obsahuje surová PDF data. Můžete je také přímo streamovat do webové odpovědi, pokud budujete API. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*Alt text obrázku: Diagram ukazující tok OCR konverze pro vytvoření prohledávatelného PDF.* + +--- + +## Okrajové případy a praktické tipy + +### 1. Velké soubory a správa paměti +Pokud zpracováváte PDF větší než 100 MB, zvažte použití `OcrEngineSettings.MemoryLimit` k omezení využití paměti. Navíc zpracovávejte stránky po dávkách, abyste se vyhnuli `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Podpora jazyků +Ve výchozím nastavení Aspose.OCR předpokládá angličtinu. Pro rozpoznání jiných jazyků nastavte vlastnost `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Vícevláknové scénáře +`OcrEngine` **není** thread‑safe. Pokud potřebujete paralelní zpracování, vytvořte samostatný engine pro každý vlákno. + +### 4. Ladění přesnosti OCR +Můžete extrahovat čistý text z `ocrResult` pro ladění: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Pokud výstup vypadá poškozeně, pohrávejte si s `PreprocessSettings` (např. deskew, despeckle) pro zlepšení kvality. + +### 5. Licenční úskalí +Když spustíte evaluační verzi, Aspose přidá vodoznak do výstupního PDF. Registrujte licenci co nejdříve v aplikaci: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Kompletní funkční příklad – Od začátku do konce + +Níže je kompletní, připravený program, který zahrnuje všechny výše uvedené tipy. Klidně jej zkopírujte do nového konzolového projektu. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Očekávaný výstup:** Po spuštění uvidíte řádek v konzoli potvrzující umístění souboru. Otevřete `output.pdf` v libovolném prohlížeči PDF; zkuste napsat slovo, o kterém víte, že se v původním skenu vyskytuje. Pokud je text zvýrazněn, úspěšně **provedli jste OCR na PDF** a vytvořili prohledávatelný dokument. + +--- + +## Často kladené otázky + +**Q: Můžu to použít k převodu jediného obrázku (PNG/JPEG) na prohledávatelné PDF?** +A: Rozhodně. Nahraďte `OcrImage.FromFile("input.pdf")` cestou k vašemu obrázku. Engine rasterizuje obrázek a vloží OCR vrstvu stejným způsobem. + +**Q: Co když můj PDF obsahuje jak skenované stránky, tak nativní text?** +A: Engine překryje OCR text nad existujícím obsahem, takže nativní text zůstane výběrný a skenované stránky se stanou prohledávatelnými. + +**Q: Jaká je přesnost OCR?** +A: Přesnost závisí na kvalitě zdroje. Čisté, vysoké rozlišení skeny (>300 dpi) dosahují >95 % přesnosti. U špinavých dokumentů zapněte `PreprocessSettings` (deskew, despeckle) před voláním `Recognize`. + +--- + +## Další kroky – Rozšíření vašeho OCR nástroje + +Nyní, když umíte **rozpoznat text z PDF** a **převést skenovaný PDF na prohledávatelné PDF**, zvažte následující témata: + +- **Dávkové zpracování**: Procházejte složku PDF a automaticky generujte prohledávatelné verze. +- **Extrahování textu**: Použijte `ocrResult.Text` k napájení vyhledávacího indexu (např. Elasticsearch). +- **Vlastní jazykové balíčky**: Stáhněte si další jazyková data od Aspose pro podporu asijských skriptů. +- **PDF/A kompatibilita**: Kombinujte Aspose.PDF s OCR výstupem pro archivně připravená PDF. + +Každý z těchto kroků staví na jádrových postupech, které jsme probrali, takže jste připraveni rozšířit své řešení. + +--- + +## Závěr + +Ukázali jsme vám **jak provést OCR na PDF** souborech pomocí Aspose.OCR, jak převést skenované PDF na plně prohledávatelná PDF a dokonce i jak konvertovat běžné obrázky na prohledávatelná PDF. Kód + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s podrobným vysvětlením, aby vám pomohl zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vlastních projektech. + +- [Rozpoznání textu v PDF – OCR operace s Aspose.OCR pro Java](/ocr/english/java/ocr-operations/) +- [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íce‑stránkového OCR výsledku](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/czech/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..5a025df2e --- /dev/null +++ b/ocr/czech/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Návod na OCR titulků ve videu, který ukazuje, jak extrahovat snímky z + videa a číst text z video souborů jako MP4 pomocí Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: cs +og_description: Naučte se OCR titulků ve videu s Aspose.OCR. Extrahujte snímky z videa, + čtěte text z videa a extrahujte text z MP4 během několika minut. +og_title: OCR titulků videa v C# – krok za krokem průvodce +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR titulků videa v C# – Kompletní průvodce +url: /cs/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR titulků ve videu v C# – Kompletní průvodce + +Už jste někdy potřebovali **video subtitle ocr**, ale nebyli jste si jisti, kde začít? Nejste v tom sami. Ať už digitalizujete nahrávky přednášek, získáváte titulky z výukových videí, nebo jste jen zvědaví, jak číst text z videa, tento tutoriál vám přesně ukáže, jak to provést v C# a s Aspose.OCR. + +V následujících několika minutách extrahujeme snímky z videa, spustíme OCR na těchto snímcích a nakonec zobrazíme text titulků snímek po snímku. Na konci budete schopni **read text from video** soubory — včetně MP4 — bez hledání nástrojů třetích stran. + +## Co vytvoříte + +Vytvoříme malou konzolovou aplikaci, která: + +1. Dekóduje MP4 (nebo jakýkoli podporovaný formát) do jednotlivých `Bitmap` snímků. +2. Omezí oblast OCR na pás titulků, aby motor nebyl rozptýlený celým obrázkem. +3. Zpracuje každý snímek pomocí `VideoOcrProcessor` od Aspose. +4. Vytiskne rozpoznaný text titulků do konzole. + +Žádné zbytečnosti, jen funkční end‑to‑end příklad, který můžete vložit do reálného projektu. + +## Požadavky + +- **.NET 6.0** nebo novější (kód také funguje na .NET Framework 4.7+). +- **Aspose.OCR for .NET** – nainstalujte přes NuGet: `Install-Package Aspose.OCR`. +- Video soubor (MP4 funguje skvěle). +- Způsob dekódování video snímků – demo používá zástupnou metodu, ale můžete připojit FFmpeg, OpenCV nebo libovolnou knihovnu, která vrací objekty `Bitmap`. + +> Pro tip: Pokud používáte Windows, balíček `System.Drawing.Common` funguje dobře pro `Bitmap`. Na Linux/macOS budete potřebovat nativní závislost `libgdiplus`. + +## Krok 1 – Extrahování snímků z videa + +První překážkou je převést pohyblivý obrázek na statické snímky. Metoda `GetVideoFrames` níže je úmyslně prázdná; nahraďte ji svým oblíbeným dekodérem. Zde je rychlý náčrt pomocí FFmpeg‑Core (jen pro ilustraci tvaru dat): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Proč je to důležité:** Extrahování snímků poskytuje OCR motoru statický obrázek, se kterým může pracovat, což dramaticky zvyšuje přesnost ve srovnání s pokusem číst přímo z video proudu. + +## Krok 2 – Nastavení VideoOcrProcessor + +Nyní, když máme sekvenci objektů `Bitmap`, můžeme je předat Aspose.OCR. `VideoOcrProcessor` nám umožňuje definovat **Region of Interest (ROI)** – ideální pro titulky, které se obvykle nacházejí nahoře nebo dole ve snímku. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Proč omezit ROI?** Ignorováním zbytku obrázku snižujeme šum, zkracujeme dobu zpracování a vyhýbáme se falešným pozitivům z pozadí. + +## Krok 3 – Spuštění OCR na sekvenci snímků + +S připraveným procesorem je podávání snímků jednorázovým příkazem. Metoda `Process` vrací enumerable objektů `OcrResult`, z nichž každý obsahuje rozpoznaný text pro odpovídající snímek. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Co se děje pod kapotou?** Aspose.OCR interně normalizuje každý bitmap, spouští rozpoznávač založený na neuronové síti a poté provádí post‑processing výstupu pro zlepšení interpunkce a zalomení řádků. + +## Krok 4 – Zobrazení extrahovaného textu + +Nakonec iterujeme přes výsledky a vytiskneme každou řádku titulků. Můžete je také zapsat do SRT souboru, databáze nebo předat překladatelskému API. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Kompletní funkční příklad + +Spojením všech částí získáme samostatný konzolový program: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Očekávaný výstup (ukázka)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Pokud OCR selže u konkrétního snímku, uvidíte prázdný řetězec – to je signál, že je potřeba upravit ROI nebo zvýšit frekvenci extrakce snímků. + +## Časté problémy a jak je opravit + +| Problém | Proč se to děje | Řešení | +|-------|----------------|-----| +| **Garbage characters** | Nízké rozlišení snímků nebo silná komprese | Extrahujte snímky při vyšším bitrate, nebo před OCR zvětšete bitmapu (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI ve skutečnosti nepokrývá pás titulků | Ověřte souřadnice obdélníku (použijte nástroj pro snímání obrazovky). | +| **Performance bottleneck** | Zpracování každého snímku při 30 fps je přehnané | Down‑samplujte na 1‑2 fps pro většinu titulků; stále zachytíte každou změnu titulků. | +| **FFmpeg not found** | `ffmpeg.exe` není v `PATH` | Zadejte úplnou cestu v `ProcessStartInfo.FileName` nebo nainstalujte FFmpeg globálně. | + +## Rozšíření řešení + +- **Export do SRT** – spojte časové značky s OCR textem a zapište SubRip soubor. +- **Podpora více jazyků** – nastavte `ocrProcessor.Language = OcrLanguage.Spanish` (nebo jakýkoli podporovaný jazyk). +- **Zpracování v reálném čase** – přenášejte snímky přímo z živého proudu místo čtení z disku. + +Všechny tyto varianty stále obíhají kolem hlavních myšlenek **extract frames from video**, **read text from video** a **extract text from mp4**. + +## Závěr + +Právě jsme prošli kompletním **video subtitle ocr** pracovním postupem v C#. Extrahováním snímků z videa, zaměřením OCR na pás titulků a iterací přes výsledky můžete spolehlivě **read text from video** soubory jako MP4. Kód je připravený ke zkopírování a modulární design vám umožní vyměnit libovolný dekodér snímků, který preferujete. + +Další kroky? Zkuste exportovat výsledky do SRT souboru, experimentujte s různými velikostmi ROI nebo předejte titulky do překladatelského API pro vícejazyčné popisky. Možnosti jsou neomezené, jakmile zvládnete základy extrakce textu z videa. + +Šťastné programování a ať jsou vaše titulky vždy krystalicky čisté! + +## Co byste se měli naučit dál? + +Následující tutoriály pokrývají úzce související témata, která staví na technikách předvedených v tomto průvodci. Každý zdroj obsahuje kompletní funkční ukázky kódu s krok‑za‑krokem vysvětleními, která vám pomohou zvládnout další funkce API a prozkoumat alternativní implementační přístupy ve vašich projektech. + +- [Extrahování textu z obrázku v C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extrahování textu z obrázku pomocí Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extrahování textu z obrázku – optimalizace OCR s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/ocr-configuration/_index.md b/ocr/dutch/net/ocr-configuration/_index.md index 4eb8a034a..a7a1b6514 100644 --- a/ocr/dutch/net/ocr-configuration/_index.md +++ b/ocr/dutch/net/ocr-configuration/_index.md @@ -61,6 +61,8 @@ Ontgrendel de kracht van OCR‑beeldherkenning in .NET met Aspose.OCR. Extraheer Ontgrendel krachtige OCR‑mogelijkheden met Aspose.OCR voor .NET. Extraheer naadloze tekst uit afbeeldingen. ### [OCRO-bewerking met lijst in OCR-beeldherkenning](./ocr-operation-with-list/) Ontgrendel het potentieel van Aspose.OCR voor .NET. Voer eenvoudig OCR‑beeldherkenning uit met lijsten. Verhoog de productiviteit en data‑extractie in je applicaties. +### [Aspose OCR‑versie ophalen in C# – Complete gids](./get-aspose-ocr-version-in-c-complete-guide/) +Leer hoe je de huidige Aspose OCR‑versie in C# kunt opvragen en gebruiken in je .NET‑applicatie. ### Veelvoorkomende gebruiksscenario's - **Tekstafbeeldingen extraheren** uit gescande facturen voor praktische boekhouding. @@ -101,4 +103,4 @@ A: Ja, het `OcrResult`‑object levert vertrouwenswaarden die je programmatisch {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/dutch/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..f80033d92 --- /dev/null +++ b/ocr/dutch/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Haal de Aspose OCR‑versie op in C# met een eenvoudig fragment. Leer hoe + u de versie van de Aspose OCR‑bibliotheek kunt ophalen met OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: nl +og_description: Ha de Aspose OCR‑versie snel op in C#. Deze tutorial laat precies + zien hoe je de versie van de Aspose OCR‑bibliotheek kunt ophalen met OcrEngine GetVersion. +og_title: Aspose OCR‑versie verkrijgen in C# – Complete gids +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Krijg Aspose OCR-versie in C# – Complete gids +url: /nl/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR‑versie ophalen in C# – Complete gids + +Heb je je ooit afgevraagd hoe je **de Aspose OCR‑versie** kunt ophalen vanuit je .NET‑project? Misschien ben je een mismatch aan het oplossen, of wil je gewoon de exacte bibliotheekbuild loggen die in productie draait. Wat de reden ook is, je bent op de juiste plek beland. + +In deze tutorial lopen we een klein, zelfstandig C#‑programma door dat `OcrEngine.GetVersion()` aanroept en het resultaat afdrukt. Aan het einde weet je niet alleen *hoe* je de versie kunt ophalen, maar ook *waarom* het controleren van de versie je hoofdpijn kan besparen bij het upgraden van de **Aspose OCR library**. + +## Wat je zult leren + +- Voeg het Aspose.OCR NuGet‑pakket toe aan een C#‑project +- Gebruik de `OcrEngine.GetVersion()`‑methode (het **ocrengine getversion**‑ingangspunt) +- Afhandelen van mogelijke uitzonderingen en verifiëren van de output +- Breid de snippet uit voor real‑world scenario's zoals logging of conditionele feature‑toggles + +Ervaring met OCR is niet vereist—alleen een basisbegrip van C# en Visual Studio (of je favoriete IDE). Laten we beginnen. + +--- + +## Stap 1: Zet het project op en haal de Aspose OCR‑bibliotheek binnen + +Voordat je enige OCR‑gerelateerde API's kunt aanroepen, moet de **Aspose OCR library** in je project worden gerefereerd. + +1. Open een terminal of de Package Manager Console in Visual Studio. +2. Voer de volgende opdracht uit om de nieuwste stabiele versie te installeren: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Als je .NET Framework target in plaats van .NET Core, gebruik dan de NuGet Package Manager UI en kies de versie die bij je runtime past. Het pakket bevat de `OcrEngine`‑klasse die we later zullen gebruiken. + +### Waarom dit belangrijk is + +Wanneer je het pakket installeert, kan de assembly‑versie op schijf verschillen van de versie die de bibliotheek tijdens runtime rapporteert. Het opvragen van de versie via code zorgt ervoor dat je de exacte build leest die de CLR heeft geladen, wat cruciaal is voor debugging en voor compliance‑audits. + +## Stap 2: Schrijf de minimale code om **de Aspose OCR‑versie** op te halen + +Maak een nieuwe console‑app (`dotnet new console -n OcrVersionDemo`) en vervang de standaard `Program.cs` door het volgende: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Uitleg van elk onderdeel** + +- `using Aspose.OCR;` brengt de OCR‑namespace in scope, waardoor we `OcrEngine` kunnen aanroepen. +- `OcrEngine.GetVersion()` is de **ocrengine getversion**‑statische methode die een string retourneert zoals `"24.5.7"`. +- Het omhullen van de aanroep in een `try/catch`‑blok beschermt je tegen runtime‑verrassingen—misschien worden de native binaries niet gevonden op de doelmachine. +- De geïnterpoleerde string `$"Aspose OCR version: {version}"` drukt een duidelijke, mens‑leesbare regel af. + +### Verwachte output + +Wanneer je `dotnet run` uitvoert in de projectmap, zou je iets vergelijkbaars moeten zien: + +``` +Aspose OCR version: 24.5.7 +``` + +Als de bibliotheek niet kan worden geladen, zal de fouttak een beknopt bericht weergeven, waardoor je het probleem snel kunt lokaliseren. + +## Stap 3: Verifieer dat de versie overeenkomt met je NuGet‑pakket + +Het is gemakkelijk aan te nemen dat de NuGet‑versie die je hebt geïnstalleerd de versie is die tijdens runtime wordt gebruikt, maar omgevingspecifieke eigenaardigheden kunnen ingrijpen. Om dit dubbel te controleren: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Het uitvoeren van deze extra snippet zal iets afdrukken zoals: + +``` +Assembly file version: 24.5.7.0 +``` + +Als de twee waarden verschillen, laad je mogelijk een oudere DLL vanuit de Global Assembly Cache (GAC) of vanuit een eerdere build‑map. In dat geval, maak je oplossing schoon (`dotnet clean`) en bouw je opnieuw. + +## Stap 4: Plaats de versie‑check in productie‑logging + +De meeste real‑world toepassingen printen niet alleen naar de console; ze schrijven naar een log‑bestand of telemetriesysteem. Hier is een snel voorbeeld met `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Nu verschijnt de versie in je gestructureerde logs, waardoor je later gemakkelijk kunt filteren op `{Version}`. Dit patroon is vooral handig wanneer je meerdere micro‑services hebt die elk een mogelijk andere OCR‑DLL binnenhalen. + +## Veelgestelde vragen & randgevallen + +### Wat als `GetVersion()` een lege string retourneert? + +Dat duidt meestal op een corrupte installatie of een ontbrekende native afhankelijkheid. Installeer het NuGet‑pakket opnieuw en controleer of de `Aspose.OCR.Native.dll` (of de juiste platform‑specifieke binary) naast je executable staat. + +### Werkt de methode op .NET Core 2.0? + +Ja, **Aspose OCR** ondersteunt .NET Standard 2.0 en hoger, dus elke .NET Core‑versie die die standaard implementeert kan `OcrEngine.GetVersion()` aanroepen. Zorg er alleen voor dat je de juiste runtime‑identifiers (`win-x64`, `linux-x64`, etc.) gebruikt als je een self‑contained app publiceert. + +### Kan ik de versie ophalen zonder een licentiebestand? + +Absoluut. `GetVersion()` vereist **geen** licentie; het rapporteert simpelweg het build‑nummer van de bibliotheek. Als je echter probeert OCR uit te voeren zonder een geldige licentie, krijg je een runtime‑exception. Daarom is de `try/catch` in onze snippet waardevol—het scheidt de versie‑check van de OCR‑uitvoeringsstroom. + +## Volledig werkend voorbeeld (klaar om te kopiëren‑plakken) + +Hieronder staat het volledige programma, klaar om in een nieuw console‑project te plaatsen. Het bevat het optionele logging‑blok, zodat je zowel console‑output als gestructureerde logs in actie kunt zien. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Voer het uit met `dotnet run` en je ziet twee regels die de versie bevestigen, plus een debug‑regel als je `LogLevel.Debug` inschakelt. + +## Conclusie + +We hebben alles behandeld wat je nodig hebt om **de Aspose OCR‑versie** op te halen in een C#‑omgeving—van het installeren van de **Aspose OCR library**, het aanroepen van de **ocrengine getversion**‑methode, het afhandelen van fouten, tot het embedden van het resultaat in productie‑grade logging. Gewapend met deze kennis kun je nu betrouwbaar de exacte OCR‑build verifiëren die je applicatie gebruikt, versie‑gerelateerde bugs vermijden en voldoen aan compliance‑vereisten zonder een zweetdruppel. + +Volgende stappen? Probeer deze versie‑check te combineren met een daadwerkelijke OCR‑aanroep (`OcrEngine` → `RecognizeImage`) en log zowel de versie als het herkenningsresultaat. Je kunt ook het **retrieve aspose version**‑patroon verkennen voor andere Aspose‑producten (PDF, Slides, Cells) om je volledige suite gesynchroniseerd te houden. + +Veel plezier met coderen, en moge je OCR‑pijplijnen scherp blijven! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Hoe OCR‑resultaten op te halen met Aspose.OCR voor .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Afbeeldingstekst extraheren in C# met taalkeuze met behulp van Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Hoe OCR‑afbeeldingen in batch te verwerken met een lijst in Aspose.OCR voor .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/dutch/net/ocr-optimization/_index.md index b95973f36..1bbcbe695 100644 --- a/ocr/dutch/net/ocr-optimization/_index.md +++ b/ocr/dutch/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Verken Aspose.OCR voor .NET. Verhoog OCR‑nauwkeurigheid met preprocessing‑fi Verbeter OCR‑nauwkeurigheid met Aspose.OCR voor .NET. Corrigeer spellingen, pas woordenboeken aan en bereik moeiteloos foutloze teksterkenning. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) Ontgrendel het potentieel van Aspose.OCR voor .NET. Sla moeiteloos multipagina‑OCR‑resultaten op als documenten met deze uitgebreide stap‑voor‑stap gids. +### [Aspose OCR C#‑voorbeeld – GPU inschakelen, geheugenlimiet instellen & TIF‑afbeeldingen verwerken](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Leer hoe je GPU‑versnelling activeert, geheugenlimiet instelt en TIF‑bestanden verwerkt met Aspose OCR in C#. ## Veelgestelde vragen diff --git a/ocr/dutch/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/dutch/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..a533962d9 --- /dev/null +++ b/ocr/dutch/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C#‑voorbeeld dat laat zien hoe je de GPU‑geheugenlimiet instelt, + een afbeelding laadt voor OCR en tekst herkent uit TIF‑bestanden, met volledige + code en tips. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: nl +og_description: 'Leer een compleet Aspose OCR C#‑voorbeeld: schakel GPU in, stel de + GPU‑geheugenlimiet in, laad een afbeelding voor OCR en herken tekst uit TIF‑bestanden. + Volledige code inbegrepen.' +og_title: Aspose OCR C#-voorbeeld – GPU-versnelling, geheugenlimiet & TIF-verwerking +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C#-voorbeeld – GPU inschakelen, geheugenlimiet instellen & TIF-afbeeldingen + verwerken +url: /nl/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Voorbeeld – GPU inschakelen, geheugenlimiet instellen & TIF‑afbeeldingen verwerken + +Heb je je ooit afgevraagd hoe je de maximale prestaties uit **Aspose OCR C# example** code kunt halen bij het verwerken van enorme TIFF‑scans? Je bent niet de enige. In veel real‑world projecten—denk aan het digitaliseren van archieven of het extraheren van gegevens uit hoge‑resolutie bonnetjes—ligt de bottleneck niet bij het OCR‑algoritme zelf, maar bij het gebruik van de hardware. + +Het punt is: Aspose OCR ondersteunt GPU‑versnelling, maar je moet precies aangeven hoeveel geheugen het mag gebruiken, het juiste afbeeldingsformaat laden en uiteindelijk de herkende tekst uit een .tif‑bestand halen. Deze tutorial leidt je door elke stap, van het installeren van de SDK tot het afstemmen van de GPU‑instellingen, zodat je OCR op razendsnelle snelheid kunt uitvoeren zonder het RAM van je GPU op te blazen. + +We zullen ook een paar “wat als” scenario’s toevoegen—zoals het verwerken van multi‑page TIFFs of terugvallen op de CPU wanneer er geen GPU aanwezig is—zodat je eindigt met een robuuste oplossing, niet alleen een eenmalige snippet. + +## Wat je nodig hebt + +Voordat we beginnen, zorg ervoor dat je het volgende op je machine hebt: + +| Voorwaarde | Waarom het belangrijk is | +|------------|--------------------------| +| **.NET 6 SDK** (or later) | Aspose OCR richt zich op .NET Standard 2.0+, dus elke recente .NET‑versie werkt. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | De kernbibliotheek die `OcrEngine`, `GpuSettings`, enz. levert. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Vereist voor GPU‑versnelling; de SDK controleert bij uitvoering op een compatibele driver. | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | Zonder voldoende geheugen kan de engine stilletjes terugvallen op de CPU. | +| A **high‑resolution TIFF** image you want to process | Aspose OCR kan vrijwel elk rasterformaat lezen, maar TIF is gangbaar voor scans. | +| Visual Studio 2022 (or any editor you like) | Voor het bouwen en debuggen van het C#‑project. | + +Als een van deze ontbreekt, compileert de code nog steeds, maar je zult de prestatieverbeteringen die we zoeken niet zien. + +## Stap 1: Maak de Aspose OCR C# Example Engine + +Het eerste in elke **Aspose OCR C# example** is het instantieren van de OCR‑engine. Beschouw `OcrEngine` als de regisseur van een film—het coördineert alles van het laden van afbeeldingen tot het extraheren van tekst. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** Als je van plan bent om veel afbeeldingen achter elkaar te verwerken, houd dan één `OcrEngine` actief. Het opnieuw aanmaken per afbeelding voegt overhead toe die de OCR‑tijd kan overtreffen. + +## Stap 2: Stel GPU‑geheugenlimiet in (en schakel Versnelling in) + +Nu komt het deel dat vaak mensen in de war brengt: **GPU‑geheugenlimiet instellen**. Standaard probeert Aspose OCR zoveel mogelijk VRAM te gebruiken, wat op een gedeelde workstation andere applicaties kan verhongeren. Het `GpuSettings`‑object laat je de toewijzing beperken. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Waarom een geheugenlimiet instellen? + +- **Stabiliteit:** Voorkomt out‑of‑memory crashes bij het verwerken van gigantische afbeeldingen. +- **Co‑existence:** Stelt andere GPU‑intensieve apps (bijv. TensorFlow‑modellen) in staat om naast elkaar te draaien. +- **Voorspelbaarheid:** Maakt prestatietesten herhaalbaar omdat de GPU niet gaat swappen. + +Als je `MemoryLimitMb` weglaten, zal Aspose toewijzen wat het nodig acht, wat prima kan zijn op een dedicated inference‑server maar riskant op een ontwikkelaars‑laptop. + +## Stap 3: Laad afbeelding voor OCR + +Het juiste bestandsformaat laden is het volgende cruciale onderdeel. De methode `OcrImage.FromFile` detecteert automatisch het afbeeldings type, maar je moet toch controleren of het bestand bestaat en dat het een ondersteunde TIFF‑variant is (bijv. LZW‑gecomprimeerd of CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Verwerken van multi‑page TIFFs + +Als je TIFF meerdere pagina's bevat, leest Aspose OCR standaard alleen de eerste. Om alle pagina's te verwerken, kun je over `image.Pages` itereren (beschikbaar in nieuwere SDK‑versies) en elke pagina afzonderlijk aan de engine voeren. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +De bovenstaande snippet demonstreert een **load image for OCR** patroon dat werkt voor zowel enkel‑ als multi‑page bestanden. + +## Stap 4: Herken tekst uit TIF (of elk raster) + +Nu de afbeelding in het geheugen staat, vragen we Aspose om zijn magie te doen. De `Recognize`‑methode retourneert een `OcrResult` die de platte tekst, confidence‑scores en zelfs bounding‑box‑informatie bevat als je die nodig hebt. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Waarom dit goed werkt met TIF + +- **Lossless compressie:** TIFF slaat vaak ruwe pixeldata op, waardoor de OCR‑engine de hoogste fideliteit krijgt. +- **Meerdere kleurenruimtes:** Aspose kan grayscale, RGB of zelfs CMYK TIFFs aan zonder extra conversiecode. + +Als je taalpakketten wilt aanpassen (bijv. Frans of Japans), stel dan `ocrEngine.Settings.Language = "fr"` in vóór het aanroepen van `Recognize`. + +## Stap 5: Toon de herkende tekst + +Tot slot geven we de tekst weer in de console. In een echte applicatie kun je naar een database, een JSON‑bestand schrijven, of de string doorgeven aan een downstream NLP‑pipeline. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Verwachte output + +Het uitvoeren van het programma op een duidelijke, 300 dpi scan van een afgedrukte pagina levert doorgaans iets als volgt op: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Als de afbeelding onscherp is of de GPU‑geheugenlimiet te laag, kun je vervormde tekens of een afgekapt resultaat zien. Het verlagen van `MemoryLimitMb` onder de voetafdruk van de afbeelding (vaak ~1 GB voor een 6000×8000 pixel TIFF) kan ervoor zorgen dat de engine automatisch terugvalt op de CPU. + +## Volledig werkend voorbeeld + +Hieronder staat het volledige, kant‑klaar te draaien programma. Kopieer‑en plak het in een nieuw Console‑App‑project, vervang `YOUR_DIRECTORY/large_photo.tif` door het pad naar je eigen TIFF, en druk op **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Snelle checklist + +- ✅ **Aspose OCR C# example** gecompileerd zonder fouten. +- ✅ **GPU ingeschakeld** (`Enable = true`). +- ✅ **GPU‑geheugenlimiet** ingesteld op 2048 MB. +- ✅ **Afbeelding geladen** vanuit een TIF‑bestand. +- ✅ **Tekst herkend** en afgedrukt. + +## Veelvoorkomende valkuilen & hoe ze te vermijden + +| Symptom | Likely cause | Fix | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA‑runtime niet geïnstalleerd of versie‑mismatch. | Installeer CUDA 11.x (of 12.x) die overeenkomt met je driver. | +| OCR returns empty string | Afbeelding is te donker of DPI < 150. | Pre‑process met `image.AdjustContrast()` of hersample naar 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` te laag voor de afbeelding. | Verhoog de limiet of splits de afbeelding in tegels via `image.Crop`. | +| `Unsupported image format` error | TIFF gebruikt een exotische compressie (bijv. JPEG‑2000). | Converteer de TIFF naar een ondersteund formaat met ImageMagick vóór OCR. | + +## Demo uitbreiden + +Nu je een solide **aspose ocr c# example** hebt, wil je misschien verkennen: + +- **Batchverwerking:** Loop over een map met TIFs, schrijf elk resultaat naar een `.txt`‑bestand. +- **Taalpakketten:** `ocrEngine.Settings.Language = "es"` voor Spaans, of laad aangepaste woordenboeken. +- **Bounding boxes:** Gebruik `ocrResult.Regions` om coördinaten voor elk woord te krijgen—handig voor redactietools. +- **CPU fallback:** Plaats het GPU‑blok in een try/catch; bij falen, stel `ocrEngine.Settings.Gpu.Enable = false` in en probeer opnieuw. + +Deze uitbreidingen behouden het kernpatroon terwijl ze waarde toevoegen voor specifieke gebruik‑ + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/dutch/net/skew-angle-calculation/_index.md index 2f3f915a0..1b3691fd1 100644 --- a/ocr/dutch/net/skew-angle-calculation/_index.md +++ b/ocr/dutch/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Ontdek Aspose.OCR voor .NET, een krachtige OCR-oplossing voor nauwkeurige teksth Ontketen de kracht van Aspose.OCR voor .NET, een robuuste oplossing voor beeldherkenning. Leer hoe u moeiteloos schuine hoeken kunt berekenen. ### [Bereken de scheefhoek op basis van de URI in OCR-beeldherkenning](./calculate-skew-angle-from-uri/) Ontdek Aspose.OCR voor .NET om moeiteloos schuine hoeken te berekenen bij OCR-beeldherkenning. Verbeter uw projecten met precisie en efficiëntie. +### [OCR-gedraaid document tutorial – automatische scheefhoekcorrectie en rotatiefix in C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Leer hoe u scheve documenten automatisch corrigeert en roteert met Aspose.OCR voor .NET in C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/dutch/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..6784aa35c --- /dev/null +++ b/ocr/dutch/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: OCR-tutorial voor een gedraaid document die laat zien hoe je scheefstand + automatisch corrigeert en rotatie detecteert met Aspose OCR in C#. Leer stap voor + stap met volledige code. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: nl +og_description: OCR-gedraaid document tutorial leert je hoe je automatisch scheefstand + corrigeert en rotatie detecteert met Aspose OCR in C#. Volg de volledige gids. +og_title: OCR-gedraaid document tutorial – Automatische scheefcorrectie en rotatiefix + in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR Gedraaid Document Handleiding – Automatische scheefcorrectie en rotatiefix + in C# +url: /nl/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Rotated Document Tutorial – Volledige gids voor C#-ontwikkelaars + +Ben je ooit een **ocr rotated document tutorial** tegengekomen wanneer een gescand formulier scheef of scheef stond? Je bent niet de enige. Die scheve afbeeldingen kunnen een schone teksteextractie verpesten, maar het goede nieuws is dat Aspose OCR dit automatisch voor je kan rechtzetten. + +In deze step‑by‑step guide zullen we een `OcrEngine` opzetten, **automatic skew correction** en **auto detect rotation** inschakelen, de engine uitvoeren op een gedraaid beeld, en de schone tekst afdrukken. Aan het einde weet je precies waarom elke instelling belangrijk is, hoe je deze kunt aanpassen voor randgevallen, en heb je een kant‑klaar C#-programma. + +## Wat je zult leren + +* Hoe je **Aspose OCR** installeert en referentie toevoegt in een .NET-project. +* Waarom het inschakelen van `AutoCorrectSkew` en `AutoDetectRotation` de sleutel is tot een betrouwbare **ocr rotated document tutorial**. +* Hoe je elke afbeelding (JPG, PNG, TIFF) laadt en de engine het zware werk laat doen. +* Tips voor het verwerken van multi‑page PDF's, scans met lage resolutie, en aangepaste taalpakketten. + +> **Prerequisites:** Visual Studio 2022 (of een andere C# IDE), .NET 6+ runtime, en een geldige Aspose OCR-licentie (of de gratis proefversie). Ervaring met OCR is niet vereist. + +--- + +## Stap 1 – Installeer Aspose OCR en stel het project in + +Allereerst. Haal het NuGet‑pakket op: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Als je een proeflicentie gebruikt, plaats dan het `Aspose.OCR.lic`‑bestand in dezelfde map als je uitvoerbare bestand, of registreer het programmatisch met `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Maak een nieuwe console‑applicatie: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Nu heb je een schone basis voor onze **ocr rotated document tutorial**. + +## Stap 2 – Initialiseert de OCR‑engine + +De engine is het hart van het proces. Beschouw het als een Zwitsers zakmes voor teksteextractie; je hoeft alleen maar te vertellen welke functies ingeschakeld moeten worden. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Waarom deze instellingen?** +* `AutoCorrectSkew` analyseert de basislijn van tekens en draait de afbeelding net genoeg om de lijnen horizontaal te maken. +* `AutoDetectRotation` kijkt naar de algemene oriëntatie (0°, 90°, 180°, 270°) en draait de pagina om als deze ondersteboven staat. Zonder deze zou de engine “pɹᴉʍ” lezen in plaats van “word”. + +## Stap 3 – Laad de afbeelding die je wilt verwerken + +Aspose OCR werkt met elk gangbaar rasterformaat. Vervang het tijdelijke pad door de werkelijke locatie van je gedraaide formulier. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** Als je een multi‑page TIFF ontvangt, gebruik dan `OcrImage.FromMultiPageTiff(filePath)` en loop door `image.Pages`. + +## Stap 4 – Voer de herkenning uit + +Nu doet de engine de magie. Hij zal eerst de afbeelding rechtzetten (dankzij onze skew/rotatie‑vlaggen) en vervolgens de tekens extraheren. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Als je taalondersteuning nodig hebt naast Engels, stel dit dan in vóór het aanroepen van `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Stap 5 – Output de herkende tekst + +Tot slot, dump de schone tekst naar de console — of leid het door naar een bestand, een database, wat ook maar past in je workflow. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Verwachte output** (ervan uitgaande dat de voorbeeldafbeelding “Invoice #1234” bevat): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Merk op hoe de tekst correct verschijnt, hoewel de bronafbeelding 90° gedraaid en licht scheef was. + +--- + +## Veelvoorkomende valkuilen behandelen + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Lege output** | Skew-correctie uitgeschakeld of afbeelding te donker. | Schakel `AutoCorrectSkew` in (reeds actief) en verhoog het contrast van de afbeelding via `image.AdjustContrast(1.2)`. | +| **Onzin tekens** | Verkeerde taalinstelling. | Stel `ocrEngine.Settings.Language` in op de taal van het document. | +| **Prestatievertraging bij grote PDF's** | Engine verwerkt elke pagina achtereenvolgens. | Gebruik `Parallel.ForEach` op `image.Pages` om multi‑core CPU's te benutten. | +| **Licentie‑exception** | Proefperiode verlopen. | Verkrijg een permanente licentie of blijf binnen de proeflimieten (5 pagina's per uitvoering). | + +## Pro‑tips voor een robuuste OCR Rotated Document Tutorial + +* **Batchverwerking:** Plaats de volledige stroom in een methode die een mappad accepteert, over elke afbeelding iterereert en elk resultaat naar een `.txt`‑bestand schrijft. +* **Pre‑processing:** Soms profiteert een ruisvolle scan van `image.Denoise()` vóór herkenning. +* **Post‑processing:** Gebruik reguliere expressies om veelvoorkomende OCR‑fouten op te schonen, bv. vervang “0” door “O” alleen wanneer het omgeven is door letters. +* **Logging:** Aspose OCR biedt `ocrEngine.Logger` – koppel dit aan een bestandslogger om waarschuwingen over lage vertrouwensscores vast te leggen. + +## Complete, kant‑klaar code + +Sla het volgende op als `Program.cs` in je console‑project. Het bevat alle stappen, commentaren, en een kleine helper voor batchverwerking. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Voer het uit: + +```bash +dotnet run +``` + +Je zou de opgeschoonde tekst in de console moeten zien verschijnen, wat bewijst dat onze **ocr rotated document tutorial** end‑to‑end werkt. + +## Conclusie + +Je hebt nu een volledige **ocr rotated document tutorial** die automatisch scheefstand corrigeert, rotatie detecteert en schone tekst extraheert met Aspose OCR in C#. De belangrijkste conclusie? Het inschakelen van `AutoCorrectSkew` **en** `AutoDetectRotation` maakt van een hopeloos scheve scan een perfect leesbare output met slechts een paar regels code. + +Vanaf hier kun je uitbreiden naar batchtaken, taalpakketten integreren, of de resultaten doorvoeren in downstream analytics‑pijplijnen. Wil je **automatic skew correction** verder verkennen? Bekijk de image‑preprocessing‑API van Aspose, of experimenteer met aangepaste drempels voor ruisvolle scans. + +Heb je vragen over het verwerken van PDF's, multi‑page TIFF's, of integratie met Azure Functions? Laat een reactie achter, en veel plezier met coderen! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden gedemonstreerd. Elke bron bevat volledige werkende codevoorbeelden met stapsgewijze uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [ocr documentmodus – Detect Areas-modus in OCR-afbeeldingsherkenning](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Afbeeldingstekst extraheren in C# met taalkeuze via Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optische tekenherkenning](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/dutch/net/text-recognition/_index.md index e39716b53..0a73fc22a 100644 --- a/ocr/dutch/net/text-recognition/_index.md +++ b/ocr/dutch/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Ontketen de kracht van Aspose.OCR voor .NET. Leer moeiteloos OCR-resultaten in J Verbeter uw .NET-toepassingen met Aspose.OCR voor efficiënte beeldtekstherkenning. Ontdek de OCR-modus voor detectiegebieden voor nauwkeurige resultaten. ### [Herken PDF in OCR-beeldherkenning](./recognize-pdf/) Ontgrendel het potentieel van OCR in .NET met Aspose.OCR. Extraheer moeiteloos tekst uit PDF's. Download nu voor een naadloze integratie-ervaring. +### [Voer OCR uit op PDF met Aspose OCR – Complete C#-gids](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Leer hoe u met Aspose OCR PDF-bestanden kunt verwerken in C#. Volg onze stapsgewijze handleiding voor optimale OCR-resultaten. ### [Herken tabel in OCR-beeldherkenning](./recognize-table/) Ontgrendel het potentieel van Aspose.OCR voor .NET met onze uitgebreide gids over het herkennen van tabellen bij OCR-beeldherkenning. +### [Voer OCR uit op afbeelding met Aspose OCR – Hindi-gids](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Leer hoe u met Aspose OCR Hindi-teksten uit afbeeldingen haalt. Volg onze stapsgewijze handleiding voor optimale resultaten. +### [Hoe Aspose te gebruiken: afbeelding naar HTML converteren met OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Leer hoe u met Aspose OCR afbeeldingen naar HTML kunt converteren, zodat u gestructureerde tekst kunt weergeven in uw .NET-toepassingen. +### [Voer OCR uit op afbeelding en detecteer spelfouten in C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Leer hoe u met Aspose OCR afbeeldingen kunt verwerken en spelfouten kunt detecteren in C#. Volg onze stap‑voor‑stap handleiding. +### [Video-ondertitel OCR in C# – Complete gids](./video-subtitle-ocr-in-c-complete-guide/) +Leer hoe u met Aspose OCR ondertitels uit video's haalt in C#. Volg onze stapsgewijze handleiding voor volledige OCR-functionaliteit. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/dutch/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..f0eb9e000 --- /dev/null +++ b/ocr/dutch/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Hoe gebruik je Aspose om een afbeelding naar HTML te converteren en tekst + uit een afbeelding te extraheren in C#. Leer snel HTML genereren vanuit een afbeelding + en OCR toepassen op een afbeelding naar HTML. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: nl +og_description: Hoe je Aspose gebruikt om een afbeelding naar HTML te converteren, + tekst uit een afbeelding te extraheren en HTML uit een afbeelding te genereren met + OCR in C#. Volg deze volledige gids. +og_title: 'Hoe Aspose te gebruiken: afbeelding naar HTML converteren met OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Hoe Aspose te gebruiken: afbeelding naar HTML converteren met OCR' +url: /nl/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe Aspose te gebruiken: Afbeelding naar HTML converteren met OCR + +Heb je je ooit afgevraagd **hoe je Aspose** kunt gebruiken om een gescande foto om te zetten in nette HTML? Misschien heb je een tijdschriftpagina, een bon of een handgeschreven notitie en moet je de tekst en lay‑out behouden voor webpublicatie. Het goede nieuws is dat je geen eigen parser hoeft te schrijven of te worstelen met low‑level beeldverwerking—Aspose.OCR doet het zware werk voor je. + +In deze tutorial lopen we een **volledig, uitvoerbaar voorbeeld** door dat laat zien hoe je **image to HTML** kunt **convert image to HTML**, **extract text from image**, en **generate HTML from image** gebruikt met de Aspose OCR‑bibliotheek in C#. Aan het einde heb je een kleine console‑app die een HTML‑bestand produceert met de originele paginalay‑out intact, klaar om in elke website te worden geplaatst. + +## Voorvereisten + +Voordat we beginnen, zorg dat je het volgende op je machine hebt: + +- **.NET 6.0 SDK** of later (de code werkt zowel met .NET Core als .NET Framework). +- **Visual Studio 2022** (of een andere editor naar keuze). +- **Aspose.OCR for .NET** – installeer via NuGet: `dotnet add package Aspose.OCR`. +- Een afbeeldingsbestand (JPEG/PNG) dat je wilt transformeren, bijv. `magazine_page.jpg`. + +Er zijn geen extra configuratie‑bestanden nodig; de bibliotheek wordt geleverd met alles wat nodig is voor OCR en HTML‑lay‑outgeneratie. + +## Stap 1: Het project opzetten en Aspose.OCR toevoegen + +Eerst maak je een nieuw console‑project aan en haal je het Aspose OCR‑pakket binnen. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Als je Visual Studio gebruikt, klik dan simpelweg met de rechtermuisknop op het project → *Manage NuGet Packages* → zoek naar **Aspose.OCR** en installeer het. Deze stap zorgt ervoor dat je **ocr image to html** kunt uitvoeren zonder ontbrekende referenties. + +## Stap 2: De OCR‑engine initialiseren + +De kern van het proces is de `OcrEngine`‑klasse. Beschouw het als het brein dat de afbeelding leest en beslist hoe het resultaat moet worden uitgegeven. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Hier instantieren we `OcrEngine`. Je hoeft geen inloggegevens door te geven voor de gratis versie; de bibliotheek gebruikt zijn ingebouwde herkenningsmodellen. + +## Stap 3: Laad de bronafbeelding + +Vervolgens wijs je de engine naar het bestand dat je wilt verwerken. Aspose biedt een handige `OcrImage.FromFile`‑methode die de meeste afbeeldingsformaten aankan. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Vervang `YOUR_DIRECTORY` door het absolute of relatieve pad waar je afbeelding zich bevindt. Als de afbeelding in dezelfde map staat als het uitvoerbare bestand, kun je gewoon `"magazine_page.jpg"` gebruiken. + +## Stap 4: Herkennen en HTML met lay‑out aanvragen + +Dit is het hart van de tutorial. Door `OutputFormat.HtmlWithLayout` door te geven, vertellen we Aspose **HTML from image** te **generate HTML from image** terwijl de oorspronkelijke positionering van tekstblokken, afbeeldingen en tabellen behouden blijft. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +De eigenschap `recognitionResult.Text` bevat nu een volledig HTML‑document. Als je alleen platte tekst nodig had, kun je `OutputFormat.Text` gebruiken, maar we richten ons op **convert image to html** met lay‑outgetrouwheid. + +## Stap 5: Sla het HTML‑bestand op + +Schrijf tenslotte de HTML‑string naar schijf. Zo krijg je een kant‑klaar bestand dat je in elke browser kunt openen. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Het uitvoeren van het programma levert `magazine.html` op. Open het, en je ziet de originele paginatekst precies gepositioneerd zoals in de bronafbeelding—perfect voor archivering of webpublicatie. + +## Volledig werkend voorbeeld + +Hieronder staat het **complete, copy‑paste‑ready** programma. Er ontbreken geen delen, zodat je het meteen kunt compileren en uitvoeren nadat je de juiste paden hebt ingesteld. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Verwachte output + +Wanneer je `magazine.html` in een browser opent, zie je iets dat hierop lijkt (vereenvoudigd voor illustratie): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +De exacte `style`‑attributen zullen verschillen op basis van de originele afbeelding, maar de structuur garandeert dat **extract text from image** en **generate html from image** in één naadloze stap plaatsvinden. + +## Veelgestelde vragen & randgevallen + +### Wat als de afbeelding een lage resolutie heeft? + +Aspose.OCR werkt het beste met afbeeldingen van minimaal **300 DPI**. Als je bestand wazig is, probeer het dan eerst voor te bewerken met een beeld‑verbeteringsbibliotheek (bijv. ImageSharp) voordat je het aan de OCR‑engine geeft. Lage kwaliteit kan zowel de **extract text from image**‑nauwkeurigheid als de getrouwe weergave van de gegenereerde HTML‑lay‑out beïnvloeden. + +### Kan ik de taal van de OCR regelen? + +Ja. Stel de `Language`‑eigenschap in op de `OcrEngine` voordat je `Recognize` aanroept: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Dit verbetert de herkenning bij niet‑Engelse tekens. + +### Hoe krijg ik platte tekst in plaats van HTML? + +Als je alleen de ruwe tekenreeks nodig hebt, vervang je `OutputFormat.HtmlWithLayout` door `OutputFormat.Text`. Dezelfde `recognitionResult.Text` zal dan alleen de geëxtraheerde karakters bevatten. + +### Is er een manier om afbeeldingen in de gegenereerde HTML in te sluiten? + +Aspose.OCR kan de originele afbeelding embedden als een base‑64 data‑URI wanneer je `OutputFormat.HtmlWithLayoutAndImages` gebruikt. Handig als je één HTML‑bestand wilt zonder externe assets. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Hoe zit het met het verwerken van grote batches? + +Voor batchverwerking, plaats de logica in een `foreach`‑lus over een lijst met bestands‑paden. Het hergebruiken van dezelfde `OcrEngine`‑instantie vermindert overhead en versnelt de **convert image to html**‑pipeline. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tips voor productie‑klare code + +- **Dispose resources**: Zowel `OcrEngine` als `OcrImage` implementeren `IDisposable`. Plaats ze in `using`‑blokken om native geheugen tijdig vrij te geven. +- **Error handling**: Vang `IOException` af voor bestandsgerelateerde problemen en `OcrException` voor herkenningsfouten. +- **Performance**: Als je veel afbeeldingen verwerkt, overweeg dan **parallelisme** (`Parallel.ForEach`) maar houd rekening met CPU‑gebruik—OCR is CPU‑intensief. +- **Logging**: Integreer een logger (bijv. Serilog) om OCR‑vertrouwensscores (`recognitionResult.Confidence`) vast te leggen voor kwaliteitsmonitoring. + +## Conclusie + +We hebben net behandeld **hoe je Aspose** kunt **convert image to HTML**, **extract text from image**, en **generate HTML from image** in een paar eenvoudige stappen. Het volledige code‑voorbeeld laat zien hoe je **ocr image to html** kunt uitvoeren terwijl de lay‑out behouden blijft, wat een solide basis vormt voor elk document‑digitaliseringsproject. + +Vanaf hier kun je: + +- Experimenteren met verschillende `OutputFormat`‑opties om aan je behoeften te voldoen. +- De HTML‑output combineren met een CSS‑framework voor responsieve styling. +- De geëxtraheerde tekst voeden aan een zoekindex of een machine‑learning‑pipeline. + +Probeer het, pas de instellingen aan, en zie hoe moeiteloos Aspose afbeeldingen omzet in web‑klaar content. Als je ergens tegenaan loopt, laat een reactie achter—happy coding! + +![Diagram van OCR-pijplijn van afbeelding naar HTML‑lay-out – hoe Aspose te gebruiken](/images/ocr-pipeline.png "hoe Aspose te gebruiken") + +--- + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn gedemonstreerd. Elke bron bevat complete werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Afbeeldingstekst extraheren in C# met taalkeuze met Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Afbeelding naar tekst converteren – OCR uitvoeren op afbeelding vanuit URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/dutch/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..ee98b82ba --- /dev/null +++ b/ocr/dutch/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-03 +description: Voer OCR uit op een afbeelding en extraheer tekst uit de afbeelding met + Aspose.OCR. Leer hoe je spelfouten kunt detecteren en spellingsuggesties kunt krijgen + in één C#‑demo. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: nl +og_description: Voer OCR uit op een afbeelding om tekst uit de afbeelding te extraheren, + detecteer vervolgens verkeerd gespelde woorden en krijg spellingsuggesties met Aspose.OCR + in C#. +og_title: Voer OCR uit op afbeelding en detecteer verkeerd gespelde woorden in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Voer OCR uit op afbeelding en detecteer verkeerd gespelde woorden in C# +url: /nl/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR uitvoeren op afbeelding en spelfouten detecteren in C# + +Heb je je ooit afgevraagd hoe je **OCR op afbeelding** kunt uitvoeren zonder je haar uit te trekken? Je bent niet de enige. Of je nu oude brieven digitaliseert, bonnetjes scant of een slimme documentworkflow bouwt, ruwe tekst uit afbeeldingen halen is de eerste horde. Het goede nieuws? Met Aspose.OCR kun je in enkele minuten een oplossing opzetten, en het extra voordeel is dat je ook **spelfouten kunt detecteren** en **spellingsuggesties kunt krijgen** in dezelfde run. + +In deze tutorial lopen we stap voor stap door een complete, kant‑klaar C# console‑applicatie die **tekst uit afbeelding** extraheert, een Engelse spellingscontrole uitvoert en elke fout met handige correctie‑ideeën afdrukt. Aan het einde weet je precies **hoe je tekst extraheert**, hoe je de spell‑check‑API aanroept en hoe de verwachte console‑output eruitziet. + +## Wat je gaat bouwen + +- Een bitmap (of PNG) laden die typografische fouten bevat. +- Aspose.OCR gebruiken om **OCR op afbeelding** uit te voeren en ruwe string‑data te verkrijgen. +- De ingebouwde Engelse spell‑checker initialiseren. +- **Spelfouten detecteren** en **spellingsuggesties krijgen** voor elk woord. +- Een nette rapportage naar de console afdrukken. + +Geen externe services, geen ingewikkelde HTTP‑calls—slechts één NuGet‑pakket en een handvol regels code. + +## Vereisten + +- .NET 6.0 SDK of later (de code werkt ook op .NET Framework 4.7+). +- Visual Studio 2022 (of een andere editor naar keuze). +- Aspose.OCR for .NET NuGet‑pakket (`Aspose.OCR`). +- Een afbeeldingsbestand (`letter_with_typos.png`) ergens geplaatst zodat je er vanuit het project naar kunt verwijzen. + +Als je Aspose nog nooit hebt gebruikt, geen zorgen—het installeren van het pakket is net zo simpel als het uitvoeren van: + +```bash +dotnet add package Aspose.OCR +``` + +Laten we nu de implementatie induiken. + +## Stap 1: Het project opzetten en Aspose.OCR installeren + +Maak een nieuw console‑project aan en haal de OCR‑bibliotheek binnen: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Nadat het restore‑proces is voltooid, open je `Program.cs`. We zullen later de standaardinhoud vervangen door de volledige demo‑code, maar eerst bespreken we waarom elke namespace belangrijk is. + +- `Aspose.OCR` – Kern‑OCR‑engine en afbeeldingsverwerking. +- `Aspose.OCR.SpellCheck` – Spell‑checking‑hulpmiddelen die bij de bibliotheek worden geleverd. +- `System` – Standaard .NET‑basisklassen (bijv. `Console`). + +## Stap 2: De afbeelding laden en OCR op afbeelding uitvoeren + +Het eerste echte werk is de afbeelding aan de OCR‑engine voeren. Aspose.OCR leest vele formaten (PNG, JPEG, TIFF). Hieronder staat het fragment dat het zware werk doet: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Waarom dit belangrijk is:** `OcrImage.FromFile` abstraheert de pixel‑niveau details, terwijl `OcrEngine.Recognize` het getrainde neurale model draait dat visuele glyphs omzet in Unicode‑tekens. De eigenschap `ocrResult.Text` bevat nu de ruwe string—precies wat je nodig hebt om **tekst uit afbeelding** te **extraheren**. +> +> **Pro tip:** Als je afbeelding meerdere talen bevat, kun je `ocrEngine.Language = OcrLanguage.Multilingual;` instellen vóór het aanroepen van `Recognize`. + +## Stap 3: De Engelse spell‑checker initialiseren + +Aspose.OCR wordt geleverd met een ingebouwde spell‑checking engine die Engels direct ondersteunt. Initialiseren is één regel: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Waarom deze stap cruciaal is:** De OCR‑output kan verkeerd herkende tekens bevatten (bijv. “l” vs “1”) of echte typefouten uit het bron‑document. De spell‑checker scant de string, lokaliseert verdachte tokens en stelt alternatieven voor. + +## Stap 4: Spelfouten detecteren en spellingsuggesties krijgen + +Nu voeren we de OCR‑tekst in de checker: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` is een collectie waarbij elk item het foutieve woord en een array met mogelijke correcties bevat. + +## Stap 5: De resultaten weergeven + +Tot slot itereren we over de collectie en printen we een mens‑leesbaar rapport: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Verwachte console‑output + +Stel dat `letter_with_typos.png` de zin bevat: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Het uitvoeren van de demo levert iets als het volgende op: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Merk op dat elke typefout wordt gekoppeld aan een handvol plausibele correcties—precies wat je nodig hebt bij het bouwen van een gebruiksvriendelijke correctie‑UI. + +## Volledig werkend voorbeeld + +Hieronder staat het **complete, copy‑paste‑klare** programma. Vervang `YOUR_DIRECTORY` door het daadwerkelijke pad naar je afbeeldingsbestand. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Randgevallen om in overweging te nemen** +> - **Lege afbeelding:** Als de OCR‑engine een lege string retourneert, zal `spellChecker.Check` simpelweg een lege collectie teruggeven—geen crash. +> - **Niet‑Engelse tekst:** Vervang `OcrLanguage.English` door `OcrLanguage.French` (of een andere ondersteunde taal) om **spelfouten te detecteren** in andere locale. +> - **Grote documenten:** Voor multi‑page PDF’s zou je over elke pagina itereren, OCR uitvoeren en vervolgens de resultaten aggregeren vóór het spell‑checken. + +## Visueel overzicht (Afbeeldings‑alt‑tekst) + +![Diagram dat de stroom toont om OCR op afbeelding uit te voeren, tekst uit afbeelding te extraheren en vervolgens spelfouten met spellingsuggesties te detecteren](perform-ocr-on-image-flow.png) + +*Het diagram hierboven illustreert de end‑to‑end‑pipeline: afbeelding → OCR‑engine → ruwe tekst → spell‑checker → suggesties.* + +## Veelgestelde vragen & Pro‑tips + +| Vraag | Antwoord | +|----------|--------| +| **Heb ik een internetverbinding nodig?** | Nee. Aspose.OCR draait volledig lokaal; perfect voor offline of beveiligde omgevingen. | +| **Hoe nauwkeurig is de spell‑checker?** | Hij gebruikt een woordenboek van ~150 k Engelse woorden en fuzzy matching, dus de meeste gangbare typefouten worden opgevangen. | +| **Kan ik het woordenboek aanpassen?** | Ja. `SpellChecker.AddUserDictionary("custom.txt")` laat je domeinspecifieke termen (bijv. productnamen) laden. | +| **Wat als de afbeelding scheef staat?** | De OCR‑engine detecteert automatisch de oriëntatie, maar je kunt handmatig `ocrEngine.ImagePreprocessing.Rotate(angle)` aanroepen voor hardnekkige gevallen. | +| **Is er een manier om suggesties te markeren in de UI?** | Nadat je de `misspellings`‑collectie hebt, kun je elk `entry.Word` terugkoppelen naar de positie in `ocrResult.Text` en onderstrepen in een RichTextBox of web‑view. | + +## Conclusie + +We hebben je laten zien **hoe je OCR op afbeelding uitvoert**, **tekst uit afbeelding extraheert**, en vervolgens **spelfouten detecteert** terwijl je **spellingsuggesties krijgt**—alles met een beknopte C# console‑app. Het kernidee is simpel: laat Aspose.OCR het zware werk van tekenherkenning doen, en laat de ingebouwde spell‑checker de output opschonen. Vanaf hier kun je de demo uitbreiden tot een volledige documentverwerkingsservice, integreren met een web‑API, of koppelen aan een desktop‑editor. + +Klaar voor de volgende stap? Probeer de taal te wisselen naar Spaans, voer een multi‑page PDF in, of bouw een kleine WPF‑frontend waarmee gebruikers op een woord kunnen klikken om een suggestie te accepteren. De bouwblokken liggen al klaar—blijf experimenteren. + +Als je tegen problemen aanloopt of ideeën hebt voor uitbreidingen, laat dan een reactie achter. Happy coding! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/dutch/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..5bff6c174 --- /dev/null +++ b/ocr/dutch/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Voer OCR uit op een afbeelding met Aspose OCR in C#. Leer hoe je een + afbeelding laadt voor OCR en offline Hindi‑tekst uit een afbeelding haalt met stapsgewijze + code. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: nl +og_description: Voer OCR uit op een afbeelding met Aspose OCR in C#. Deze tutorial + laat zien hoe je een afbeelding laadt voor OCR en offline Hindi-tekst uit een afbeelding + extraheert, compleet met uitvoerbare code. +og_title: Voer OCR uit op afbeelding – Aspose OCR Hindi-gids +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Voer OCR uit op afbeelding met Aspose OCR – Hindi-gids +url: /nl/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR uitvoeren op afbeelding met Aspose OCR – Hindi‑gids + +Heb je ooit **OCR op afbeelding** moeten uitvoeren maar zat je vast bij het verkrijgen van Hindi‑tekens? Je bent niet de enige—veel ontwikkelaars lopen tegen die muur aan wanneer ze voor het eerst niet‑Latijnse scripts proberen te lezen. Het goede nieuws is dat Aspose OCR het behoorlijk eenvoudig maakt, en je kunt het zelfs volledig offline doen. + +In deze gids **laden we een afbeelding voor OCR**, wijzen we de engine naar je offline taalpakketten, en uiteindelijk **extraheren we Hindi‑tekst uit een afbeelding** zonder ooit internet te gebruiken. Aan het einde heb je een kant‑klaar C#‑console‑applicatie die een Hindi‑bon leest en de tekst naar de console print. + +## Wat je nodig hebt + +- **.NET 6.0** of later (de code werkt ook met .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet‑pakket + `dotnet add package Aspose.OCR` +- Een map met de **offline Hindi‑taalresources** (download van het Aspose‑portaal) +- Een afbeeldingsbestand met Hindi‑tekst, bijvoorbeeld `receipt_hindi.png` + +Dat is alles—geen externe services, geen API‑sleutels, alleen recht‑toe‑rechtaan code. + +## OCR uitvoeren op afbeelding – Stapsgewijze implementatie + +Hieronder splitsen we het proces in zeven duidelijke stappen. Elke stap wordt uitgelegd **waarom** het belangrijk is, niet alleen **wat** je moet typen. + +### Stap 1: Maak een OCR‑engine‑instantie + +De engine is het hart van Aspose OCR. Door een instantie te maken krijg je toegang tot alle instellingen die je later zult aanpassen. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Waarom?** +> Zonder een `OcrEngine` heb je geen object om `Recognize` op aan te roepen. Beschouw het als de “camera” die later je afbeelding scant. + +### Stap 2: Wijs de engine naar offline resources + +Aspose levert taalpakketten die je lokaal kunt opslaan. Het instellen van `ResourcesFolder` vertelt de engine waar hij moet zoeken. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tip:** +> Gebruik een absoluut pad tijdens ontwikkeling, en schakel later over naar een relatief pad of een configuratie‑instelling voor productie. + +### Stap 3: Forceer offline‑modus + +Je vraagt je misschien af: “Moet ik echt online opzoekacties uitschakelen?” +Als je achter een firewall werkt of gewoon deterministische resultaten wilt, zet je `UseOfflineResources` op `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro‑tip:** +> Het laten staan van deze vlag op `false` kan ertoe leiden dat de engine extra data downloadt, wat latentie toevoegt en mogelijk beveiligingsbeleid schendt. + +### Stap 4: Selecteer Hindi als herkennings‑taal + +Hier **extraheren we Hindi‑tekst uit een afbeelding** door de engine te vertellen welke taal verwacht wordt. Dit verbetert de nauwkeurigheid drastisch. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Waarom het helpt:** +> OCR‑engines gebruiken taalspecifieke tekenmodellen. Door vast te zetten op Hindi voorkom je dat de engine moet gokken tussen tientallen scripts. + +### Stap 5: Laad afbeelding voor OCR + +Nu **laden we de afbeelding voor OCR**. De methode `OcrImage.FromFile` leest de bitmap in een formaat dat de engine begrijpt. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Veelvoorkomende valkuil:** +> Een pad met schuine strepen (`/`) werkt op Windows, maar `Path.Combine` maakt je code platform‑onafhankelijk. + +### Stap 6: Voer de herkenning uit + +Met alles ingesteld voeren we eindelijk **OCR uit op afbeelding** uit door `Recognize` aan te roepen. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Wat gebeurt er?** +> De engine scant elke pixel, vergelijkt patronen met de Hindi‑glyph‑database en bouwt een string van Unicode‑tekens op. + +### Stap 7: Output van de herkende tekst + +Het resultaatobject bevat een `Text`‑eigenschap die de geëxtraheerde string bevat. We schrijven deze simpelweg naar de console. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Verwachte output:** +> Als `receipt_hindi.png` “भुगतान सफल” bevat, zal de console precies die regel afdrukken, inclusief diakritische tekens. + +## Afbeelding laden voor OCR – De resource voorbereiden + +Vraag je je af of je de engine een stream kunt geven in plaats van een bestand? Het antwoord is ja. Vervang `OcrImage.FromFile` door: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Waarom een stream gebruiken?** +> Streams laten je werken met afbeeldingen die in databases, cloud‑blobs of ingebedde resources staan—perfect voor schaalbare services. + +## Hindi‑tekst uit afbeelding extraheren – Randgevallen afhandelen + +1. **Ontbrekend taalpakket** – Als het Hindi‑pakket niet wordt gevonden, gooit `Recognize` een uitzondering. Plaats de aanroep in een try/catch en log een vriendelijke melding. +2. **Laag‑resolutie‑afbeeldingen** – OCR‑nauwkeurigheid daalt onder 300 dpi. Pre‑process de afbeelding (schalen, verscherpen) vóór het laden. +3. **Documenten met meerdere talen** – Je kunt meerdere talen inschakelen: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Deze aanpassingen zorgen ervoor dat je **OCR uitvoeren op afbeelding**‑routine robuust blijft in productie. + +## Het volledige voorbeeld uitvoeren + +Sla het volgende bestand op als `Program.cs`, vervang de voorbeeld‑paden, en voer uit: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Wanneer je `dotnet run` uitvoert, zou je iets moeten zien als: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Als je een lege string krijgt, controleer dan of de **ResourcesFolder** naar de map wijst die `Hindi.traineddata` bevat en of de afbeelding voldoende duidelijk is. + +## Conclusie + +We hebben stap voor stap laten zien hoe je **OCR op afbeelding**‑bestanden uitvoert met Aspose OCR, van **afbeelding laden voor OCR** tot **Hindi‑tekst uit afbeelding extraheren** in een volledig offline scenario. De complete, uitvoerbare code hierboven biedt een solide basis, en de tips over streams, foutafhandeling en meertalige ondersteuning helpen je de oplossing aan te passen aan real‑world projecten. + +Klaar voor de volgende stap? Probeer de taal te wijzigen naar **OcrLanguage.Tamil** of afbeeldingen vanuit Azure Blob Storage te lezen. Je kunt ook experimenteren met de `ImagePreprocessing`‑instellingen om de nauwkeurigheid op ruisende bonnetjes te verhogen. + +Vragen of een probleem? Laat een reactie achter—happy coding! + +![Voorbeeld van OCR op afbeelding + +## Wat moet je hierna leren? + + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Afbeeldingstekst extraheren in C# met taalkeuze via Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Tekst in afbeelding herkennen met Aspose OCR voor meerdere talen](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [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/dutch/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/dutch/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..bf0a84230 --- /dev/null +++ b/ocr/dutch/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-03 +description: Voer OCR uit op PDF en zet een gescande PDF om naar doorzoekbare PDF + met Aspose.OCR. Leer hoe je tekst uit PDF herkent en in enkele minuten doorzoekbare + PDF's maakt. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: nl +og_description: Voer OCR uit op PDF en maak direct een doorzoekbare PDF. Deze tutorial + laat stap voor stap zien hoe je tekst uit een PDF herkent met Aspose.OCR. +og_title: OCR uitvoeren op PDF – Complete C#-gids +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Voer OCR uit op PDF met Aspose.OCR – Complete C#-gids +url: /nl/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR uitvoeren op PDF met Aspose.OCR – Complete C# Gids + +Heb je je ooit afgevraagd **hoe je OCR op PDF**‑bestanden kunt uitvoeren zonder te worstelen met tientallen command‑line‑tools? Je bent niet de enige. Of je nu facturen digitaliseert, oude rapporten archiveert, of gewoon een doorzoekbare versie van een gescande overeenkomst nodig hebt, het omzetten van een statische PDF naar iets waar je daadwerkelijk in kunt zoeken is een echte game‑changer. + +In deze gids lopen we stap voor stap door **hoe je doorzoekbare PDF**‑bestanden maakt van gescande PDF’s (en zelfs van gewone afbeeldingen) met Aspose.OCR voor .NET. Aan het einde kun je **tekst herkennen uit PDF** met een paar regels C#‑code, en begrijp je de reden achter elke stap zodat je de oplossing kunt aanpassen aan je eigen projecten. + +> **Snelle samenvatting:** Het hele proces draait om drie dingen – het initialiseren van de OCR‑engine, het voeden van de bron (PDF of afbeelding), en het opslaan van de doorzoekbare PDF‑output. Laten we beginnen. + +--- + +## Wat je nodig hebt + +Voordat we starten, zorg dat je het volgende hebt: + +| Voorwaarde | Waarom het belangrijk is | +|------------|--------------------------| +| **.NET 6.0+** (of .NET Framework 4.6+) | Aspose.OCR richt zich op moderne runtimes; oudere versies missen mogelijk API‑updates. | +| **Aspose.OCR for .NET** NuGet‑pakket | Biedt de `OcrEngine`‑klasse en PDF‑verwerkingshulpmiddelen. | +| **Een geldige Aspose‑licentie** (of gebruik de gratis evaluatie) | Zonder licentie krijg je een 30‑daagse evaluatielimiet en watermerken. | +| **Een gescande PDF** (of een afbeeldingsbestand) die je doorzoekbaar wilt maken | Dit is het bron‑document voor OCR. | +| **Visual Studio 2022** (of een andere C#‑editor) | Maakt debuggen makkelijker, maar elke IDE werkt. | + +Je kunt de bibliotheek installeren met de volgende NuGet‑opdracht: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Als je werkt in een CI‑pipeline, voeg dan het licentiebestand toe aan de build‑artefacten en laad het tijdens runtime om hard‑coded paden te vermijden. + +--- + +## OCR uitvoeren op PDF – Aspose.OCR instellen + +Het eerste wat we nodig hebben is een verse `OcrEngine`‑instantie. Beschouw het als het brein dat je document gaat lezen. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Waarom elke keer een nieuwe instantie? De engine bevat configuratie (zoals taalinstellingen) die per document kan verschillen. Een nieuwe instantie per run garandeert een schone lei en voorkomt kruis‑talk tussen jobs. + +--- + +## Hoe een doorzoekbare PDF maken – Wachtwoorden configureren (optioneel) + +Als je PDF beveiligd is, moet je de engine het wachtwoord vertellen voordat hij de pagina’s kan lezen: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Dit stap overslaan bij een beveiligd bestand resulteert in een `PdfPasswordException`. Wrap het altijd in een try‑catch als je niet zeker bent van de beveiligingsstatus. + +--- + +## Gescande PDF omzetten naar doorzoekbare PDF – De bron laden + +Aspose.OCR werkt met de abstractie `OcrImage`, die PDF’s, TIFF’s, JPEG’s, enz. kan omhullen. Zo laad je een gescande PDF in het geheugen: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Achter de schermen parseert `FromFile` elke pagina naar raster‑afbeeldingen die de OCR‑engine kan verwerken. Als je een meer‑pagina PDF hebt, doorloopt de engine automatisch elke pagina. + +--- + +## Tekst herkennen uit PDF – De OCR uitvoeren + +Nu het hart van de tutorial: vraag de engine om de tekst te herkennen en een doorzoekbare PDF te produceren. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` vertelt de engine om een onzichtbare tekstlaag bovenop de originele gescande afbeeldingen te embedden. De resulterende PDF behoudt de visuele kwaliteit van de scan terwijl hij volledig doorzoekbaar wordt – precies wat je nodig hebt voor compliance‑audits. + +--- + +## Afbeelding omzetten naar doorzoekbare PDF – Het resultaat opslaan + +Tot slot schrijf je de binaire data naar schijf: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +De eigenschap `Binary` bevat de ruwe PDF‑bytes. Je kunt ze ook direct streamen naar een web‑response als je een API bouwt. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*Afbeeldings‑alt‑tekst: Diagram dat de OCR‑conversiestroom toont om een doorzoekbare PDF te maken, waarbij een gescande PDF wordt omgezet in een doorzoekbare PDF.* + +--- + +## Edge Cases & Praktische Tips + +### 1. Grote bestanden & geheugenbeheer +Als je PDF’s verwerkt die groter zijn dan 100 MB, overweeg dan `OcrEngineSettings.MemoryLimit` om het geheugenverbruik te beperken. Verwerk daarnaast pagina’s in batches om `OutOfMemoryException` te voorkomen. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Taalondersteuning +Standaard gaat Aspose.OCR uit van Engels. Om andere talen te herkennen, stel je de `Language`‑eigenschap in: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Multi‑threaded scenario’s +`OcrEngine` is **niet** thread‑safe. Als je parallel wilt verwerken, maak dan een aparte engine per thread. + +### 4. OCR‑nauwkeurigheid debuggen +Je kunt de platte tekst uit `ocrResult` halen voor debugging: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Als de output er rommelig uitziet, experimenteer dan met `PreprocessSettings` (bijv. deskew, despeckle) om de kwaliteit te verbeteren. + +### 5. Licentie‑valkuilen +Wanneer je de evaluatieversie draait, voegt Aspose een watermerk toe aan de output‑PDF. Registreer je licentie vroeg in de applicatie: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Volledig werkend voorbeeld – Van begin tot eind + +Hieronder vind je het complete, kant‑klaar programma dat alle bovenstaande tips bevat. Kopieer‑en‑plak het gerust in een nieuw console‑project. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Verwachte output:** Na uitvoering zie je een console‑regel die de bestandslocatie bevestigt. Open `output.pdf` in een PDF‑viewer; typ een woord waarvan je weet dat het in de originele scan voorkomt. Als het woord wordt gemarkeerd, heb je **OCR op PDF** succesvol uitgevoerd en een doorzoekbaar document gecreëerd. + +--- + +## Veelgestelde vragen + +**V: Kan ik dit gebruiken om een enkele afbeelding (PNG/JPEG) om te zetten naar een doorzoekbare PDF?** +A: Absoluut. Vervang `OcrImage.FromFile("input.pdf")` door het pad naar je afbeeldingsbestand. De engine rastert de afbeelding en embedde de OCR‑laag op dezelfde manier. + +**V: Wat als mijn PDF zowel gescande pagina’s als native tekst bevat?** +A: De engine legt de OCR‑tekst bovenop de bestaande inhoud, zodat native tekst selecteerbaar blijft terwijl gescande pagina’s doorzoekbaar worden. + +**V: Hoe nauwkeurig is de OCR?** +A: De nauwkeurigheid hangt af van de bronkwaliteit. Schone, hoge‑resolutie scans (>300 dpi) leveren >95 % nauwkeurigheid. Voor ruisende documenten schakel `PreprocessSettings` (deskew, despeckle) in vóór `Recognize`. + +--- + +## Volgende stappen – Je OCR‑toolkit uitbreiden + +Nu je **tekst kunt herkennen uit PDF** en **gescande PDF kunt omzetten naar doorzoekbare PDF**, overweeg dan de volgende vervolgtopics: + +- **Batchverwerking**: Loop over een map met PDF’s en genereer automatisch doorzoekbare versies. +- **Tekstextractie**: Gebruik `ocrResult.Text` om een zoekindex te voeden (bijv. Elasticsearch). +- **Aangepaste taalpakketten**: Download extra taaldata van Aspose om Aziatische scripts te ondersteunen. +- **PDF/A‑conformiteit**: Combineer Aspose.PDF met OCR‑output om archief‑klare PDF’s te maken. + +Elk van deze onderwerpen bouwt voort op de kernstappen die we hebben behandeld, zodat je goed gepositioneerd bent om je oplossing uit te breiden. + +--- + +## Afsluiting + +We hebben je net laten zien **hoe je OCR op PDF‑bestanden** uitvoert met Aspose.OCR, gescande PDF’s omzet in volledig doorzoekbare PDF’s, en zelfs hoe je gewone afbeeldingen omzet naar doorzoekbare PDF’s. De code + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids zijn gedemonstreerd. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap‑uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementaties in je eigen projecten te verkennen. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/dutch/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a3e36ca1b --- /dev/null +++ b/ocr/dutch/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Video‑ondertitel OCR‑tutorial die laat zien hoe je frames uit een video + kunt extraheren en tekst uit videobestanden zoals MP4 kunt lezen met Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: nl +og_description: Leer video‑ondertiteling OCR met Aspose.OCR. Haal frames uit een video, + lees tekst uit een video en extraheer tekst uit MP4 in enkele minuten. +og_title: Video-ondertiteling OCR in C# – Stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: Video-ondertiteling OCR in C# – Complete gids +url: /nl/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Video-ondertitel OCR in C# – Complete gids + +Heb je ooit **video subtitle ocr** nodig gehad maar wist je niet waar te beginnen? Je bent niet de enige. Of je nu college‑opnames digitaliseert, ondertitels uit trainingsvideo's haalt, of gewoon nieuwsgierig bent naar het lezen van tekst uit video, deze tutorial laat je precies zien hoe je het doet met C# en Aspose.OCR. + +In de komende paar minuten zullen we frames uit een video extraheren, OCR op die frames uitvoeren en uiteindelijk de ondertiteltekst frame‑voor‑frame weergeven. Aan het einde kun je **tekst uit video** bestanden lezen — inclusief MP4 — zonder op zoek te gaan naar tools van derden. + +## Wat je gaat bouwen + +We zullen een kleine console‑app maken die: + +1. Decodeert een MP4 (of elk ondersteund formaat) naar afzonderlijke `Bitmap`‑frames. +2. Beperkt het OCR‑gebied tot de ondertitelband zodat de engine niet wordt afgeleid door de volledige afbeelding. +3. Verwerkt elk frame met Aspose’s `VideoOcrProcessor`. +4. Print de herkende ondertiteltekst naar de console. + +Geen poespas, alleen een werkend end‑to‑end voorbeeld dat je in een echt project kunt gebruiken. + +## Vereisten + +- **.NET 6.0** of later (de code werkt ook op .NET Framework 4.7+). +- **Aspose.OCR for .NET** – installeer via NuGet: `Install-Package Aspose.OCR`. +- Een videobestand (MP4 werkt uitstekend). +- Een manier om videoframes te decoderen – de demo gebruikt een placeholder‑methode, maar je kunt FFmpeg, OpenCV of een andere bibliotheek die `Bitmap`‑objecten retourneert, gebruiken. + +> Pro tip: Als je op Windows werkt, werkt het `System.Drawing.Common`‑pakket prima voor `Bitmap`. Op Linux/macOS heb je de native `libgdiplus`‑dependency nodig. + +## Stap 1 – Frames uit video extraheren + +De eerste hindernis is het omzetten van een bewegend beeld naar stilstaande afbeeldingen. De methode `GetVideoFrames` hieronder is opzettelijk leeg gelaten; vervang deze door je favoriete decoder. Hier is een snelle schets met FFmpeg‑Core (alleen om de vorm van de data te illustreren): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Waarom dit belangrijk is:** Het extraheren van frames geeft de OCR‑engine een statisch beeld om mee te werken, wat de nauwkeurigheid aanzienlijk verbetert vergeleken met direct uit een videostream proberen te lezen. + +## Stap 2 – VideoOcrProcessor instellen + +Nu we een reeks `Bitmap`‑objecten hebben, kunnen we ze aan Aspose.OCR geven. De `VideoOcrProcessor` stelt ons in staat een **Region of Interest (ROI)** te definiëren – perfect voor ondertitels die meestal bovenaan of onderaan het frame staan. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Waarom de ROI beperken?** Door de rest van de afbeelding te negeren verminderen we ruis, verkorten we de verwerkingstijd en voorkomen we valse positieven van achtergrondgrafieken. + +## Stap 3 – OCR uitvoeren op de frame‑reeks + +Met de processor klaar, is het voeden van de frames een één‑regel‑code. De `Process`‑methode retourneert een enumerable van `OcrResult`‑objecten, elk met de herkende tekst voor het bijbehorende frame. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Wat gebeurt er onder de motorkap?** Aspose.OCR normaliseert intern elke bitmap, voert een op neurale netwerken gebaseerde herkenner uit, en verwerkt vervolgens de output naverwerking om interpunctie en regeleinden te verbeteren. + +## Stap 4 – De geëxtraheerde tekst weergeven + +Tot slot itereren we over de resultaten en printen we elke ondertitelregel. Je kunt ze ook naar een SRT‑bestand schrijven, naar een database, of ze doorvoeren naar een vertaaldienst. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Volledig werkend voorbeeld + +Alles samenvoegen levert een zelfstandige console‑applicatie op: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Verwachte output (voorbeeld)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Als de OCR moeite heeft met een bepaald frame, zie je een lege string – dat is een signaal om de ROI aan te passen of de frame‑extractiesnelheid te verhogen. + +## Veelvoorkomende valkuilen & hoe ze op te lossen + +| Probleem | Waarom het gebeurt | Oplossing | +|-------|----------------|-----| +| **Garbage characters** | Frames met lage resolutie of zware compressie | Extraheer frames met een hogere bitrate, of schaal de bitmap op vóór OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI dekt de ondertitelband niet | Controleer de rechthoekcoördinaten (gebruik een screenshot‑tool om te meten). | +| **Performance bottleneck** | Elke frame verwerken op 30 fps is overbodig | Down‑sample naar 1‑2 fps voor de meeste ondertitel‑streams; je kunt nog steeds elke ondertitelwijziging vastleggen. | +| **FFmpeg not found** | `ffmpeg.exe` staat niet in de `PATH` | Geef het volledige pad op in `ProcessStartInfo.FileName` of installeer FFmpeg globaal. | + +## De oplossing uitbreiden + +- **Exporteren naar SRT** – concateneer de tijdstempels met de OCR‑tekst en schrijf een SubRip‑bestand. +- **Meertalige ondersteuning** – stel `ocrProcessor.Language = OcrLanguage.Spanish` in (of een andere ondersteunde taal). +- **Realtime verwerking** – pipe frames direct van een live‑stream in plaats van van schijf te lezen. + +Al deze variaties draaien nog steeds om de kernideeën van **frames uit video extraheren**, **tekst uit video lezen**, en **tekst uit mp4 extraheren**. + +## Conclusie + +We hebben zojuist een volledige **video subtitle ocr**‑workflow in C# doorlopen. Door frames uit video te extraheren, de OCR te richten op de ondertitelband, en over de resultaten te itereren, kun je betrouwbaar **tekst uit video** bestanden zoals MP4 lezen. De code is klaar om te copy‑pasten, en het modulaire ontwerp laat je elke gewenste frame‑decoder gebruiken. + +Volgende stappen? Probeer de resultaten naar een SRT‑bestand te exporteren, experimenteer met verschillende ROI‑groottes, of voer de ondertitels in een vertaal‑API voor meertalige captions. De mogelijkheden zijn eindeloos zodra je de basis van tekst uit video extraheren onder de knie hebt. + +Veel plezier met coderen, en moge je ondertitels altijd kristalhelder zijn! + +## Wat moet je hierna leren? + +De volgende tutorials behandelen nauw verwante onderwerpen die voortbouwen op de technieken die in deze gids worden getoond. Elke bron bevat volledige werkende code‑voorbeelden met stap‑voor‑stap uitleg om je te helpen extra API‑functies onder de knie te krijgen en alternatieve implementatie‑benaderingen in je eigen projecten te verkennen. + +- [Afbeeldingstekst extraheren C# met taalkeuze via Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Tekst extraheren uit afbeelding met Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Tekst extraheren uit afbeelding – OCR‑optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/ocr-configuration/_index.md b/ocr/english/net/ocr-configuration/_index.md index 32e2ef7e1..1b4eabf6b 100644 --- a/ocr/english/net/ocr-configuration/_index.md +++ b/ocr/english/net/ocr-configuration/_index.md @@ -60,6 +60,8 @@ Unlock the power of OCR image recognition in .NET with Aspose.OCR. Extract text Unlock powerful OCR capabilities with Aspose.OCR for .NET. Extract text from images seamlessly. ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) Unlock the potential of Aspose.OCR for .NET. Effortlessly perform OCR image recognition with lists. Boost productivity and data extraction in your applications. +### [Get Aspose OCR Version in C# – Complete Guide](./get-aspose-ocr-version-in-c-complete-guide/) +Learn how to retrieve the Aspose OCR library version in C# with a complete guide. ### Common Use Cases - **Extract text images** from scanned invoices for automated accounting. @@ -100,4 +102,4 @@ A: Yes, the `OcrResult` object provides confidence values you can inspect progra {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/english/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..507fdb473 --- /dev/null +++ b/ocr/english/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-03 +description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: en +og_description: Get Aspose OCR version in C# quickly. This tutorial shows exactly + how to retrieve the Aspose OCR library version using OcrEngine GetVersion. +og_title: Get Aspose OCR Version in C# – Complete Guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Get Aspose OCR Version in C# – Complete Guide +url: /net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Get Aspose OCR Version in C# – Complete Guide + +Ever wondered how to **get Aspose OCR version** from within your .NET project? Maybe you’re troubleshooting a mismatch, or you just want to log the exact library build that’s running in production. Whatever the reason, you’ve landed in the right spot. + +In this tutorial we’ll walk through a tiny, self‑contained C# program that calls `OcrEngine.GetVersion()` and prints the result. By the end you’ll know not only *how* to retrieve the version, but also *why* checking the version can save you headaches when upgrading the **Aspose OCR library**. + +## What You’ll Learn + +- Add the Aspose.OCR NuGet package to a C# project +- Use the `OcrEngine.GetVersion()` method (the **ocrengine getversion** entry point) +- Handle possible exceptions and verify the output +- Extend the snippet for real‑world scenarios like logging or conditional feature toggles + +No prior experience with OCR is required—just a basic grasp of C# and Visual Studio (or your favourite IDE). Let’s get started. + +--- + +## Step 1: Set Up the Project and Pull in the Aspose OCR Library + +Before you can call any OCR‑related APIs, you need the **Aspose OCR library** referenced in your project. + +1. Open a terminal or the Package Manager Console in Visual Studio. +2. Run the following command to install the latest stable version: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** If you’re targeting .NET Framework instead of .NET Core, use the NuGet Package Manager UI and pick the version that matches your runtime. The package includes the `OcrEngine` class we’ll use later. + +### Why this matters + +When you install the package, the assembly version on disk may differ from the version reported by the library at runtime. Querying the version via code ensures you’re reading the exact build that the CLR loaded, which is crucial for debugging and for compliance audits. + +--- + +## Step 2: Write the Minimal Code to **Get Aspose OCR Version** + +Create a new console app (`dotnet new console -n OcrVersionDemo`) and replace the default `Program.cs` with the following: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Explanation of each part** + +- `using Aspose.OCR;` brings the OCR namespace into scope, allowing us to call `OcrEngine`. +- `OcrEngine.GetVersion()` is the **ocrengine getversion** static method that returns a string like `"24.5.7"`. +- Wrapping the call in a `try/catch` block protects you from runtime surprises—perhaps the native binaries aren’t found on the target machine. +- The interpolated string `$"Aspose OCR version: {version}"` prints a clear, human‑readable line. + +### Expected output + +When you run `dotnet run` inside the project folder, you should see something similar to: + +``` +Aspose OCR version: 24.5.7 +``` + +If the library cannot be loaded, the error branch will output a concise message, helping you pinpoint the issue fast. + +--- + +## Step 3: Verify the Version Matches Your NuGet Package + +It’s easy to assume the NuGet version you installed is the one being used at runtime, but environment quirks can intervene. To double‑check: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Running this extra snippet will print something like: + +``` +Assembly file version: 24.5.7.0 +``` + +If the two values differ, you might be loading an older DLL from the Global Assembly Cache (GAC) or from a previous build folder. In that case, clean your solution (`dotnet clean`) and rebuild. + +--- + +## Step 4: Put the Version Check Into Production Logging + +Most real‑world applications don’t just print to the console; they write to a log file or telemetry system. Here’s a quick example using `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Now the version appears in your structured logs, making it easy to filter by `{Version}` later. This pattern is especially handy when you have multiple micro‑services each pulling in a potentially different OCR DLL. + +--- + +## Common Questions & Edge Cases + +### What if `GetVersion()` returns an empty string? + +That usually signals a corrupted installation or a missing native dependency. Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or the appropriate platform‑specific binary) sits alongside your executable. + +### Does the method work on .NET Core 2.0? + +Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core version that implements that standard can call `OcrEngine.GetVersion()`. Just make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, etc.) if you’re publishing a self‑contained app. + +### Can I retrieve the version without a license file? + +Absolutely. `GetVersion()` does **not** require a license; it simply reports the library build number. However, if you attempt to perform OCR without a valid license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet is valuable—it isolates the version check from the OCR execution flow. + +--- + +## Full Working Example (Copy‑Paste Ready) + +Below is the entire program, ready to drop into a new console project. It includes the optional logging block, so you can see both console output and structured logs in action. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Run it with `dotnet run` and you’ll see two lines confirming the version, plus a debug line if you enable `LogLevel.Debug`. + +--- + +## Conclusion + +We’ve covered everything you need to **get Aspose OCR version** in a C# environment—from installing the **Aspose OCR library**, calling the **ocrengine getversion** method, handling errors, to embedding the result in production‑grade logging. Armed with this knowledge, you can now reliably verify the exact OCR build your application is using, avoid version‑related bugs, and satisfy compliance requirements without breaking a sweat. + +Next steps? Try pairing this version check with an actual OCR call (`OcrEngine` → `RecognizeImage`) and log both the version and the recognition result. You might also explore the **retrieve aspose version** pattern for other Aspose products (PDF, Slides, Cells) to keep your entire suite in sync. + +Happy coding, and may your OCR pipelines stay sharp! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/english/net/ocr-optimization/_index.md index ff28e4eeb..aed73a4a0 100644 --- a/ocr/english/net/ocr-optimization/_index.md +++ b/ocr/english/net/ocr-optimization/_index.md @@ -69,9 +69,11 @@ Unlock the potential of Aspose.OCR for .NET with our comprehensive guide. Learn ### [Preprocessing Filters for Image in OCR Image Recognition](./preprocessing-filters-for-image/) Explore Aspose.OCR for .NET. Boost OCR accuracy with preprocessing filters. Download now for seamless integration. ### [Result Correction with Spell Checking in OCR Image Recognition](./result-correction-with-spell-checking/) -Enhance OCR accuracy with Aspose.OCR for .NET. Correct spellings, customize dictionaries, and achieve error-free text recognition effortlessly. +Enhance OCR accuracy with Aspose.OCR for .NET. Correct spellings, customize dictionaries, and achieve error‑free text recognition effortlessly. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) Unlock the potential of Aspose.OCR for .NET. Effortlessly save multipage OCR results as documents with this comprehensive step-by-step guide. +### [Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Learn how to enable GPU acceleration, set memory limits, and process TIF images using Aspose.OCR in C#. ## Frequently Asked Questions diff --git a/ocr/english/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/english/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..80a9465e5 --- /dev/null +++ b/ocr/english/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: en +og_description: 'Learn a complete Aspose OCR C# example: enable GPU, set GPU memory + limit, load an image for OCR and recognize text from TIF files. Full code included.' +og_title: Aspose OCR C# Example – GPU Acceleration, Memory Limit & TIF Processing +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images +url: /net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + +Ever wondered how to squeeze the most performance out of **Aspose OCR C# example** code when dealing with massive TIFF scans? You’re not alone. In many real‑world projects—think digitizing archives or extracting data from high‑resolution receipts—the bottleneck isn’t the OCR algorithm itself, it’s the hardware utilization. + +Here’s the thing: Aspose OCR supports GPU acceleration, but you have to tell it exactly how much memory it may chew up, load the right image type, and finally pull the recognized text out of a .tif file. This tutorial walks you through every step, from installing the SDK to tweaking the GPU settings, so you can run OCR at blazing speed without blowing your GPU’s RAM. + +We’ll also sprinkle in a few “what if” scenarios—like handling multi‑page TIFFs or falling back to CPU when a GPU isn’t present—so you end up with a robust solution, not just a one‑off snippet. + +## What You’ll Need + +Before we dive in, make sure you have the following on your machine: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6 SDK** (or later) | Aspose OCR targets .NET Standard 2.0+, so any recent .NET version works. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | The core library that provides `OcrEngine`, `GpuSettings`, etc. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Required for GPU acceleration; the SDK will check for a compatible driver at runtime. | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | Without enough memory, the engine may fall back to CPU silently. | +| A **high‑resolution TIFF** image you want to process | Aspose OCR can read virtually any raster format, but TIF is common for scans. | +| Visual Studio 2022 (or any editor you like) | For building and debugging the C# project. | + +If any of these are missing, the code will still compile, but you won’t see the performance gains we’re after. + +## Step 1: Create the Aspose OCR C# Example Engine + +The first thing in every **Aspose OCR C# example** is to instantiate the OCR engine. Think of `OcrEngine` as the director of a movie—it coordinates everything from image loading to text extraction. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** If you plan to process many images in a row, keep a single `OcrEngine` alive. Re‑creating it per image adds overhead that can dwarf the OCR time. + +## Step 2: Set GPU Memory Limit (and Enable Acceleration) + +Now comes the part that often trips people up: **set GPU memory limit**. By default Aspose OCR will try to use as much VRAM as it can, which on a shared workstation may starve other applications. The `GpuSettings` object lets you cap the allocation. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Why set a memory limit? + +- **Stability:** Prevents out‑of‑memory crashes when processing gigantic images. +- **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) to run side‑by‑side. +- **Predictability:** Makes performance testing repeatable because the GPU won’t start swapping. + +If you omit `MemoryLimitMb`, Aspose will allocate whatever it deems necessary, which can be fine on a dedicated inference server but risky on a developer laptop. + +## Step 3: Load Image for OCR + +Loading the right file format is the next crucial piece. The method `OcrImage.FromFile` automatically detects the image type, but you should still verify that the file exists and that it’s a supported TIFF variant (e.g., LZW‑compressed or CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Handling multi‑page TIFFs + +If your TIFF contains several pages, Aspose OCR will only read the first one by default. To process all pages, you can loop over `image.Pages` (available in newer SDK versions) and feed each page to the engine separately. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +The snippet above demonstrates a **load image for OCR** pattern that works for both single‑ and multi‑page files. + +## Step 4: Recognize Text from TIF (or any raster) + +Now that the image lives in memory, we ask Aspose to do its magic. The `Recognize` method returns an `OcrResult` which contains the plain text, confidence scores, and even bounding‑box information if you need it. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Why this works well with TIF + +- **Lossless compression:** TIFF often stores raw pixel data, giving the OCR engine the highest fidelity. +- **Multiple color spaces:** Aspose can handle grayscale, RGB, or even CMYK TIFFs without extra conversion code. + +If you need to tweak language packs (e.g., French or Japanese), set `ocrEngine.Settings.Language = "fr"` before calling `Recognize`. + +## Step 5: Display the Recognized Text + +Finally, we output the text to the console. In a real application you might write to a database, a JSON file, or feed the string into a downstream NLP pipeline. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Expected output + +Running the program on a clear, 300 dpi scan of a printed page typically yields something like: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +If the image is blurry or the GPU memory limit is too low, you might see garbled characters or a truncated result. Lowering `MemoryLimitMb` below the image’s footprint (often ~1 GB for a 6000×8000 pixel TIFF) can cause the engine to fall back to CPU automatically. + +## Full Working Example + +Below is the complete, ready‑to‑run program. Copy‑paste it into a new Console App project, replace `YOUR_DIRECTORY/large_photo.tif` with the path to your own TIFF, and hit **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Quick checklist + +- ✅ **Aspose OCR C# example** compiled without errors. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** set to 2048 MB. +- ✅ **Image loaded** from a TIF file. +- ✅ **Text recognized** and printed. + +## Common Pitfalls & How to Avoid Them + +| Symptom | Likely cause | Fix | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA runtime not installed or version mismatch. | Install CUDA 11.x (or 12.x) matching your driver. | +| OCR returns empty string | Image is too dark or DPI < 150. | Pre‑process with `image.AdjustContrast()` or resample to 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` too low for the image. | Raise the limit or split the image into tiles via `image.Crop`. | +| `Unsupported image format` error | TIFF uses an exotic compression (e.g., JPEG‑2000). | Convert the TIFF to a supported format with ImageMagick before OCR. | + +## Extending the Demo + +Now that you have a solid **aspose ocr c# example**, you might want to explore: + +- **Batch processing:** Loop over a folder of TIFs, write each result to a `.txt` file. +- **Language packs:** `ocrEngine.Settings.Language = "es"` for Spanish, or load custom dictionaries. +- **Bounding boxes:** Use `ocrResult.Regions` to get coordinates for each word—handy for redaction tools. +- **CPU fallback:** Wrap the GPU block in a try/catch; on failure, set `ocrEngine.Settings.Gpu.Enable = false` and retry. + +These extensions keep the core pattern intact while adding value for specific use‑ + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/english/net/skew-angle-calculation/_index.md index 50232bfea..c1539399e 100644 --- a/ocr/english/net/skew-angle-calculation/_index.md +++ b/ocr/english/net/skew-angle-calculation/_index.md @@ -40,9 +40,12 @@ Explore Aspose.OCR for .NET, a powerful OCR solution for accurate text recogniti Unleash the power of Aspose.OCR for .NET, a robust solution for image recognition. Learn how to calculate skew angles effortlessly. ### [Calculate Skew Angle from URI in OCR Image Recognition](./calculate-skew-angle-from-uri/) Explore Aspose.OCR for .NET to effortlessly calculate skew angles in OCR image recognition. Enhance your projects with precision and efficiency. +### [OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Explore Aspose.OCR for .NET to automatically fix skew and rotation in OCR of rotated documents. Improve accuracy and efficiency. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/english/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..13f053e95 --- /dev/null +++ b/ocr/english/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-03 +description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: en +og_description: OCR rotated document tutorial teaches you how to automatically correct + skew and detect rotation using Aspose OCR in C#. Follow the complete guide. +og_title: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# +url: /net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Rotated Document Tutorial – Full Guide for C# Developers + +Ever stumbled upon an **ocr rotated document tutorial** when a scanned form came in sideways or slanted? You’re not alone. Those wonky images can ruin a clean text extraction, but the good news is that Aspose OCR can straighten things out for you automatically. + +In this step‑by‑step guide we’ll spin up an `OcrEngine`, turn on **automatic skew correction** and **auto detect rotation**, run the engine against a rotated image, and print the clean text. By the end you’ll know exactly why each setting matters, how to tweak it for edge cases, and you’ll have a ready‑to‑run C# program. + +## What You’ll Learn + +* How to install and reference **Aspose OCR** in a .NET project. +* Why enabling `AutoCorrectSkew` and `AutoDetectRotation` is the key to a reliable **ocr rotated document tutorial**. +* How to load any image (JPG, PNG, TIFF) and let the engine do the heavy lifting. +* Tips for handling multi‑page PDFs, low‑resolution scans, and custom language packs. + +> **Prerequisites:** Visual Studio 2022 (or any C# IDE), .NET 6+ runtime, and a valid Aspose OCR license (or the free trial). No prior OCR experience required. + +--- + +## Step 1 – Install Aspose OCR and Set Up the Project + +First things first. Grab the NuGet package: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** If you’re using a trial license, place the `Aspose.OCR.lic` file in the same folder as your executable, or register it programmatically with `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Create a new console app: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Now you have a clean slate for our **ocr rotated document tutorial**. + +## Step 2 – Initialize the OCR Engine + +The engine is the heart of the process. Think of it as a Swiss‑army knife for text extraction; you just need to tell it what tricks to enable. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Why these settings?** +* `AutoCorrectSkew` analyses the baseline of characters and rotates the image just enough to make lines horizontal. +* `AutoDetectRotation` looks at the overall orientation (0°, 90°, 180°, 270°) and flips the page if it’s upside‑down. Without them, the engine would read “pɹᴉʍ” instead of “word”. + +## Step 3 – Load the Image You Want to Process + +Aspose OCR works with any common raster format. Replace the placeholder path with the real location of your rotated form. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** If you receive a multi‑page TIFF, use `OcrImage.FromMultiPageTiff(filePath)` and loop through `image.Pages`. + +## Step 4 – Run the Recognition + +Now the engine does the magic. It will first straighten the image (thanks to our skew/rotation flags) and then pull out the characters. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +If you need language support beyond English, set it before calling `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Step 5 – Output the Recognized Text + +Finally, dump the clean text to the console—or pipe it to a file, a database, whatever fits your workflow. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Expected output** (assuming the sample image contains “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Notice how the text appears correctly even though the source image was rotated 90° and slightly skewed. + +--- + +## Handling Common Pitfalls + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Blank output** | Skew correction disabled or image too dark. | Enable `AutoCorrectSkew` (already on) and increase image contrast via `image.AdjustContrast(1.2)`. | +| **Garbage characters** | Wrong language setting. | Set `ocrEngine.Settings.Language` to match the document language. | +| **Performance lag on large PDFs** | Engine processes each page sequentially. | Use `Parallel.ForEach` on `image.Pages` to leverage multi‑core CPUs. | +| **License exception** | Trial expired. | Acquire a permanent license or stay within the trial limits (5 pages per run). | + +--- + +## Pro Tips for a Robust OCR Rotated Document Tutorial + +* **Batch processing:** Wrap the whole flow in a method that accepts a folder path, loops over every image, and writes each result to a `.txt` file. +* **Pre‑processing:** Sometimes a noisy scan benefits from `image.Denoise()` before recognition. +* **Post‑processing:** Use regular expressions to clean up common OCR misreads, e.g., replace “0” with “O” only when surrounded by letters. +* **Logging:** Aspose OCR provides `ocrEngine.Logger` – hook it up to a file logger to capture warnings about low confidence scores. + +--- + +## Complete, Ready‑to‑Run Code + +Save the following as `Program.cs` inside your console project. It includes all the steps, comments, and a small helper for batch processing. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Run it: + +```bash +dotnet run +``` + +You should see the cleaned text printed to the console, proving that our **ocr rotated document tutorial** works end‑to‑end. + +--- + +## Conclusion + +You now have a complete **ocr rotated document tutorial** that automatically corrects skew, detects rotation, and extracts clean text using Aspose OCR in C#. The key takeaway? Enabling `AutoCorrectSkew` **and** `AutoDetectRotation` turns a hopelessly tilted scan into perfectly readable output with just a few lines of code. + +From here, you can expand to batch jobs, integrate language packs, or feed the results into downstream analytics pipelines. Want to explore **automatic skew correction** further? Check out Aspose’s image preprocessing API, or experiment with custom thresholds for noisy scans. + +Got questions about handling PDFs, multi‑page TIFFs, or integrating with Azure Functions? Drop a comment, and happy coding! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/english/net/text-recognition/_index.md index b3bb5f052..3a9aa5856 100644 --- a/ocr/english/net/text-recognition/_index.md +++ b/ocr/english/net/text-recognition/_index.md @@ -55,9 +55,20 @@ Enhance your .NET applications with Aspose.OCR for efficient image text recognit Unlock the potential of OCR in .NET with Aspose.OCR. Extract text from PDFs effortlessly. Download now for a seamless integration experience. ### [Recognize Table in OCR Image Recognition](./recognize-table/) Unlock the potential of Aspose.OCR for .NET with our comprehensive guide on recognizing tables in OCR image recognition. +### [Perform OCR on PDF with Aspose.OCR – Complete C# Guide](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Learn how to perform OCR on PDF files using Aspose.OCR with a comprehensive C# guide. +### [Perform OCR on Image with Aspose OCR – Hindi Guide](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Perform OCR on images using Aspose OCR with a Hindi guide. Follow step-by-step instructions to extract text from images efficiently. +### [How to Use Aspose: Convert Image to HTML with OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Convert images to HTML while extracting text using Aspose.OCR. Follow our step-by-step guide to generate searchable HTML content. +### [Perform OCR on Image and Detect Misspelled Words in C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Learn how to use Aspose.OCR in C# to extract text from images and identify misspelled words with a simple spell‑check implementation. +### [Video Subtitle OCR in C# – Complete Guide](./video-subtitle-ocr-in-c-complete-guide/) +Extract video subtitles using Aspose.OCR in C# with this comprehensive, step-by-step guide. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/english/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..776c9b46b --- /dev/null +++ b/ocr/english/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: en +og_description: How to use Aspose to convert image to HTML, extract text from image, + and generate HTML from image with OCR in C#. Follow this complete guide. +og_title: 'How to Use Aspose: Convert Image to HTML with OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'How to Use Aspose: Convert Image to HTML with OCR' +url: /net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Use Aspose: Convert Image to HTML with OCR + +Ever wondered **how to use Aspose** to turn a scanned picture into tidy HTML? Maybe you have a magazine page, a receipt, or a handwritten note and you need the text and layout preserved for web publishing. The good news is you don’t need to write a custom parser or wrestle with low‑level image processing—Aspose.OCR does the heavy lifting for you. + +In this tutorial we’ll walk through a **complete, runnable example** that shows you how to **convert image to HTML**, **extract text from image**, and **generate HTML from image** using the Aspose OCR library in C#. By the end you’ll have a small console app that produces an HTML file with the original page layout intact, ready to be dropped into any website. + +## Prerequisites + +Before we dive in, make sure you have the following on your machine: + +- **.NET 6.0 SDK** or later (the code works with .NET Core and .NET Framework alike). +- **Visual Studio 2022** (or any editor you like). +- **Aspose.OCR for .NET** – install via NuGet: `dotnet add package Aspose.OCR`. +- An image file (JPEG/PNG) you want to transform, e.g., `magazine_page.jpg`. + +No extra configuration files are needed; the library ships with everything required for OCR and HTML layout generation. + +## Step 1: Set Up the Project and Add Aspose.OCR + +First, create a new console project and pull in the Aspose OCR package. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** If you’re using Visual Studio, simply right‑click the project → *Manage NuGet Packages* → search for **Aspose.OCR** and install it. This step ensures you can **ocr image to html** without any missing references. + +## Step 2: Initialize the OCR Engine + +The core of the process is the `OcrEngine` class. Think of it as the brain that reads the picture and decides how to output the result. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Here we instantiate `OcrEngine`. You don’t need to pass any credentials for the free version; the library will use its built‑in recognition models. + +## Step 3: Load the Source Image + +Next, point the engine at the file you want to process. Aspose provides a convenient `OcrImage.FromFile` method that handles most image formats. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Replace `YOUR_DIRECTORY` with the absolute or relative path where your image lives. If the image is in the same folder as the executable, you can just use `"magazine_page.jpg"`. + +## Step 4: Recognize and Request HTML With Layout + +This is the heart of the tutorial. By passing `OutputFormat.HtmlWithLayout` we tell Aspose to **generate HTML from image** while preserving the original positioning of text blocks, images, and tables. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +The `recognitionResult.Text` property now contains a full HTML document. If you only needed plain text, you could use `OutputFormat.Text`, but we’re focusing on **convert image to html** with layout fidelity. + +## Step 5: Save the HTML File + +Finally, write the HTML string to disk. This gives you a ready‑to‑use file you can open in any browser. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Running the program will produce `magazine.html`. Open it, and you’ll see the original page’s text positioned exactly as it appeared in the source image—perfect for archiving or web publishing. + +## Full Working Example + +Below is the **complete, copy‑paste‑ready** program. No parts are omitted, so you can compile and run it immediately after setting the correct paths. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Expected Output + +When you open `magazine.html` in a browser, you should see something akin to this (simplified for illustration): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +The exact `style` attributes will differ based on the original image, but the structure guarantees that **extract text from image** and **generate html from image** happen in a single, seamless step. + +## Common Questions & Edge Cases + +### What if the image is low‑resolution? + +Aspose.OCR works best with images that have at least **300 DPI**. If your file is blurry, try preprocessing it with an image‑enhancement library (e.g., ImageSharp) before feeding it to the OCR engine. Low quality can affect both the **extract text from image** accuracy and the fidelity of the generated HTML layout. + +### Can I control the language of the OCR? + +Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +This improves recognition when dealing with non‑English characters. + +### How do I get plain text instead of HTML? + +If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just the extracted characters. + +### Is there a way to embed images into the generated HTML? + +Aspose.OCR can embed the original image as a base‑64 data URI when you use `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single HTML file without external assets. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### What about handling large batches? + +For batch processing, wrap the logic in a `foreach` loop over a list of file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds up the **convert image to html** pipeline. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tips for Production‑Ready Code + +- **Dispose resources**: Both `OcrEngine` and `OcrImage` implement `IDisposable`. Wrap them in `using` statements to free native memory promptly. +- **Error handling**: Catch `IOException` for file‑related issues and `OcrException` for recognition problems. +- **Performance**: If you process many images, consider enabling **parallelism** (`Parallel.ForEach`) but be mindful of CPU usage—OCR is CPU‑intensive. +- **Logging**: Integrate a logger (e.g., Serilog) to capture OCR confidence scores (`recognitionResult.Confidence`) for quality monitoring. + +## Conclusion + +We’ve just covered **how to use Aspose** to **convert image to HTML**, **extract text from image**, and **generate HTML from image** in a few straightforward steps. The complete code sample shows you how to **ocr image to html** while preserving layout, making it a solid foundation for any document‑digitization project. + +From here you might: + +- Experiment with different `OutputFormat` options to suit your needs. +- Combine the HTML output with a CSS framework for responsive styling. +- Feed the extracted text into a search index or a machine‑learning pipeline. + +Give it a try, tweak the settings, and see how effortlessly Aspose turns pictures into web‑ready content. If you hit any snags, drop a comment—happy coding! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/english/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..3ab0a85a8 --- /dev/null +++ b/ocr/english/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-03 +description: Perform OCR on image and extract text from image using Aspose.OCR. Learn + how to detect misspelled words and get spelling suggestions in a single C# demo. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: en +og_description: Perform OCR on image to extract text from image, then detect misspelled + words and get spelling suggestions with Aspose.OCR in C#. +og_title: Perform OCR on Image and Detect Misspelled Words in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Perform OCR on Image and Detect Misspelled Words in C# +url: /net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Perform OCR on Image and Detect Misspelled Words in C# + +Ever wondered how to **perform OCR on image** files without pulling your hair out? You're not the only one. Whether you're digitizing old letters, scanning receipts, or building a smart document workflow, extracting clean text from pictures is the first hurdle. The good news? With Aspose.OCR you can spin up a solution in minutes, and the bonus is you can also **detect misspelled words** and **get spelling suggestions** in the same run. + +In this tutorial we'll walk through a complete, ready‑to‑run C# console app that **extracts text from image**, runs an English spell‑checker, and prints each error with handy correction ideas. By the end you’ll know exactly **how to extract text**, how to hook the spell‑check API, and what the expected console output looks like. + +## What You’ll Build + +- Load a bitmap (or PNG) that contains typographical errors. +- Run Aspose.OCR to **perform OCR on image** and obtain raw string data. +- Initialise the built‑in English spell‑checker. +- **Detect misspelled words** and **get spelling suggestions** for each. +- Print a tidy report to the console. + +No external services, no fiddly HTTP calls—just a single NuGet package and a handful of lines of code. + +## Prerequisites + +- .NET 6.0 SDK or later (the code also works on .NET Framework 4.7+). +- Visual Studio 2022 (or any editor you like). +- Aspose.OCR for .NET NuGet package (`Aspose.OCR`). +- An image file (`letter_with_typos.png`) placed somewhere you can reference it from the project. + +If you’ve never used Aspose before, don’t worry—installing the package is as easy as running: + +```bash +dotnet add package Aspose.OCR +``` + +Now let’s dive into the implementation. + +## Step 1: Set Up the Project and Install Aspose.OCR + +Create a new console project and pull in the OCR library: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +After the restore finishes, open `Program.cs`. We’ll replace the default content with the full demo code later, but first let’s talk about why each namespace matters. + +- `Aspose.OCR` – Core OCR engine and image handling. +- `Aspose.OCR.SpellCheck` – Spell‑checking utilities that ship with the library. +- `System` – Standard .NET base classes (e.g., `Console`). + +## Step 2: Load the Image and Perform OCR on Image + +The first real work is feeding the image to the OCR engine. Aspose.OCR reads many formats (PNG, JPEG, TIFF). Here’s the snippet that does the heavy lifting: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Why this matters:** `OcrImage.FromFile` abstracts away pixel‑level details, while `OcrEngine.Recognize` runs the trained neural model that translates visual glyphs into Unicode characters. The `ocrResult.Text` property now holds the raw string—exactly what you need to **extract text from image**. + +> **Pro tip:** If your image contains multiple languages, you can set `ocrEngine.Language = OcrLanguage.Multilingual;` before calling `Recognize`. + +## Step 3: Initialise the English Spell‑Checker + +Aspose.OCR ships with a built‑in spell‑checking engine that understands English out of the box. Initialising it is a one‑liner: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Why this step is crucial:** The OCR output may include mis‑recognised characters (e.g., “l” vs “1”) or genuine typos from the source document. The spell‑checker will scan the string, locate suspicious tokens, and suggest alternatives. + +## Step 4: Detect Misspelled Words and Get Spelling Suggestions + +Now we feed the OCR text into the checker: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` is a collection where each entry contains the erroneous word and an array of possible corrections. + +## Step 5: Output the Results + +Finally, we iterate over the collection and print a human‑readable report: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Expected Console Output + +Assuming `letter_with_typos.png` contains the sentence: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Running the demo will produce something like: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Notice how each typo is paired with a handful of plausible fixes—exactly what you need when building a user‑friendly correction UI. + +## Full Working Example + +Below is the **complete, copy‑paste‑ready** program. Replace `YOUR_DIRECTORY` with the actual path to your image file. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Edge Cases to Consider** +> - **Empty Image:** If the OCR engine returns an empty string, `spellChecker.Check` will simply return an empty collection—no crash. +> - **Non‑English Text:** Swap `OcrLanguage.English` with `OcrLanguage.French` (or any supported language) to **detect misspelled words** in other locales. +> - **Large Documents:** For multi‑page PDFs, you’d loop over each page, perform OCR, then aggregate the results before spell‑checking. + +## Visual Overview (Image Alt Text) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*The diagram above illustrates the end‑to‑end pipeline: image → OCR engine → raw text → spell‑checker → suggestions.* + +## Common Questions & Pro Tips + +| Question | Answer | +|----------|--------| +| **Do I need an internet connection?** | No. Aspose.OCR runs entirely locally; perfect for offline or secure environments. | +| **How accurate is the spell‑checker?** | It uses a dictionary of ~150k English words and fuzzy matching, so most common typos are caught. | +| **Can I customize the dictionary?** | Yes. `SpellChecker.AddUserDictionary("custom.txt")` lets you load domain‑specific terms (e.g., product names). | +| **What if the image is skewed?** | The OCR engine auto‑detects orientation, but you can manually call `ocrEngine.ImagePreprocessing.Rotate(angle)` for stubborn cases. | +| **Is there a way to highlight suggestions in UI?** | After you have the `misspellings` collection, you can map each `entry.Word` back to its position in `ocrResult.Text` and underline it in a RichTextBox or web view. | + +## Conclusion + +We’ve just shown you **how to perform OCR on image**, **extract text from image**, and then **detect misspelled words** while **getting spelling suggestions**—all with a concise C# console app. The core idea is simple: let Aspose.OCR do the heavy lifting of recognizing characters, then let its built‑in spell‑checker clean up the output. From here you can expand the demo into a full‑blown document processing service, integrate it with a web API, or plug it into a desktop editor. + +Ready for the next step? Try swapping the language to Spanish, feed a multi‑page PDF, or build a small WPF front‑end that lets users click a word to accept a suggestion. The building blocks are already in place—just keep experimenting. + +If you ran into any hiccups or have ideas for extensions, drop a comment below. Happy coding! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/english/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..031cf04c5 --- /dev/null +++ b/ocr/english/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: en +og_description: Perform OCR on image with Aspose OCR in C#. This tutorial shows how + to load image for OCR and extract Hindi text image offline, complete with runnable + code. +og_title: Perform OCR on Image – Aspose OCR Hindi Guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Perform OCR on Image with Aspose OCR – Hindi Guide +url: /net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Perform OCR on Image with Aspose OCR – Hindi Guide + +Ever needed to **perform OCR on image** files but were stuck on how to get Hindi characters out of them? You're not alone—many developers hit that wall when they first try to read non‑Latin scripts. The good news is that Aspose OCR makes it pretty painless, and you can even do it completely offline. + +In this guide we’ll **load image for OCR**, point the engine at your offline language packs, and finally **extract Hindi text image** data without ever touching the internet. By the end you’ll have a ready‑to‑run C# console app that reads a Hindi receipt and prints the text to the console. + +## What You’ll Need + +- **.NET 6.0** or later (the code also works on .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet package + `dotnet add package Aspose.OCR` +- A folder containing the **offline Hindi language resources** (download from Aspose’s portal) +- An image file with Hindi text, e.g., `receipt_hindi.png` + +That’s it—no external services, no API keys, just straight‑line code. + +## Perform OCR on Image – Step‑by‑Step Implementation + +Below we break the process into seven clear steps. Each step is explained **why** it matters, not just **what** to type. + +### Step 1: Create the OCR Engine Instance + +The engine is the heart of Aspose OCR. Instantiating it gives you access to all the settings you’ll tweak later. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Why?** +> Without an `OcrEngine` you have no object to call `Recognize` on. Think of it as the “camera” that will later scan your picture. + +### Step 2: Point the Engine to Offline Resources + +Aspose ships language packs that you can store locally. Setting `ResourcesFolder` tells the engine where to look. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tip:** +> Use an absolute path during development, then switch to a relative path or configuration setting for production. + +### Step 3: Force Offline Mode + +You might wonder, “Do I really need to disable online lookup?” +If you’re working behind a firewall or just want deterministic results, set `UseOfflineResources` to `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> Leaving this flag `false` can cause the engine to download additional data, which adds latency and may breach security policies. + +### Step 4: Select Hindi as the Recognition Language + +Here we **extract Hindi text image** by telling the engine which language to expect. This dramatically improves accuracy. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Why it helps:** +> OCR engines use language‑specific character models. By locking to Hindi, you avoid the engine guessing among dozens of scripts. + +### Step 5: Load Image for OCR + +Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads the bitmap into a format the engine understands. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Common pitfall:** +> Supplying a path with forward slashes on Windows works, but using `Path.Combine` makes your code platform‑agnostic. + +### Step 6: Run the Recognition + +With everything set, we finally **perform OCR on image** by calling `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **What’s happening?** +> The engine scans each pixel, matches patterns against the Hindi glyph database, and builds a string of Unicode characters. + +### Step 7: Output the Recognized Text + +The result object contains a `Text` property that holds the extracted string. We simply write it to the console. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Expected output:** +> If `receipt_hindi.png` contains “भुगतान सफल”, the console will print exactly that line, preserving diacritics. + +## Load Image for OCR – Preparing the Resource + +If you’re wondering whether you can feed the engine a stream instead of a file, the answer is yes. Replace `OcrImage.FromFile` with: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Why use a stream?** +> Streams let you work with images stored in databases, cloud blobs, or embedded resources—perfect for scalable services. + +## Extract Hindi Text Image – Handling Edge Cases + +1. **Missing language pack** – If the Hindi pack isn’t found, `Recognize` throws an exception. Wrap the call in a try/catch and log a friendly message. +2. **Low‑resolution images** – OCR accuracy drops below 300 dpi. Pre‑process the image (resize, sharpen) before loading. +3. **Mixed‑language documents** – You can enable multiple languages: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +These tweaks ensure your **perform OCR on image** routine stays robust in production. + +## Running the Full Example + +Save the following file as `Program.cs`, replace the placeholder paths, and run: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +When you execute `dotnet run`, you should see something like: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +If you get an empty string, double‑check that the **ResourcesFolder** points to the folder containing `Hindi.traineddata` and that the image is clear enough. + +## Conclusion + +We’ve walked through how to **perform OCR on image** files with Aspose OCR, covering everything from **load image for OCR** to **extract Hindi text image** in an entirely offline scenario. The complete, runnable code above gives you a solid foundation, and the tips on streams, error handling, and multi‑language support will help you adapt the solution to real‑world projects. + +Ready for the next step? Try switching the language to **OcrLanguage.Tamil** or feeding images from an Azure Blob storage. You can also experiment with the `ImagePreprocessing` settings to boost accuracy on noisy receipts. + +Got questions or ran into a snag? Drop a comment—happy coding! + +![Perform OCR on image example + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [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/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/english/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..f7442ec9f --- /dev/null +++ b/ocr/english/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-06-03 +description: Perform OCR on PDF and convert scanned PDF to searchable PDF using Aspose.OCR. + Learn how to recognize text from PDF and create searchable PDFs in minutes. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: en +og_description: Perform OCR on PDF and instantly create a searchable PDF. This tutorial + shows step‑by‑step how to recognize text from PDF using Aspose.OCR. +og_title: Perform OCR on PDF – Complete C# Guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Perform OCR on PDF with Aspose.OCR – Complete C# Guide +url: /net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Perform OCR on PDF with Aspose.OCR – Complete C# Guide + +Ever wondered **how to perform OCR on PDF** files without wrestling with dozens of command‑line tools? You're not alone. Whether you're digitizing invoices, archiving old reports, or just need a searchable version of a scanned contract, turning a static PDF into something you can actually search is a game‑changer. + +In this guide we’ll walk through **how to create searchable PDF** files from scanned PDFs (and even plain images) using Aspose.OCR for .NET. By the end you’ll be able to **recognize text from PDF** with a few lines of C# code, and you’ll understand the why behind each step so you can adapt the solution to your own projects. + +> **Quick takeaway:** The entire process boils down to three things—initializing the OCR engine, feeding it the source (PDF or image), and saving the searchable PDF output. Let’s dive in. + +--- + +## What You’ll Need + +Before we start, make sure you have: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.OCR targets modern runtimes; older versions may miss API updates. | +| **Aspose.OCR for .NET** NuGet package | Provides the `OcrEngine` class and PDF handling utilities. | +| **A valid Aspose license** (or use the free evaluation) | Without a license you’ll hit a 30‑day evaluation limit and watermarks. | +| **A scanned PDF** (or an image file) you want to make searchable | This is the source document for OCR. | +| **Visual Studio 2022** (or any C# editor) | Makes debugging easier, but any IDE works. | + +You can install the library with the following NuGet command: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** If you’re working on a CI pipeline, add the license file to the build artefacts and load it at runtime to avoid hard‑coding paths. + +--- + +## Perform OCR on PDF – Setting Up Aspose.OCR + +The first thing we need is a fresh `OcrEngine` instance. Think of it as the brain that will read your document. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Why a new instance every time? The engine holds configuration (like language settings) that can differ per document. Instantiating it per run guarantees a clean slate and avoids cross‑talk between jobs. + +--- + +## How to Create Searchable PDF – Configuring Passwords (Optional) + +If your PDF is protected, you have to tell the engine the password before it can read the pages: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Skipping this step on a protected file will raise a `PdfPasswordException`. Always wrap it in a try‑catch if you’re unsure about the protection status. + +--- + +## Convert Scanned PDF to Searchable PDF – Loading the Source + +Aspose.OCR works with the `OcrImage` abstraction, which can wrap PDFs, TIFFs, JPEGs, etc. Here’s how you pull a scanned PDF into memory: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Behind the scenes, `FromFile` parses each page into raster images that the OCR engine can process. If you have a multi‑page PDF, the engine will automatically iterate over every page. + +--- + +## Recognize Text from PDF – Performing the OCR + +Now the core of the tutorial: ask the engine to recognize the text and output a searchable PDF. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` tells the engine to embed an invisible text layer on top of the original scanned images. The resulting PDF retains the visual fidelity of the scan while becoming fully searchable—exactly what you need for compliance audits. + +--- + +## Convert Image to Searchable PDF – Saving the Result + +Finally, write the binary data to disk: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +The `Binary` property holds the raw PDF bytes. You could also stream them directly to a web response if you’re building an API. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*Image alt text: Perform OCR on PDF flow diagram illustrating how a scanned PDF is turned into a searchable PDF.* + +--- + +## Edge Cases & Practical Tips + +### 1. Large Files & Memory Management +If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Language Support +By default Aspose.OCR assumes English. To recognize other languages, set the `Language` property: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Multi‑Threaded Scenarios +`OcrEngine` is **not** thread‑safe. If you need parallel processing, create a separate engine per thread. + +### 4. Debugging OCR Accuracy +You can extract the plain text from `ocrResult` for debugging: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +If the output looks garbled, experiment with `PreprocessSettings` (e.g., deskew, despeckle) to improve quality. + +### 5. Licensing Gotchas +When you run the evaluation version, Aspose adds a watermark to the output PDF. Register your license early in the application: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Full Working Example – From Start to Finish + +Below is the complete, ready‑to‑run program that incorporates all the tips above. Feel free to copy‑paste it into a new console project. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Expected output:** After running, you’ll see a console line confirming the file location. Open `output.pdf` in any PDF viewer; try typing a word you know appears in the original scan. If the text is highlighted, you’ve successfully **performed OCR on PDF** and created a searchable document. + +--- + +## Frequently Asked Questions + +**Q: Can I use this to convert a single image (PNG/JPEG) to a searchable PDF?** +A: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to your image file. The engine will rasterize the image and embed the OCR layer just the same. + +**Q: What if my PDF has both scanned pages and native text?** +A: The engine will overlay the OCR text on top of existing content, so native text stays selectable while scanned pages become searchable. + +**Q: How accurate is the OCR?** +A: Accuracy hinges on source quality. Clean, high‑resolution scans (>300 dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, despeckle) before calling `Recognize`. + +--- + +## Next Steps – Extending Your OCR Toolkit + +Now that you can **recognize text from PDF** and **convert scanned PDF to searchable PDF**, consider these follow‑up topics: + +- **Batch processing**: Loop over a folder of PDFs and generate searchable versions automatically. +- **Text extraction**: Use `ocrResult.Text` to feed a search index (e.g., Elasticsearch). +- **Custom language packs**: Download additional language data from Aspose to support Asian scripts. +- **PDF/A compliance**: Combine Aspose.PDF with OCR output to create archival‑ready PDFs. + +Each of these builds on the core steps we covered, so you’re well‑positioned to expand your solution. + +--- + +## Wrap‑Up + +We’ve just shown you **how to perform OCR on PDF** files using Aspose.OCR, turned scanned PDFs into fully searchable PDFs, and even covered converting plain images into searchable PDFs. The code + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR 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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/english/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9e6881878 --- /dev/null +++ b/ocr/english/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-06-03 +description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: en +og_description: Learn video subtitle OCR with Aspose.OCR. Extract frames from video, + read text from video, and extract text from MP4 in a few minutes. +og_title: Video Subtitle OCR in C# – Step‑by‑Step Guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: Video Subtitle OCR in C# – Complete Guide +url: /net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Video Subtitle OCR in C# – Complete Guide + +Ever needed **video subtitle ocr** but weren’t sure where to start? You’re not alone. Whether you’re digitizing lecture recordings, pulling captions from training videos, or just curious about reading text from video, this tutorial shows you exactly how to do it with C# and Aspose.OCR. + +In the next few minutes we’ll extract frames from video, run OCR on those frames, and finally display the subtitle text frame‑by‑frame. By the end you’ll be able to **read text from video** files—including MP4—without hunting for third‑party tools. + +## What You’ll Build + +We’ll create a small console app that: + +1. Decodes an MP4 (or any supported format) into individual `Bitmap` frames. +2. Limits the OCR region to the subtitle band so the engine isn’t distracted by the whole picture. +3. Processes each frame with Aspose’s `VideoOcrProcessor`. +4. Prints the recognized subtitle text to the console. + +No fluff, just a working end‑to‑end example you can drop into a real project. + +## Prerequisites + +- **.NET 6.0** or later (the code also works on .NET Framework 4.7+). +- **Aspose.OCR for .NET** – install via NuGet: `Install-Package Aspose.OCR`. +- A video file (MP4 works great). +- A way to decode video frames – the demo uses a placeholder method, but you can plug in FFmpeg, OpenCV, or any library that returns `Bitmap` objects. + +> Pro tip: If you’re on Windows, the `System.Drawing.Common` package works fine for `Bitmap`. On Linux/macOS you’ll need the native `libgdiplus` dependency. + +## Step 1 – Extract Frames from Video + +The first hurdle is turning a moving picture into still images. The method `GetVideoFrames` below is deliberately left blank; replace it with your favourite decoder. Here’s a quick sketch using FFmpeg‑Core (just to illustrate the shape of the data): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Why this matters:** Extracting frames gives the OCR engine a static image to work with, which dramatically improves accuracy compared with trying to read directly from a video stream. + +## Step 2 – Set Up the VideoOcrProcessor + +Now that we have a sequence of `Bitmap` objects, we can hand them to Aspose.OCR. The `VideoOcrProcessor` lets us define a **Region of Interest (ROI)** – perfect for subtitles that usually sit at the top or bottom of the frame. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Why limit the ROI?** By ignoring the rest of the picture we reduce noise, cut down processing time, and avoid false positives from background graphics. + +## Step 3 – Run OCR on the Frame Sequence + +With the processor ready, feeding the frames is a one‑liner. The `Process` method returns an enumerable of `OcrResult` objects, each containing the recognized text for its corresponding frame. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **What’s happening under the hood?** Aspose.OCR internally normalizes each bitmap, runs a neural‑network‑based recognizer, and then post‑processes the output to improve punctuation and line breaks. + +## Step 4 – Display the Extracted Text + +Finally, we iterate over the results and print each subtitle line. You could also write them to a SRT file, a database, or feed them into a translation service. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Full Working Example + +Putting everything together yields a self‑contained console program: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Expected output (sample)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +If the OCR struggles with a particular frame, you’ll see an empty string – that’s a cue to adjust the ROI or increase the frame extraction rate. + +## Common Pitfalls & How to Fix Them + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | Low‑resolution frames or heavy compression | Extract frames at a higher bitrate, or upscale the bitmap before OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI doesn’t actually cover the subtitle band | Verify the rectangle coordinates (use a screenshot tool to measure). | +| **Performance bottleneck** | Processing every frame at 30 fps is overkill | Down‑sample to 1‑2 fps for most subtitle streams; you can still capture every subtitle change. | +| **FFmpeg not found** | `ffmpeg.exe` isn’t on the `PATH` | Provide the full path in `ProcessStartInfo.FileName` or install FFmpeg globally. | + +## Extending the Solution + +- **Export to SRT** – concatenate the timestamps with the OCR text and write a SubRip file. +- **Multi‑language support** – set `ocrProcessor.Language = OcrLanguage.Spanish` (or any supported language). +- **Real‑time processing** – pipe frames directly from a live stream instead of reading from disk. + +All of these variations still revolve around the core ideas of **extract frames from video**, **read text from video**, and **extract text from mp4**. + +## Conclusion + +We’ve just walked through a complete **video subtitle ocr** workflow in C#. By extracting frames from video, focusing the OCR on the subtitle band, and iterating over the results, you can reliably **read text from video** files such as MP4. The code is ready to copy‑paste, and the modular design lets you swap in any frame‑decoder you prefer. + +Next steps? Try exporting the results to an SRT file, experiment with different ROI sizes, or feed the subtitles into a translation API for multilingual captions. The sky’s the limit once you’ve mastered the basics of extracting text from video. + +Happy coding, and may your subtitles always be crystal‑clear! + + +## What Should You Learn Next? + + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step-by-step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/french/net/ocr-configuration/_index.md index d06fa9627..141e80121 100644 --- a/ocr/french/net/ocr-configuration/_index.md +++ b/ocr/french/net/ocr-configuration/_index.md @@ -67,6 +67,9 @@ Libérez la puissance de la reconnaissance d’images OCR dans .NET avec Aspose. Débloquez de puissantes capacités OCR avec Aspose.OCR pour .NET. Extrayez le texte des images de manière transparente. ### [OCROperation avec liste dans la reconnaissance d'images OCR](./ocr-operation-with-list/) +### [Obtenir la version d'Aspose OCR en C# – Guide complet](./get-aspose-ocr-version-in-c-complete-guide/) +Apprenez à récupérer la version d'Aspose OCR dans votre code C# avec un guide complet et des exemples pratiques. + Exploitez pleinement le potentiel d'Aspose.OCR pour .NET. Réalisez facilement la reconnaissance d'images OCR avec des listes. Optimisez la productivité et l'extraction de données dans vos applications. ### Cas d'utilisation courants @@ -115,4 +118,4 @@ R : Oui, l’objet `OcrResult` fournit des valeurs de confiance que vous pouvez {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/french/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..bd25ab8eb --- /dev/null +++ b/ocr/french/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-03 +description: Obtenez la version d’Aspose OCR en C# avec un simple extrait de code. + Apprenez comment récupérer la version de la bibliothèque Aspose OCR en utilisant + OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: fr +og_description: Obtenez rapidement la version d'Aspose OCR en C#. Ce tutoriel montre + exactement comment récupérer la version de la bibliothèque Aspose OCR en utilisant + OcrEngine GetVersion. +og_title: Obtenez la version Aspose OCR en C# – Guide complet +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Obtenez la version Aspose OCR en C# – Guide complet +url: /fr/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Obtenir la version d'Aspose OCR en C# – Guide complet + +Vous êtes‑vous déjà demandé comment **obtenir la version d'Aspose OCR** depuis votre projet .NET ? Peut‑être que vous dépannez une incompatibilité, ou que vous souhaitez simplement enregistrer la version exacte de la bibliothèque qui s’exécute en production. Quelle que soit la raison, vous êtes au bon endroit. + +Dans ce tutoriel, nous allons parcourir un petit programme C# autonome qui appelle `OcrEngine.GetVersion()` et affiche le résultat. À la fin, vous saurez non seulement *comment* récupérer la version, mais aussi *pourquoi* vérifier la version peut vous éviter des maux de tête lors de la mise à jour de la **bibliothèque Aspose OCR**. + +## Ce que vous apprendrez + +- Ajouter le package NuGet Aspose.OCR à un projet C# +- Utiliser la méthode `OcrEngine.GetVersion()` (le point d'entrée **ocrengine getversion**) +- Gérer les éventuelles exceptions et vérifier la sortie +- Étendre le fragment pour des scénarios réels comme la journalisation ou les bascules de fonctionnalités conditionnelles + +Aucune expérience préalable avec l'OCR n'est requise—juste une compréhension de base du C# et de Visual Studio (ou de votre IDE préféré). Commençons. + +--- + +## Étape 1 : Configurer le projet et intégrer la bibliothèque Aspose OCR + +Avant de pouvoir appeler des API liées à l'OCR, vous devez référencer la **bibliothèque Aspose OCR** dans votre projet. + +1. Ouvrez un terminal ou la console du gestionnaire de packages dans Visual Studio. +2. Exécutez la commande suivante pour installer la dernière version stable : + +```bash +dotnet add package Aspose.OCR +``` + +> **Astuce :** Si vous ciblez le .NET Framework au lieu du .NET Core, utilisez l'interface du gestionnaire de packages NuGet et choisissez la version qui correspond à votre environnement d'exécution. Le package inclut la classe `OcrEngine` que nous utiliserons plus tard. + +### Pourquoi c'est important + +Lorsque vous installez le package, la version de l'assembly sur le disque peut différer de la version rapportée par la bibliothèque à l'exécution. Interroger la version via le code garantit que vous lisez la version exacte chargée par le CLR, ce qui est crucial pour le débogage et les audits de conformité. + +## Étape 2 : Écrire le code minimal pour **obtenir la version d'Aspose OCR** + +Créez une nouvelle application console (`dotnet new console -n OcrVersionDemo`) et remplacez le fichier `Program.cs` par défaut par le suivant : + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Explication de chaque partie** + +- `using Aspose.OCR;` importe l'espace de noms OCR, nous permettant d'appeler `OcrEngine`. +- `OcrEngine.GetVersion()` est la méthode statique **ocrengine getversion** qui renvoie une chaîne comme `"24.5.7"`. +- Encapsuler l'appel dans un bloc `try/catch` vous protège des surprises d'exécution—il se peut que les binaires natifs ne soient pas trouvés sur la machine cible. +- La chaîne interpolée `$"Aspose OCR version: {version}"` affiche une ligne claire et lisible par l'homme. + +### Sortie attendue + +Lorsque vous exécutez `dotnet run` dans le dossier du projet, vous devriez voir quelque chose de similaire à : + +``` +Aspose OCR version: 24.5.7 +``` + +Si la bibliothèque ne peut pas être chargée, la branche d'erreur affichera un message concis, vous aidant à identifier rapidement le problème. + +## Étape 3 : Vérifier que la version correspond à votre package NuGet + +Il est facile de supposer que la version NuGet que vous avez installée est celle utilisée à l'exécution, mais des particularités d'environnement peuvent intervenir. Pour vérifier à nouveau : + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +L'exécution de cet extrait supplémentaire affichera quelque chose comme : + +``` +Assembly file version: 24.5.7.0 +``` + +Si les deux valeurs diffèrent, vous pourriez charger une DLL plus ancienne depuis le Global Assembly Cache (GAC) ou depuis un dossier de construction précédent. Dans ce cas, nettoyez votre solution (`dotnet clean`) et reconstruisez. + +## Étape 4 : Intégrer la vérification de version dans la journalisation de production + +La plupart des applications réelles n'affichent pas seulement dans la console ; elles écrivent dans un fichier de journal ou un système de télémétrie. Voici un exemple rapide utilisant `Microsoft.Extensions.Logging` : + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Maintenant, la version apparaît dans vos journaux structurés, ce qui facilite le filtrage par `{Version}` ultérieurement. Ce modèle est particulièrement utile lorsque vous avez plusieurs micro‑services tirant chacun une DLL OCR potentiellement différente. + +## Questions fréquentes & cas limites + +### Que faire si `GetVersion()` renvoie une chaîne vide ? + +Cela indique généralement une installation corrompue ou une dépendance native manquante. Réinstallez le package NuGet et vérifiez que le `Aspose.OCR.Native.dll` (ou le binaire spécifique à la plateforme appropriée) se trouve à côté de votre exécutable. + +### La méthode fonctionne‑t‑elle sur .NET Core 2.0 ? + +Oui, **Aspose OCR** prend en charge .NET Standard 2.0 et supérieur, donc toute version de .NET Core implémentant cette norme peut appeler `OcrEngine.GetVersion()`. Assurez‑vous simplement de référencer les bons identifiants d'exécution (`win‑x64`, `linux‑x64`, etc.) si vous publiez une application autonome. + +### Puis‑je récupérer la version sans fichier de licence ? + +Absolument. `GetVersion()` ne nécessite **pas** de licence ; il indique simplement le numéro de build de la bibliothèque. Cependant, si vous essayez d'exécuter l'OCR sans licence valide, vous obtiendrez une exception d'exécution. C’est pourquoi le `try/catch` dans notre extrait est utile — il isole la vérification de version du flux d'exécution OCR. + +## Exemple complet fonctionnel (prêt à copier‑coller) + +Ci‑dessous se trouve le programme complet, prêt à être intégré dans un nouveau projet console. Il inclut le bloc de journalisation optionnel, afin que vous puissiez voir à la fois la sortie console et les journaux structurés en action. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Exécutez‑le avec `dotnet run` et vous verrez deux lignes confirmant la version, plus une ligne de débogage si vous activez `LogLevel.Debug`. + +## Conclusion + +Nous avons couvert tout ce dont vous avez besoin pour **obtenir la version d'Aspose OCR** dans un environnement C#—de l'installation de la **bibliothèque Aspose OCR**, à l'appel de la méthode **ocrengine getversion**, en passant par la gestion des erreurs, jusqu'à l'intégration du résultat dans une journalisation de niveau production. Armé de ces connaissances, vous pouvez désormais vérifier de manière fiable le build OCR exact utilisé par votre application, éviter les bugs liés aux versions et satisfaire les exigences de conformité sans effort. + +Prochaines étapes ? Essayez d’associer cette vérification de version à un appel OCR réel (`OcrEngine` → `RecognizeImage`) et journalisez à la fois la version et le résultat de reconnaissance. Vous pouvez également explorer le modèle **retrieve aspose version** pour d'autres produits Aspose (PDF, Slides, Cells) afin de garder l’ensemble de votre suite synchronisé. + +Bon codage, et que vos pipelines OCR restent performants ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités d'API supplémentaires et à explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Comment obtenir les résultats OCR avec Aspose.OCR pour .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extraire le texte d'une image en C# avec sélection de langue en utilisant Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Comment traiter par lots des images OCR avec une liste dans Aspose.OCR pour .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/french/net/ocr-optimization/_index.md index 8d188ea7d..e94017477 100644 --- a/ocr/french/net/ocr-optimization/_index.md +++ b/ocr/french/net/ocr-optimization/_index.md @@ -75,6 +75,8 @@ Explorez Aspose.OCR pour .NET. Boostez la précision de l’OCR avec des filtres Améliorez la précision de l’OCR avec Aspose.OCR pour .NET. Corrigez les fautes, personnalisez les dictionnaires et obtenez une reconnaissance de texte sans erreur en toute simplicité. ### [Enregistrer le résultat multipage en tant que document dans la reconnaissance d'image OCR](./save-multipage-result-as-document/) Débloquez le potentiel d’Aspose.OCR pour .NET. Enregistrez sans effort les résultats OCR multipages sous forme de documents grâce à ce guide complet étape par étape. +### [Exemple Aspose OCR C# – Activer le GPU, définir la limite de mémoire et traiter les images TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Apprenez à activer le GPU, définir une limite de mémoire et traiter les fichiers TIF avec Aspose OCR en C#. ## Questions fréquemment posées diff --git a/ocr/french/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/french/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..3f061c3ac --- /dev/null +++ b/ocr/french/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-03 +description: Exemple Aspose OCR C# montrant comment définir la limite de mémoire GPU, + charger une image pour l'OCR et reconnaître le texte des fichiers TIF avec le code + complet et des astuces. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: fr +og_description: 'Apprenez un exemple complet d’Aspose OCR en C# : activez le GPU, + définissez la limite de mémoire du GPU, chargez une image pour l’OCR et reconnaissez + le texte des fichiers TIF. Code complet inclus.' +og_title: Exemple Aspose OCR C# – Accélération GPU, Limite de mémoire et traitement + TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Exemple Aspose OCR C# – Activer le GPU, définir la limite de mémoire et traiter + les images TIF +url: /fr/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exemple Aspose OCR C# – Activer le GPU, définir la limite de mémoire et traiter les images TIF + +Vous êtes-vous déjà demandé comment extraire le maximum de performances du **exemple Aspose OCR C#** lorsqu’il s’agit de scanner d’énormes fichiers TIFF ? Vous n’êtes pas seul. Dans de nombreux projets réels—par exemple la numérisation d’archives ou l’extraction de données à partir de reçus haute résolution—le goulot d’étranglement n’est pas l’algorithme OCR lui‑-même, mais l’utilisation du matériel. + +Voici le point : Aspose OCR prend en charge l’accélération GPU, mais il faut lui indiquer exactement la quantité de mémoire qu’il peut consommer, charger le bon type d’image, puis extraire le texte reconnu d’un fichier .tif. Ce tutoriel vous guide pas à pas, de l’installation du SDK à l’ajustement des paramètres GPU, afin que vous puissiez exécuter l’OCR à une vitesse fulgurante sans saturer la RAM de votre GPU. + +Nous ajouterons également quelques scénarios « et si »—comme la gestion des TIFF multi‑pages ou le basculement vers le CPU lorsqu’aucun GPU n’est disponible—pour que vous disposiez d’une solution robuste, et non d’un simple extrait de code. + +## Ce dont vous avez besoin + +Avant de commencer, assurez‑vous que les éléments suivants sont présents sur votre machine : + +| Prérequis | Pourquoi c’est important | +|--------------|----------------| +| **.NET 6 SDK** (ou version ultérieure) | Aspose OCR cible .NET Standard 2.0+, donc toute version récente de .NET fonctionne. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | La bibliothèque principale qui fournit `OcrEngine`, `GpuSettings`, etc. | +| **CUDA 11+** (NVIDIA) **ou ROCm 5+** (AMD) | Nécessaire pour l’accélération GPU ; le SDK vérifiera la présence d’un pilote compatible au moment de l’exécution. | +| Un **GPU avec au moins 2 Go de VRAM** (nous le limiterons à 2048 Mo) | Sans assez de mémoire, le moteur peut revenir silencieusement au CPU. | +| Une image **TIFF haute résolution** que vous souhaitez traiter | Aspose OCR peut lire pratiquement n’importe quel format raster, mais le TIF est courant pour les numérisations. | +| Visual Studio 2022 (ou tout autre éditeur) | Pour compiler et déboguer le projet C#. | + +Si l’un de ces éléments manque, le code compilera tout de même, mais vous ne constaterez pas les gains de performance recherchés. + +## Étape 1 : Créer le moteur d’exemple Aspose OCR C# + +La première chose dans chaque **exemple Aspose OCR C#** est d’instancier le moteur OCR. Pensez à `OcrEngine` comme le réalisateur d’un film — il coordonne tout, du chargement de l’image à l’extraction du texte. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Astuce :** Si vous prévoyez de traiter de nombreuses images consécutivement, conservez un seul `OcrEngine` en vie. Le recréer à chaque image ajoute un surcoût qui peut largement dépasser le temps d’OCR. + +## Étape 2 : Définir la limite de mémoire GPU (et activer l’accélération) + +Vient maintenant la partie qui fait souvent trébucher les développeurs : **définir la limite de mémoire GPU**. Par défaut, Aspose OCR essaiera d’utiliser autant de VRAM que possible, ce qui, sur une station de travail partagée, peut priver d’autres applications de ressources. L’objet `GpuSettings` vous permet de plafonner l’allocation. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Pourquoi définir une limite de mémoire ? + +- **Stabilité :** Empêche les plantages « out‑of‑memory » lors du traitement d’images gigantesques. +- **Coexistence :** Permet à d’autres applications gourmandes en GPU (par ex. modèles TensorFlow) de fonctionner côte à côte. +- **Prévisibilité :** Rend les tests de performance reproductibles, car le GPU ne commencera pas à swapper. + +Si vous omettez `MemoryLimitMb`, Aspose allouera ce qu’il juge nécessaire, ce qui peut convenir à un serveur dédié à l’inférence mais reste risqué sur un ordinateur portable de développeur. + +## Étape 3 : Charger l’image pour l’OCR + +Le chargement du bon format de fichier est l’étape suivante cruciale. La méthode `OcrImage.FromFile` détecte automatiquement le type d’image, mais vous devez tout de même vérifier que le fichier existe et qu’il s’agit d’une variante TIFF prise en charge (par ex. LZW‑compressé ou CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Gestion des TIFF multi‑pages + +Si votre TIFF contient plusieurs pages, Aspose OCR ne lira par défaut que la première. Pour traiter toutes les pages, vous pouvez itérer sur `image.Pages` (disponible dans les versions récentes du SDK) et fournir chaque page au moteur séparément. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +L’extrait ci‑dessus montre un **modèle de chargement d’image pour l’OCR** qui fonctionne tant pour les fichiers à page unique que pour les fichiers multi‑pages. + +## Étape 4 : Reconnaître le texte à partir d’un TIF (ou tout raster) + +Maintenant que l’image réside en mémoire, nous demandons à Aspose d’effectuer sa magie. La méthode `Recognize` renvoie un `OcrResult` contenant le texte brut, les scores de confiance, et même les informations de boîte englobante si vous en avez besoin. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Pourquoi cela fonctionne bien avec le TIF + +- **Compression sans perte :** Le TIFF stocke souvent les données brutes des pixels, offrant à l’engin OCR la plus haute fidélité. +- **Multiples espaces colorimétriques :** Aspose peut gérer les TIFF en niveaux de gris, RGB ou même CMYK sans code de conversion supplémentaire. + +Si vous devez ajuster les packs de langues (par ex. français ou japonais), définissez `ocrEngine.Settings.Language = "fr"` avant d’appeler `Recognize`. + +## Étape 5 : Afficher le texte reconnu + +Enfin, nous affichons le texte dans la console. Dans une application réelle, vous pourriez écrire dans une base de données, un fichier JSON, ou transmettre la chaîne à un pipeline NLP en aval. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Sortie attendue + +Exécuter le programme sur une numérisation nette de 300 dpi d’une page imprimée donne généralement quelque chose comme : + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Si l’image est floue ou que la limite de mémoire GPU est trop basse, vous pourriez voir des caractères corrompus ou un résultat tronqué. Réduire `MemoryLimitMb` en dessous de l’empreinte de l’image (souvent ~1 Go pour un TIFF de 6000×8000 pixels) peut entraîner le basculement automatique vers le CPU. + +## Exemple complet fonctionnel + +Voici le programme complet, prêt à être exécuté. Copiez‑collez‑le dans un nouveau projet Console App, remplacez `YOUR_DIRECTORY/large_photo.tif` par le chemin de votre propre TIFF, puis appuyez sur **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Liste de contrôle rapide + +- ✅ **Exemple Aspose OCR C#** compilé sans erreurs. +- ✅ **GPU activé** (`Enable = true`). +- ✅ **Limite de mémoire GPU** fixée à 2048 Mo. +- ✅ **Image chargée** depuis un fichier TIF. +- ✅ **Texte reconnu** et affiché. + +## Problèmes courants et comment les éviter + +| Symptôme | Cause probable | Solution | +|---------|----------------|----------| +| `System.DllNotFoundException: cudart64_110.dll` | Runtime CUDA non installé ou version incompatible. | Installez CUDA 11.x (ou 12.x) correspondant à votre pilote. | +| OCR renvoie une chaîne vide | Image trop sombre ou DPI < 150. | Pré‑traitez avec `image.AdjustContrast()` ou rééchantillonnez à 300 dpi. | +| Plantage « out‑of‑memory » sur le GPU | `MemoryLimitMb` trop bas pour l’image. | Augmentez la limite ou découpez l’image en tuiles via `image.Crop`. | +| Erreur « Unsupported image format » | Le TIFF utilise une compression exotique (ex. JPEG‑2000). | Convertissez le TIFF en un format supporté avec ImageMagick avant l’OCR. | + +## Étendre la démo + +Maintenant que vous disposez d’un **exemple aspose ocr c#** solide, vous pourriez explorer : + +- **Traitement par lots :** Boucler sur un dossier de TIF, écrire chaque résultat dans un fichier `.txt`. +- **Packs de langues :** `ocrEngine.Settings.Language = "es"` pour l’espagnol, ou charger des dictionnaires personnalisés. +- **Boîtes englobantes :** Utiliser `ocrResult.Regions` pour obtenir les coordonnées de chaque mot—pratique pour les outils de rédaction. +- **Basculement CPU :** Enveloppez le bloc GPU dans un try/catch ; en cas d’échec, définissez `ocrEngine.Settings.Gpu.Enable = false` et réessayez. + +Ces extensions conservent le modèle de base tout en ajoutant de la valeur pour des cas d’utilisation spécifiques. + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extraire du texte d'une image avec Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extraire du texte d'une image – Optimisation OCR avec Aspose.OCR pour .NET](/ocr/english/net/ocr-optimization/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/skew-angle-calculation/_index.md b/ocr/french/net/skew-angle-calculation/_index.md index c7073d788..bfb22f983 100644 --- a/ocr/french/net/skew-angle-calculation/_index.md +++ b/ocr/french/net/skew-angle-calculation/_index.md @@ -35,14 +35,17 @@ Intégrez sans effort Aspose.OCR pour .NET dans vos projets et améliorez la rec En conclusion, nos didacticiels de calcul de l'angle d'inclinaison vous servent de boussole dans le domaine de la reconnaissance d'images OCR. Que vous soyez un passionné de C# ou un aficionado de Java, Aspose.OCR vous fournit les outils nécessaires pour conquérir les angles d'inclinaison et élever vos projets vers de nouveaux sommets. Explorez, apprenez et révolutionnez votre parcours de développement avec nous ! ## Tutoriels de calcul de l'angle d'inclinaison ### [Calculer l'angle d'inclinaison dans la reconnaissance d'images OCR](./calculate-skew-angle/) -Explorez Aspose.OCR pour .NET, une solution OCR puissante pour une reconnaissance de texte précise dans vos applications C#. +Explore Aspose.OCR pour .NET, une solution OCR puissante pour une reconnaissance de texte précise dans vos applications C#. ### [Calculer l'angle d'inclinaison du flux dans la reconnaissance d'image OCR](./calculate-skew-angle-from-stream/) Libérez la puissance d'Aspose.OCR pour .NET, une solution robuste pour la reconnaissance d'images. Apprenez à calculer les angles d'inclinaison sans effort. ### [Calculer l'angle d'inclinaison à partir de l'URI dans la reconnaissance d'images OCR](./calculate-skew-angle-from-uri/) Explorez Aspose.OCR pour .NET pour calculer sans effort les angles d'inclinaison dans la reconnaissance d'images OCR. Valorisez vos projets avec précision et efficacité. +### [Tutoriel de document OCR pivoté – Correction automatique de l'inclinaison et de la rotation en C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Apprenez à corriger automatiquement l'inclinaison et la rotation des documents OCR en C# avec Aspose.OCR. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/french/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..a49fa0a5a --- /dev/null +++ b/ocr/french/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Tutoriel OCR de document pivoté qui montre comment corriger automatiquement + l’inclinaison et détecter la rotation à l’aide d’Aspose OCR en C#. Apprenez étape + par étape avec le code complet. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: fr +og_description: Le tutoriel OCR de document pivoté vous apprend comment corriger automatiquement + l’inclinaison et détecter la rotation en utilisant Aspose OCR en C#. Suivez le guide + complet. +og_title: Tutoriel OCR de document pivoté – Correction automatique du biais et de + la rotation en C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Tutoriel OCR de document pivoté – Correction automatique de l’inclinaison et + de la rotation en C# +url: /fr/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutoriel OCR Document Tourné – Guide complet pour les développeurs C# + +Vous êtes déjà tombé sur un **tutoriel OCR document tourné** lorsqu’un formulaire numérisé arrive de travers ou incliné ? Vous n’êtes pas seul. Ces images bancales peuvent ruiner une extraction de texte propre, mais la bonne nouvelle, c’est qu’Aspose OCR peut redresser les choses automatiquement. + +Dans ce guide pas‑à‑pas, nous créerons un `OcrEngine`, activerons la **correction automatique de l’inclinaison** et la **détection automatique de la rotation**, exécuterons le moteur sur une image tournée, et afficherons le texte nettoyé. À la fin, vous saurez exactement pourquoi chaque paramètre est important, comment l’ajuster pour les cas limites, et vous disposerez d’un programme C# prêt à l’emploi. + +## Ce que vous allez apprendre + +* Comment installer et référencer **Aspose OCR** dans un projet .NET. +* Pourquoi activer `AutoCorrectSkew` et `AutoDetectRotation` est la clé d’un **tutoriel OCR document tourné** fiable. +* Comment charger n’importe quelle image (JPG, PNG, TIFF) et laisser le moteur faire le gros du travail. +* Astuces pour gérer les PDF multi‑pages, les scans basse résolution et les packs de langues personnalisés. + +> **Prérequis :** Visual Studio 2022 (ou tout IDE C#), runtime .NET 6+ et une licence valide Aspose OCR (ou l’essai gratuit). Aucune expérience préalable en OCR n’est requise. + +--- + +## Étape 1 – Installer Aspose OCR et configurer le projet + +Première chose à faire. Récupérez le package NuGet : + +```bash +dotnet add package Aspose.OCR +``` + +> **Astuce :** Si vous utilisez une licence d’essai, placez le fichier `Aspose.OCR.lic` dans le même dossier que votre exécutable, ou enregistrez‑le par programme avec `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Créez une nouvelle application console : + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Vous avez maintenant une base propre pour notre **tutoriel OCR document tourné**. + +## Étape 2 – Initialiser le moteur OCR + +Le moteur est le cœur du processus. Pensez‑y comme un couteau suisse pour l’extraction de texte ; il suffit de lui dire quels outils activer. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Pourquoi ces paramètres ?** +* `AutoCorrectSkew` analyse la ligne de base des caractères et fait pivoter l’image juste assez pour rendre les lignes horizontales. +* `AutoDetectRotation` examine l’orientation globale (0°, 90°, 180°, 270°) et retourne la page si elle est à l’envers. Sans eux, le moteur lirait « pɹᴉʍ » au lieu de « word ». + +## Étape 3 – Charger l’image à traiter + +Aspose OCR fonctionne avec tous les formats raster courants. Remplacez le chemin factice par le vrai emplacement de votre formulaire tourné. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Cas limite :** Si vous recevez un TIFF multi‑pages, utilisez `OcrImage.FromMultiPageTiff(filePath)` et parcourez `image.Pages`. + +## Étape 4 – Exécuter la reconnaissance + +Maintenant le moteur fait la magie. Il redresse d’abord l’image (grâce à nos drapeaux d’inclinaison/rotation) puis extrait les caractères. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Si vous avez besoin d’un support linguistique au‑delà de l’anglais, définissez‑le avant d’appeler `Recognize` : + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Étape 5 – Afficher le texte reconnu + +Enfin, déversez le texte propre dans la console — ou redirigez‑le vers un fichier, une base de données, ce qui convient à votre flux de travail. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Sortie attendue** (en supposant que l’image d’exemple contienne « Invoice #1234 ») : + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Remarquez comment le texte apparaît correctement même si l’image source était tournée de 90° et légèrement inclinée. + +--- + +## Gestion des problèmes courants + +| Problème | Pourquoi cela se produit | Solution | +|------|----------------|-----| +| **Sortie vide** | Correction d’inclinaison désactivée ou image trop sombre. | Activez `AutoCorrectSkew` (déjà activé) et augmentez le contraste de l’image via `image.AdjustContrast(1.2)`. | +| **Caractères illisibles** | Paramètre de langue incorrect. | Définissez `ocrEngine.Settings.Language` pour correspondre à la langue du document. | +| **Lenteur sur de gros PDF** | Le moteur traite chaque page séquentiellement. | Utilisez `Parallel.ForEach` sur `image.Pages` pour exploiter les CPU multi‑cœurs. | +| **Exception de licence** | Essai expiré. | Procurez‑vous une licence permanente ou restez dans les limites de l’essai (5 pages par exécution). | + +--- + +## Astuces pro pour un tutoriel OCR Document Tourné robuste + +* **Traitement par lots :** Enveloppez tout le flux dans une méthode qui accepte un chemin de dossier, parcourt chaque image et écrit chaque résultat dans un fichier `.txt`. +* **Pré‑traitement :** Parfois, un scan bruyant bénéficie de `image.Denoise()` avant la reconnaissance. +* **Post‑traitement :** Utilisez des expressions régulières pour nettoyer les erreurs courantes d’OCR, par ex. remplacer « 0 » par « O » uniquement lorsqu’il est entouré de lettres. +* **Journalisation :** Aspose OCR fournit `ocrEngine.Logger` – connectez‑le à un logger fichier pour capturer les avertissements sur les scores de confiance faibles. + +--- + +## Code complet, prêt à l’exécution + +Enregistrez ce qui suit sous le nom `Program.cs` dans votre projet console. Il inclut toutes les étapes, les commentaires et un petit helper pour le traitement par lots. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Exécutez‑le : + +```bash +dotnet run +``` + +Vous devriez voir le texte nettoyé affiché dans la console, prouvant que notre **tutoriel OCR document tourné** fonctionne de bout en bout. + +--- + +## Conclusion + +Vous disposez maintenant d’un **tutoriel OCR document tourné** complet qui corrige automatiquement l’inclinaison, détecte la rotation et extrait du texte propre avec Aspose OCR en C#. La leçon clé ? Activer `AutoCorrectSkew` **et** `AutoDetectRotation` transforme un scan désespérément incliné en une sortie parfaitement lisible en quelques lignes de code. + +À partir d’ici, vous pouvez étendre aux traitements par lots, intégrer des packs de langues, ou alimenter les résultats dans des pipelines d’analyse en aval. Vous voulez explorer davantage la **correction automatique d’inclinaison** ? Consultez l’API de pré‑traitement d’image d’Aspose, ou expérimentez avec des seuils personnalisés pour les scans bruyants. + +Des questions sur la gestion des PDF, des TIFF multi‑pages, ou l’intégration avec Azure Functions ? Laissez un commentaire, et bon codage ! + +## Que devez‑vous apprendre ensuite ? + + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code fonctionnels complets avec des explications pas‑à‑pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/french/net/text-recognition/_index.md index 1b27348f2..8c1867727 100644 --- a/ocr/french/net/text-recognition/_index.md +++ b/ocr/french/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Libérez la puissance d’Aspose.OCR pour .NET. Apprenez à obtenir des résulta Améliorez vos applications .NET avec Aspose.OCR pour une reconnaissance efficace du texte des images. Explorez le mode de détection des zones OCR pour des résultats précis. ### [Reconnaître un PDF dans la reconnaissance d'images OCR](./recognize-pdf/) Libérez le potentiel de l’OCR dans .NET avec Aspose.OCR. Extrayez le texte des PDF sans effort. Téléchargez-le maintenant pour une expérience d'intégration transparente. +### [Effectuer une OCR sur un PDF avec Aspose.OCR – Guide complet C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Apprenez à réaliser une OCR sur des PDF avec Aspose.OCR en suivant notre guide complet en C#. ### [Reconnaître la table dans la reconnaissance d'images OCR](./recognize-table/) Libérez le potentiel d'Aspose.OCR pour .NET avec notre guide complet sur la reconnaissance des tableaux dans la reconnaissance d'images OCR. +### [Effectuer une OCR sur une image avec Aspose OCR – Guide Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Apprenez à réaliser une OCR d'image avec Aspose OCR en suivant notre guide complet en hindi. +### [Comment utiliser Aspose : convertir une image en HTML avec OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Apprenez à convertir des images en HTML en utilisant la reconnaissance OCR d’Aspose pour .NET. +### [Effectuer une OCR sur une image et détecter les mots mal orthographiés en C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Apprenez à extraire du texte d’une image avec Aspose.OCR et à identifier les mots mal orthographiés en C#. +### [OCR de sous-titres vidéo en C# – Guide complet](./video-subtitle-ocr-in-c-complete-guide/) +Apprenez à extraire les sous-titres des vidéos avec Aspose.OCR en C# grâce à ce guide complet. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/french/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..07449f036 --- /dev/null +++ b/ocr/french/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-06-03 +description: Comment utiliser Aspose pour convertir une image en HTML et extraire + le texte d’une image en C#. Apprenez à générer du HTML à partir d’une image et à + faire de l’OCR d’image vers HTML rapidement. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: fr +og_description: Comment utiliser Aspose pour convertir une image en HTML, extraire + le texte d’une image et générer du HTML à partir d’une image avec OCR en C#. Suivez + ce guide complet. +og_title: 'Comment utiliser Aspose : convertir une image en HTML avec OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Comment utiliser Aspose : convertir une image en HTML avec OCR' +url: /fr/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment utiliser Aspose : Convertir une image en HTML avec OCR + +Vous vous êtes déjà demandé **comment utiliser Aspose** pour transformer une image numérisée en HTML propre ? Peut‑être avez‑vous une page de magazine, un reçu ou une note manuscrite et vous avez besoin de conserver le texte et la mise en page pour la publier sur le web. La bonne nouvelle, c’est que vous n’avez pas besoin d’écrire un analyseur personnalisé ou de vous battre avec du traitement d’image bas‑niveau — Aspose.OCR fait le gros du travail pour vous. + +Dans ce tutoriel, nous allons parcourir un **exemple complet et exécutable** qui montre comment **convertir une image en HTML**, **extraire le texte d’une image**, et **générer du HTML à partir d’une image** en utilisant la bibliothèque Aspose OCR en C#. À la fin, vous disposerez d’une petite application console qui produit un fichier HTML avec la mise en page d’origine intacte, prête à être intégrée à n’importe quel site web. + +## Prérequis + +Avant de commencer, assurez‑vous d’avoir les éléments suivants sur votre machine : + +- **.NET 6.0 SDK** ou version ultérieure (le code fonctionne aussi bien avec .NET Core qu’avec .NET Framework). +- **Visual Studio 2022** (ou tout autre éditeur de votre choix). +- **Aspose.OCR for .NET** – installez‑le via NuGet : `dotnet add package Aspose.OCR`. +- Un fichier image (JPEG/PNG) que vous souhaitez transformer, par ex. `magazine_page.jpg`. + +Aucun fichier de configuration supplémentaire n’est requis ; la bibliothèque fournit tout ce qui est nécessaire pour l’OCR et la génération de mise en page HTML. + +## Étape 1 : Créer le projet et ajouter Aspose.OCR + +Tout d’abord, créez un nouveau projet console et ajoutez le package Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Astuce :** Si vous utilisez Visual Studio, faites simplement un clic droit sur le projet → *Manage NuGet Packages* → recherchez **Aspose.OCR** et installez‑le. Cette étape vous permet de **ocr image to html** sans références manquantes. + +## Étape 2 : Initialiser le moteur OCR + +Le cœur du processus est la classe `OcrEngine`. Pensez‑y comme le cerveau qui lit l’image et décide du format de sortie. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Ici nous instancions `OcrEngine`. Vous n’avez pas besoin de fournir des informations d’identification pour la version gratuite ; la bibliothèque utilise ses modèles de reconnaissance intégrés. + +## Étape 3 : Charger l’image source + +Ensuite, indiquez au moteur le fichier que vous voulez traiter. Aspose propose la méthode pratique `OcrImage.FromFile` qui gère la plupart des formats d’image. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Remplacez `YOUR_DIRECTORY` par le chemin absolu ou relatif où se trouve votre image. Si l’image se trouve dans le même dossier que l’exécutable, vous pouvez simplement utiliser `"magazine_page.jpg"`. + +## Étape 4 : Reconnaître et demander le HTML avec mise en page + +C’est le cœur du tutoriel. En passant `OutputFormat.HtmlWithLayout`, nous indiquons à Aspose de **générer du HTML à partir de l’image** tout en conservant le positionnement original des blocs de texte, images et tableaux. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +La propriété `recognitionResult.Text` contient maintenant un document HTML complet. Si vous ne vouliez que du texte brut, vous pourriez utiliser `OutputFormat.Text`, mais nous nous concentrons sur le **convert image to html** avec fidélité de mise en page. + +## Étape 5 : Enregistrer le fichier HTML + +Enfin, écrivez la chaîne HTML sur le disque. Vous obtenez ainsi un fichier prêt à l’emploi que vous pouvez ouvrir dans n’importe quel navigateur. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +L’exécution du programme produira `magazine.html`. Ouvrez‑le, et vous verrez le texte de la page d’origine positionné exactement comme il apparaissait dans l’image source — parfait pour l’archivage ou la publication web. + +## Exemple complet fonctionnel + +Voici le programme **complet, prêt à copier‑coller**. Aucun morceau n’est omis, vous pouvez le compiler et l’exécuter immédiatement après avoir renseigné les bons chemins. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Résultat attendu + +Lorsque vous ouvrirez `magazine.html` dans un navigateur, vous devriez voir quelque chose de similaire (simplifié à titre d’illustration) : + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Les attributs `style` exacts différeront selon l’image d’origine, mais la structure garantit que **extract text from image** et **generate html from image** s’effectuent en une seule étape fluide. + +## Questions fréquentes & cas particuliers + +### Que faire si l’image est de basse résolution ? + +Aspose.OCR fonctionne au mieux avec des images d’au moins **300 DPI**. Si votre fichier est flou, essayez de le pré‑traiter avec une bibliothèque d’amélioration d’image (par ex., ImageSharp) avant de le transmettre au moteur OCR. Une mauvaise qualité peut affecter à la fois la précision de **extract text from image** et la fidélité du layout HTML généré. + +### Puis‑je contrôler la langue de l’OCR ? + +Oui. Définissez la propriété `Language` sur le `OcrEngine` avant d’appeler `Recognize` : + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Cela améliore la reconnaissance lorsqu’il s’agit de caractères non anglais. + +### Comment obtenir du texte brut au lieu du HTML ? + +Si vous ne souhaitez que la chaîne brute, remplacez `OutputFormat.HtmlWithLayout` par `OutputFormat.Text`. La même propriété `recognitionResult.Text` contiendra alors uniquement les caractères extraits. + +### Existe‑t‑il un moyen d’incorporer les images dans le HTML généré ? + +Aspose.OCR peut intégrer l’image originale sous forme de data‑URI base‑64 lorsque vous utilisez `OutputFormat.HtmlWithLayoutAndImages`. C’est pratique si vous voulez un fichier HTML unique sans ressources externes. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Et pour le traitement de gros lots ? + +Pour le traitement par lots, encapsulez la logique dans une boucle `foreach` parcourant une liste de chemins de fichiers. Réutiliser la même instance de `OcrEngine` réduit la surcharge et accélère le pipeline **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Conseils pour un code prêt pour la production + +- **Libérer les ressources** : `OcrEngine` et `OcrImage` implémentent `IDisposable`. Enveloppez‑les dans des instructions `using` pour libérer rapidement la mémoire native. +- **Gestion des erreurs** : Capturez `IOException` pour les problèmes liés aux fichiers et `OcrException` pour les erreurs de reconnaissance. +- **Performance** : Si vous traitez de nombreuses images, envisagez d’activer le **parallélisme** (`Parallel.ForEach`) tout en surveillant l’utilisation du CPU — l’OCR est gourmand en ressources. +- **Journalisation** : Intégrez un logger (par ex., Serilog) pour enregistrer les scores de confiance OCR (`recognitionResult.Confidence`) afin de monitorer la qualité. + +## Conclusion + +Nous venons de couvrir **comment utiliser Aspose** pour **convertir une image en HTML**, **extraire le texte d’une image**, et **générer du HTML à partir d’une image** en quelques étapes simples. L’exemple complet montre comment **ocr image to html** tout en conservant la mise en page, constituant une base solide pour tout projet de numérisation de documents. + +À partir d’ici, vous pouvez : + +- Expérimenter avec les différentes options `OutputFormat` selon vos besoins. +- Combiner la sortie HTML avec un framework CSS pour un rendu réactif. +- Alimenter le texte extrait dans un index de recherche ou un pipeline d’apprentissage automatique. + +Essayez, ajustez les paramètres, et constatez à quel point Aspose transforme facilement les images en contenu prêt pour le web. Si vous rencontrez des difficultés, laissez un commentaire — bon codage ! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + + +## Que devriez‑vous apprendre ensuite ? + + +Les tutoriels suivants abordent des sujets étroitement liés qui s’appuient sur les techniques présentées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et à explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/french/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..37c116fed --- /dev/null +++ b/ocr/french/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,247 @@ +--- +category: general +date: 2026-06-03 +description: Effectuez une OCR sur une image et extrayez le texte à l'aide d'Aspose.OCR. + Apprenez à détecter les mots mal orthographiés et à obtenir des suggestions d'orthographe + dans une démonstration C# unique. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: fr +og_description: Effectuer une OCR sur l’image pour extraire le texte, puis détecter + les mots mal orthographiés et obtenir des suggestions d’orthographe avec Aspose.OCR + en C#. +og_title: Effectuer la reconnaissance optique de caractères sur une image et détecter + les mots mal orthographiés en C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Effectuer une reconnaissance optique de caractères sur une image et détecter + les mots mal orthographiés en C# +url: /fr/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Effectuer la reconnaissance optique de caractères (OCR) sur une image et détecter les mots mal orthographiés en C# + +Vous êtes-vous déjà demandé comment **perform OCR on image** des fichiers sans perdre patience ? Vous n'êtes pas seul. Que vous numérisiez de vieilles lettres, scanniez des reçus ou construisiez un flux de travail intelligent pour les documents, extraire du texte propre à partir d’images est le premier obstacle. Bonne nouvelle : avec Aspose.OCR, vous pouvez mettre en place une solution en quelques minutes, et en prime vous pouvez également **detect misspelled words** et **get spelling suggestions** lors de la même exécution. + +Dans ce tutoriel, nous allons parcourir une application console C# complète, prête à l’emploi, qui **extracts text from image**, exécute un correcteur orthographique anglais, et affiche chaque erreur avec des suggestions de correction pratiques. À la fin, vous saurez exactement **how to extract text**, comment appeler l’API de vérification orthographique, et à quoi ressemble la sortie console attendue. + +## Ce que vous allez créer + +- Charger un bitmap (ou PNG) contenant des fautes typographiques. +- Exécuter Aspose.OCR pour **perform OCR on image** et obtenir les données brutes sous forme de chaîne. +- Initialiser le correcteur orthographique anglais intégré. +- **Detect misspelled words** et **get spelling suggestions** pour chaque mot. +- Imprimer un rapport clair dans la console. + +Pas de services externes, pas d’appels HTTP compliqués — juste un seul package NuGet et quelques lignes de code. + +## Prérequis + +- .NET 6.0 SDK ou version ultérieure (le code fonctionne également avec .NET Framework 4.7+). +- Visual Studio 2022 (ou tout autre éditeur de votre choix). +- Package NuGet Aspose.OCR for .NET (`Aspose.OCR`). +- Un fichier image (`letter_with_typos.png`) placé quelque part où le projet peut y accéder. + +Si vous n’avez jamais utilisé Aspose auparavant, pas d’inquiétude — l’installation du package est aussi simple que d’exécuter : + +```bash +dotnet add package Aspose.OCR +``` + +Passons maintenant à l’implémentation. + +## Étape 1 : Créer le projet et installer Aspose.OCR + +Créez un nouveau projet console et ajoutez la bibliothèque OCR : + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Une fois la restauration terminée, ouvrez `Program.cs`. Nous remplacerons le contenu par défaut par le code complet plus tard, mais commençons d’abord par expliquer l’utilité de chaque espace de noms. + +- `Aspose.OCR` – Moteur OCR principal et gestion des images. +- `Aspose.OCR.SpellCheck` – Utilitaires de vérification orthographique fournis avec la bibliothèque. +- `System` – Classes de base .NET standard (par ex., `Console`). + +## Étape 2 : Charger l’image et **perform OCR on image** + +Le premier vrai travail consiste à fournir l’image au moteur OCR. Aspose.OCR lit de nombreux formats (PNG, JPEG, TIFF). Voici l’extrait qui fait le gros du travail : + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Pourquoi c’est important :** `OcrImage.FromFile` masque les détails au niveau des pixels, tandis que `OcrEngine.Recognize` exécute le modèle neuronal entraîné qui traduit les glyphes visuels en caractères Unicode. La propriété `ocrResult.Text` contient maintenant la chaîne brute — exactement ce dont vous avez besoin pour **extract text from image**. + +> **Astuce :** Si votre image contient plusieurs langues, vous pouvez définir `ocrEngine.Language = OcrLanguage.Multilingual;` avant d’appeler `Recognize`. + +## Étape 3 : Initialiser le correcteur orthographique anglais + +Aspose.OCR fournit un moteur de vérification orthographique intégré qui comprend l’anglais dès le départ. L’initialiser ne prend qu’une ligne : + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Pourquoi cette étape est cruciale :** La sortie OCR peut inclure des caractères mal reconnus (par ex., “l” vs “1”) ou de véritables fautes de frappe du document source. Le correcteur orthographique analysera la chaîne, repérera les jetons suspects et proposera des alternatives. + +## Étape 4 : **Detect misspelled words** et obtenir les suggestions + +Nous injectons maintenant le texte OCR dans le vérificateur : + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` est une collection où chaque entrée contient le mot erroné et un tableau de corrections possibles. + +## Étape 5 : Afficher les résultats + +Enfin, nous parcourons la collection et imprimons un rapport lisible : + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Sortie console attendue + +En supposant que `letter_with_typos.png` contienne la phrase : + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +L’exécution du démonstration produira quelque chose comme : + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Remarquez comment chaque faute est associée à plusieurs corrections plausibles — exactement ce qu’il faut pour créer une interface utilisateur de correction conviviale. + +## Exemple complet fonctionnel + +Voici le programme **complet, prêt à copier‑coller**. Remplacez `YOUR_DIRECTORY` par le chemin réel vers votre fichier image. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Cas limites à considérer** +> - **Image vide :** Si le moteur OCR renvoie une chaîne vide, `spellChecker.Check` renverra simplement une collection vide — pas de plantage. +> - **Texte non anglais :** Remplacez `OcrLanguage.English` par `OcrLanguage.French` (ou toute langue prise en charge) pour **detect misspelled words** dans d’autres paramètres régionaux. +> - **Documents volumineux :** Pour les PDF multi‑pages, vous parcourriez chaque page, exécuteriez l’OCR, puis agrègeriez les résultats avant la vérification orthographique. + +## Vue d’ensemble visuelle (texte alternatif) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*Le diagramme ci‑dessus illustre le pipeline de bout en bout : image → moteur OCR → texte brut → correcteur orthographique → suggestions.* + +## Questions fréquentes & Astuces avancées + +| Question | Réponse | +|----------|--------| +| **Ai‑je besoin d’une connexion Internet ?** | Non. Aspose.OCR fonctionne entièrement en local ; idéal pour les environnements hors ligne ou sécurisés. | +| **Quelle est la précision du correcteur orthographique ?** | Il utilise un dictionnaire d’environ 150 k mots anglais et un algorithme de correspondance floue, donc la plupart des fautes courantes sont détectées. | +| **Puis‑je personnaliser le dictionnaire ?** | Oui. `SpellChecker.AddUserDictionary("custom.txt")` vous permet de charger des termes spécifiques à votre domaine (par ex., noms de produits). | +| **Que faire si l’image est inclinée ?** | Le moteur OCR détecte automatiquement l’orientation, mais vous pouvez appeler manuellement `ocrEngine.ImagePreprocessing.Rotate(angle)` pour les cas récalcitrants. | +| **Existe‑t‑il un moyen de mettre en évidence les suggestions dans l’UI ?** | Après avoir récupéré la collection `misspellings`, vous pouvez mapper chaque `entry.Word` à sa position dans `ocrResult.Text` et le souligner dans un RichTextBox ou une vue web. | + +## Conclusion + +Nous venons de vous montrer **how to perform OCR on image**, **extract text from image**, puis **detect misspelled words** tout en **getting spelling suggestions** — le tout avec une petite application console C#. L’idée centrale est simple : laissez Aspose.OCR faire le travail lourd de reconnaissance de caractères, puis laissez son correcteur orthographique intégré nettoyer le résultat. À partir d’ici, vous pouvez transformer la démo en un service complet de traitement de documents, l’intégrer à une API web, ou la brancher à un éditeur de bureau. + +Prêt pour l’étape suivante ? Essayez de changer la langue en espagnol, traitez un PDF multi‑pages, ou créez une petite interface WPF qui permet à l’utilisateur de cliquer sur un mot pour accepter une suggestion. Les blocs de construction sont déjà en place — continuez à expérimenter. + +Si vous avez rencontré des problèmes ou avez des idées d’extensions, laissez un commentaire ci‑dessous. Bon codage ! + + +## Que devriez‑vous apprendre ensuite ? + + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/french/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..2857073c8 --- /dev/null +++ b/ocr/french/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: Effectuer la reconnaissance optique de caractères (OCR) sur une image + avec Aspose OCR en C#. Apprenez à charger une image pour l’OCR et à extraire du + texte hindi d’une image hors ligne grâce à un code étape par étape. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: fr +og_description: Effectuez la reconnaissance optique de caractères (OCR) sur une image + avec Aspose OCR en C#. Ce tutoriel montre comment charger une image pour l'OCR et + extraire du texte hindi hors ligne, avec un code exécutable complet. +og_title: Effectuer la reconnaissance optique de caractères sur une image – Guide + Aspose OCR Hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Effectuer la reconnaissance OCR sur une image avec Aspose OCR – Guide en hindi +url: /fr/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Effectuer une OCR sur une image avec Aspose OCR – Guide Hindi + +Vous avez déjà eu besoin d'**effectuer une OCR sur des fichiers image** mais vous ne saviez pas comment extraire les caractères hindi ? Vous n'êtes pas seul — de nombreux développeurs rencontrent ce problème lorsqu'ils essaient de lire des scripts non latins. La bonne nouvelle, c'est qu'Aspose OCR rend cela assez simple, et vous pouvez même le faire entièrement hors ligne. + +Dans ce guide, nous allons **charger l'image pour l'OCR**, indiquer au moteur où se trouvent vos packs de langues hors ligne, puis **extraire le texte hindi de l'image** sans jamais toucher à Internet. À la fin, vous disposerez d'une application console C# prête à l'emploi qui lit un reçu en hindi et affiche le texte dans la console. + +## Ce dont vous avez besoin + +- **.NET 6.0** ou supérieur (le code fonctionne également avec .NET Framework 4.7+) +- **Aspose.OCR for .NET** package NuGet + `dotnet add package Aspose.OCR` +- Un dossier contenant les **ressources de langue hindi hors ligne** (téléchargeables depuis le portail Aspose) +- Un fichier image contenant du texte hindi, par ex. `receipt_hindi.png` + +C’est tout — aucune service externe, aucune clé API, juste du code direct. + +## Effectuer une OCR sur une image – Implémentation étape par étape + +Nous décomposons le processus en sept étapes claires. Chaque étape explique **pourquoi** elle est importante, pas seulement **quoi** taper. + +### Étape 1 : Créer l'instance du moteur OCR + +Le moteur est le cœur d'Aspose OCR. L'instancier vous donne accès à tous les paramètres que vous ajusterez plus tard. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pourquoi ?** +> Sans un `OcrEngine` vous n’avez aucun objet sur lequel appeler `Recognize`. Pensez‑y comme à la « caméra » qui scannera votre image plus tard. + +### Étape 2 : Pointer le moteur vers les ressources hors ligne + +Aspose fournit des packs de langues que vous pouvez stocker localement. Le paramètre `ResourcesFolder` indique au moteur où chercher. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Astuce :** +> Utilisez un chemin absolu pendant le développement, puis passez à un chemin relatif ou à un paramètre de configuration pour la production. + +### Étape 3 : Forcer le mode hors ligne + +Vous vous demandez peut‑être : « Dois‑je vraiment désactiver la recherche en ligne ? » +Si vous travaillez derrière un pare‑feu ou que vous voulez des résultats déterministes, définissez `UseOfflineResources` sur `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip :** +> Laisser ce drapeau à `false` peut amener le moteur à télécharger des données supplémentaires, ce qui ajoute de la latence et peut enfreindre les politiques de sécurité. + +### Étape 4 : Sélectionner le hindi comme langue de reconnaissance + +Ici nous **extraitons le texte hindi de l'image** en indiquant au moteur quelle langue attendre. Cela améliore considérablement la précision. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Pourquoi cela aide :** +> Les moteurs OCR utilisent des modèles de caractères spécifiques à chaque langue. En verrouillant le hindi, vous évitez que le moteur ne devine parmi des dizaines de scripts. + +### Étape 5 : Charger l'image pour l'OCR + +Nous **chargeons maintenant l'image pour l'OCR**. La méthode `OcrImage.FromFile` lit le bitmap dans un format que le moteur comprend. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Piège fréquent :** +> Fournir un chemin avec des barres obliques (`/`) sous Windows fonctionne, mais utiliser `Path.Combine` rend votre code indépendant de la plateforme. + +### Étape 6 : Exécuter la reconnaissance + +Une fois tout configuré, nous **effectuons l'OCR sur l'image** en appelant `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Que se passe‑t‑il ?** +> Le moteur analyse chaque pixel, compare les motifs à la base de données de glyphes hindi, et construit une chaîne de caractères Unicode. + +### Étape 7 : Afficher le texte reconnu + +L’objet résultat possède une propriété `Text` qui contient la chaîne extraite. Nous l’écrivons simplement dans la console. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Sortie attendue :** +> Si `receipt_hindi.png` contient « भुगतान सफल », la console affichera exactement cette ligne, en conservant les diacritiques. + +## Charger l'image pour l'OCR – Préparer la ressource + +Si vous vous demandez s’il est possible de fournir au moteur un flux au lieu d’un fichier, la réponse est oui. Remplacez `OcrImage.FromFile` par : + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Pourquoi utiliser un flux ?** +> Les flux vous permettent de travailler avec des images stockées dans des bases de données, des blobs cloud ou des ressources embarquées — idéal pour des services évolutifs. + +## Extraire le texte hindi de l'image – Gestion des cas particuliers + +1. **Pack de langue manquant** – Si le pack hindi n’est pas trouvé, `Recognize` lève une exception. Enveloppez l’appel dans un try/catch et consignez un message convivial. +2. **Images basse résolution** – La précision de l’OCR chute sous 300 dpi. Pré‑traitez l’image (redimensionnement, netteté) avant de la charger. +3. **Documents multilingues** – Vous pouvez activer plusieurs langues : + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Ces ajustements garantissent que votre routine **effectuer une OCR sur une image** reste robuste en production. + +## Exécuter l'exemple complet + +Enregistrez le fichier suivant sous le nom `Program.cs`, remplacez les chemins factices, puis lancez : + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Lorsque vous exécutez `dotnet run`, vous devriez voir quelque chose comme : + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Si vous obtenez une chaîne vide, vérifiez que le **ResourcesFolder** pointe bien vers le dossier contenant `Hindi.traineddata` et que l’image est suffisamment nette. + +## Conclusion + +Nous avons parcouru comment **effectuer une OCR sur des fichiers image** avec Aspose OCR, en couvrant tout, de **charger l'image pour l'OCR** à **extraire le texte hindi de l'image**, dans un scénario entièrement hors ligne. Le code complet et exécutable ci‑dessus vous offre une base solide, et les astuces sur les flux, la gestion des erreurs et le support multilingue vous aideront à adapter la solution à des projets réels. + +Prêt pour l’étape suivante ? Essayez de changer la langue en **OcrLanguage.Tamil** ou de fournir des images depuis un stockage Azure Blob. Vous pouvez également expérimenter avec les paramètres `ImagePreprocessing` pour améliorer la précision sur des reçus bruyants. + +Des questions ou un problème ? Laissez un commentaire—bon codage ! + +![Perform OCR on image example + + +## Que devriez‑vous apprendre ensuite ? + + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource inclut des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser d’autres fonctionnalités de l’API et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/french/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..ed83f8f15 --- /dev/null +++ b/ocr/french/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-06-03 +description: Effectuez la reconnaissance optique de caractères (OCR) sur un PDF et + convertissez un PDF numérisé en PDF consultable à l’aide d’Aspose.OCR. Apprenez + à reconnaître le texte d’un PDF et à créer des PDF consultables en quelques minutes. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: fr +og_description: Effectuez la reconnaissance OCR sur un PDF et créez instantanément + un PDF consultable. Ce tutoriel montre étape par étape comment reconnaître le texte + d’un PDF à l’aide d’Aspose.OCR. +og_title: Effectuer l'OCR sur PDF – Guide complet C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Effectuer l'OCR sur un PDF avec Aspose.OCR – Guide complet C# +url: /fr/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Effectuer de l'OCR sur un PDF avec Aspose.OCR – Guide complet en C# + +Vous vous êtes déjà demandé **comment réaliser de l'OCR sur des fichiers PDF** sans vous battre avec des dizaines d'outils en ligne de commande ? Vous n'êtes pas seul. Que vous numérisiez des factures, archiviez d'anciens rapports ou que vous ayez simplement besoin d'une version recherchable d'un contrat scanné, transformer un PDF statique en quelque chose de réellement consultable change la donne. + +Dans ce guide, nous allons parcourir **comment créer des fichiers PDF recherchables** à partir de PDFs scannés (et même d'images simples) en utilisant Aspose.OCR pour .NET. À la fin, vous pourrez **reconnaître du texte à partir d'un PDF** avec quelques lignes de code C#, et vous comprendrez le pourquoi de chaque étape afin d'adapter la solution à vos propres projets. + +> **À retenir rapidement :** Le processus complet se résume à trois choses — initialiser le moteur OCR, lui fournir la source (PDF ou image) et enregistrer le PDF recherchable en sortie. Plongeons‑y. + +--- + +## Ce dont vous avez besoin + +Avant de commencer, assurez‑vous d'avoir : + +| Prérequis | Pourquoi c'est important | +|--------------|----------------| +| **.NET 6.0+** (ou .NET Framework 4.6+) | Aspose.OCR cible les runtimes modernes ; les versions plus anciennes peuvent manquer de mises à jour d'API. | +| **Aspose.OCR for .NET** package NuGet | Fournit la classe `OcrEngine` et les utilitaires de gestion PDF. | +| **Une licence Aspose valide** (ou utilisez l'évaluation gratuite) | Sans licence vous tomberez sur la limite d'évaluation de 30 jours et les filigranes. | +| **Un PDF scanné** (ou un fichier image) que vous souhaitez rendre recherchable | C'est le document source pour l'OCR. | +| **Visual Studio 2022** (ou tout éditeur C#) | Facilite le débogage, mais tout IDE fonctionne. | + +Vous pouvez installer la bibliothèque avec la commande NuGet suivante : + +```bash +dotnet add package Aspose.OCR +``` + +> **Astuce pro :** Si vous travaillez sur une pipeline CI, ajoutez le fichier de licence aux artefacts de construction et chargez‑le à l'exécution pour éviter de coder en dur les chemins. + +--- + +## Effectuer de l'OCR sur PDF – Configuration d'Aspose.OCR + +La première chose dont nous avons besoin est une nouvelle instance `OcrEngine`. Pensez‑y comme le cerveau qui lira votre document. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Pourquoi une nouvelle instance à chaque fois ? Le moteur conserve la configuration (comme les paramètres de langue) qui peut différer d'un document à l'autre. L'instancier à chaque exécution garantit une ardoise propre et évite les interférences entre les jobs. + +--- + +## Comment créer un PDF recherchable – Configuration des mots de passe (facultatif) + +Si votre PDF est protégé, vous devez indiquer le mot de passe au moteur avant qu'il ne puisse lire les pages : + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Ignorer cette étape sur un fichier protégé déclenchera une `PdfPasswordException`. Enveloppez toujours cela dans un try‑catch si vous n'êtes pas sûr du statut de protection. + +--- + +## Convertir un PDF scanné en PDF recherchable – Chargement de la source + +Aspose.OCR travaille avec l'abstraction `OcrImage`, qui peut encapsuler des PDFs, TIFF, JPEG, etc. Voici comment charger un PDF scanné en mémoire : + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +En coulisses, `FromFile` analyse chaque page en images raster que le moteur OCR peut traiter. Si vous avez un PDF multi‑pages, le moteur itérera automatiquement sur chaque page. + +--- + +## Reconnaître du texte à partir d'un PDF – Exécution de l'OCR + +Voici le cœur du tutoriel : demander au moteur de reconnaître le texte et de produire un PDF recherchable. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` indique au moteur d'intégrer une couche de texte invisible au-dessus des images scannées d'origine. Le PDF résultant conserve la fidélité visuelle du scan tout en devenant entièrement recherchable — exactement ce qu'il faut pour les audits de conformité. + +--- + +## Convertir une image en PDF recherchable – Enregistrement du résultat + +Enfin, écrivez les octets binaires sur le disque : + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +La propriété `Binary` contient les octets bruts du PDF. Vous pourriez également les transmettre directement à une réponse web si vous construisez une API. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*Texte alternatif de l'image : Diagramme illustrant le flux de conversion OCR pour créer un PDF recherchable.* + +--- + +## Cas limites & conseils pratiques + +### 1. Gros fichiers & gestion de la mémoire +Si vous traitez des PDFs de plus de 100 Mo, envisagez d'utiliser `OcrEngineSettings.MemoryLimit` pour plafonner l'utilisation de la mémoire. De plus, traitez les pages par lots afin d'éviter les `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Prise en charge des langues +Par défaut, Aspose.OCR suppose l'anglais. Pour reconnaître d'autres langues, définissez la propriété `Language` : + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Scénarios multi‑thread +`OcrEngine` n'est **pas** thread‑safe. Si vous avez besoin de traitement parallèle, créez un moteur distinct par thread. + +### 4. Débogage de la précision OCR +Vous pouvez extraire le texte brut de `ocrResult` pour le débogage : + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Si la sortie apparaît illisible, expérimentez avec `PreprocessSettings` (par ex., deskew, despeckle) pour améliorer la qualité. + +### 5. Pièges de licence +Lorsque vous utilisez la version d'évaluation, Aspose ajoute un filigrane au PDF de sortie. Enregistrez votre licence tôt dans l'application : + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Exemple complet – De A à Z + +Voici le programme complet, prêt à être exécuté, qui intègre tous les conseils ci‑dessus. N'hésitez pas à le copier‑coller dans un nouveau projet console. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Sortie attendue :** Après exécution, vous verrez une ligne de console confirmant l'emplacement du fichier. Ouvrez `output.pdf` avec n'importe quel lecteur PDF ; essayez de taper un mot que vous savez présent dans le scan original. Si le texte est mis en surbrillance, vous avez **effectué de l'OCR sur un PDF** et créé un document recherchable. + +--- + +## Questions fréquentes + +**Q : Puis‑je utiliser cela pour convertir une seule image (PNG/JPEG) en PDF recherchable ?** +R : Absolument. Remplacez `OcrImage.FromFile("input.pdf")` par le chemin de votre fichier image. Le moteur rasterisera l'image et intégrera la couche OCR de la même façon. + +**Q : Et si mon PDF contient à la fois des pages scannées et du texte natif ?** +R : Le moteur superposera le texte OCR sur le contenu existant, de sorte que le texte natif reste sélectionnable tandis que les pages scannées deviennent recherchables. + +**Q : Quelle est la précision de l'OCR ?** +R : La précision dépend de la qualité de la source. Des scans propres et haute résolution (>300 dpi) donnent >95 % de précision. Pour les documents bruyants, activez `PreprocessSettings` (deskew, despeckle) avant d'appeler `Recognize`. + +--- + +## Prochaines étapes – Étendre votre boîte à outils OCR + +Maintenant que vous pouvez **reconnaître du texte à partir d'un PDF** et **convertir un PDF scanné en PDF recherchable**, envisagez ces sujets complémentaires : + +- **Traitement par lots** : Parcourez un dossier de PDFs et générez automatiquement des versions recherchables. +- **Extraction de texte** : Utilisez `ocrResult.Text` pour alimenter un index de recherche (par ex., Elasticsearch). +- **Packs de langues personnalisés** : Téléchargez des données linguistiques supplémentaires depuis Aspose pour prendre en charge les scripts asiatiques. +- **Conformité PDF/A** : Combinez Aspose.PDF avec la sortie OCR pour créer des PDFs prêts à l'archivage. + +Chacune de ces extensions repose sur les étapes de base que nous avons couvertes, vous plaçant ainsi en excellente position pour élargir votre solution. + +--- + +## Conclusion + +Nous venons de vous montrer **comment effectuer de l'OCR sur des fichiers PDF** avec Aspose.OCR, transformer des PDFs scannés en PDFs entièrement recherchables, et même couvrir la conversion d'images simples en PDFs recherchables. Le code + +## Que devez‑vous apprendre ensuite ? + +Les tutoriels suivants abordent des sujets étroitement liés qui s'appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets avec des explications pas à pas pour vous aider à maîtriser des fonctionnalités API supplémentaires et explorer des approches d'implémentation alternatives dans vos propres projets. + +- [Reconnaître le texte PDF – Opérations OCR avec Aspose.OCR pour Java](/ocr/english/java/ocr-operations/) +- [Comment faire de l'OCR sur 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 multipage](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/french/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..adab798a2 --- /dev/null +++ b/ocr/french/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Tutoriel OCR de sous-titres vidéo montrant comment extraire des images + d’une vidéo et lire le texte des fichiers vidéo tels que MP4 en utilisant Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: fr +og_description: Apprenez la reconnaissance OCR des sous-titres vidéo avec Aspose.OCR. + Extrayez des images d’une vidéo, lisez le texte d’une vidéo et extrayez le texte + d’un MP4 en quelques minutes. +og_title: OCR de sous-titres vidéo en C# – Guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR de sous-titres vidéo en C# – Guide complet +url: /fr/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR de sous-titres vidéo en C# – Guide complet + +Vous avez déjà eu besoin de **video subtitle ocr** mais vous ne saviez pas par où commencer ? Vous n'êtes pas seul. Que vous numérisiez des enregistrements de cours, extrayiez les sous-titres de vidéos de formation, ou soyez simplement curieux de lire du texte à partir d’une vidéo, ce tutoriel vous montre exactement comment le faire avec C# et Aspose.OCR. + +Dans les prochaines minutes, nous extrairons des images d’une vidéo, exécuterons l’OCR sur ces images, et enfin afficherons le texte des sous-titres image par image. À la fin, vous pourrez **lire du texte à partir d’une vidéo** – y compris les fichiers MP4 – sans chercher d’outils tiers. + +## Ce que vous allez créer + +Nous créerons une petite application console qui : + +1. Décode un MP4 (ou tout format supporté) en images `Bitmap` individuelles. +2. Limite la région OCR à la bande de sous-titres afin que le moteur ne soit pas distrait par l’image entière. +3. Traite chaque image avec le `VideoOcrProcessor` d’Aspose. +4. Affiche le texte des sous-titres reconnu dans la console. + +Pas de fioritures, juste un exemple complet fonctionnel que vous pouvez intégrer dans un projet réel. + +## Prérequis + +- **.NET 6.0** ou ultérieur (le code fonctionne également sur .NET Framework 4.7+). +- **Aspose.OCR for .NET** – installez via NuGet : `Install-Package Aspose.OCR`. +- Un fichier vidéo (MP4 fonctionne très bien). +- Un moyen de décoder les images vidéo – la démo utilise une méthode factice, mais vous pouvez brancher FFmpeg, OpenCV, ou toute bibliothèque qui renvoie des objets `Bitmap`. + +> Conseil pro : Si vous êtes sous Windows, le package `System.Drawing.Common` fonctionne bien pour les `Bitmap`. Sous Linux/macOS, vous aurez besoin de la dépendance native `libgdiplus`. + +## Étape 1 – Extraire des images d’une vidéo + +Le premier obstacle consiste à transformer une image animée en images fixes. La méthode `GetVideoFrames` ci‑dessous est délibérément laissée vide ; remplacez‑la par votre décodeur préféré. Voici un rapide croquis utilisant FFmpeg‑Core (juste pour illustrer la forme des données) : + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Pourquoi c’est important :** Extraire des images fournit à l’engin OCR une image statique avec laquelle travailler, ce qui améliore considérablement la précision comparé à la lecture directe d’un flux vidéo. + +## Étape 2 – Configurer le VideoOcrProcessor + +Maintenant que nous disposons d’une séquence d’objets `Bitmap`, nous pouvons les transmettre à Aspose.OCR. Le `VideoOcrProcessor` nous permet de définir une **Region of Interest (ROI)** – idéal pour les sous-titres qui se trouvent généralement en haut ou en bas de l’image. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Pourquoi limiter la ROI ?** En ignorant le reste de l’image, nous réduisons le bruit, diminuons le temps de traitement et évitons les faux positifs provenant des graphiques d’arrière‑plan. + +## Étape 3 – Exécuter l’OCR sur la séquence d’images + +Avec le processeur prêt, alimenter les images se fait en une seule ligne. La méthode `Process` renvoie un enumerable d’objets `OcrResult`, chacun contenant le texte reconnu pour l’image correspondante. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Que se passe-t-il en coulisses ?** Aspose.OCR normalise en interne chaque bitmap, exécute un reconnaisseur basé sur un réseau de neurones, puis post‑traite la sortie pour améliorer la ponctuation et les sauts de ligne. + +## Étape 4 – Afficher le texte extrait + +Enfin, nous parcourons les résultats et affichons chaque ligne de sous-titre. Vous pourriez également les écrire dans un fichier SRT, une base de données, ou les transmettre à un service de traduction. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Exemple complet fonctionnel + +Assembler le tout donne un programme console autonome : + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Sortie attendue (exemple)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Si l’OCR a du mal avec une image particulière, vous verrez une chaîne vide – c’est le signal pour ajuster la ROI ou augmenter le taux d’extraction d’images. + +## Problèmes courants & comment les résoudre + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| **Caractères indésirables** | Images à basse résolution ou forte compression | Extrayez les images à un débit binaire plus élevé, ou agrandissez le bitmap avant l’OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **Aucun texte retourné** | La ROI ne couvre pas réellement la bande de sous-titres | Vérifiez les coordonnées du rectangle (utilisez un outil de capture d’écran pour mesurer). | +| **Goulot d’étranglement de performance** | Traiter chaque image à 30 fps est excessif | Sous‑échantillonnez à 1‑2 fps pour la plupart des flux de sous-titres ; vous pouvez toujours capturer chaque changement de sous-titre. | +| **FFmpeg introuvable** | `ffmpeg.exe` n’est pas dans le `PATH` | Fournissez le chemin complet dans `ProcessStartInfo.FileName` ou installez FFmpeg globalement. | + +## Étendre la solution + +- **Export to SRT** – concaténez les horodatages avec le texte OCR et écrivez un fichier SubRip. +- **Multi‑language support** – définissez `ocrProcessor.Language = OcrLanguage.Spanish` (ou toute langue supportée). +- **Real‑time processing** – transmettez les images directement depuis un flux en direct au lieu de les lire depuis le disque. + +Toutes ces variantes tournent toujours autour des idées principales d’**extraction d’images d’une vidéo**, **lecture de texte à partir d’une vidéo**, et **extraction de texte d’un mp4**. + +## Conclusion + +Nous venons de parcourir un flux de travail complet d’**video subtitle ocr** en C#. En extrayant des images d’une vidéo, en concentrant l’OCR sur la bande de sous-titres, et en itérant sur les résultats, vous pouvez de manière fiable **read text from video** des fichiers tels que MP4. Le code est prêt à être copié‑collé, et la conception modulaire vous permet de remplacer n’importe quel décodeur d’images que vous préférez. + +Prochaines étapes ? Essayez d’exporter les résultats vers un fichier SRT, expérimentez différentes tailles de ROI, ou alimentez les sous-titres dans une API de traduction pour des légendes multilingues. Le ciel est la limite une fois que vous avez maîtrisé les bases de l’extraction de texte à partir d’une vidéo. + +Bon codage, et que vos sous-titres soient toujours d’une clarté cristalline ! + +## Que devriez‑vous apprendre ensuite ? + +Les tutoriels suivants couvrent des sujets étroitement liés qui s’appuient sur les techniques démontrées dans ce guide. Chaque ressource comprend des exemples de code complets et fonctionnels avec des explications étape par étape pour vous aider à maîtriser des fonctionnalités d’API supplémentaires et explorer des approches d’implémentation alternatives dans vos propres projets. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/german/net/ocr-configuration/_index.md b/ocr/german/net/ocr-configuration/_index.md index 2f940176d..632641242 100644 --- a/ocr/german/net/ocr-configuration/_index.md +++ b/ocr/german/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Entfesseln Sie die Leistungsfähigkeit der OCR-Bilderkennung in .NET mit Aspose. Entfesseln Sie leistungsstarke OCR-Funktionen mit Aspose.OCR für .NET. Extrahieren Sie nahtlos Text aus Bildern. ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) Entfesseln Sie das Potenzial von Aspose.OCR für .NET. Führen Sie mühelos OCR-Bilderkennung mit Listen durch. Steigern Sie die Produktivität und Datenerfassung in Ihren Anwendungen. +### [Aspose OCR-Version in C# abrufen – Komplettanleitung](./get-aspose-ocr-version-in-c-complete-guide/) +Erfahren Sie, wie Sie die installierte Aspose.OCR-Version in C# ermitteln und prüfen. ### Häufige Anwendungsfälle - **Text aus Bildern** von gescannten Rechnungen für die automatisierte Buchhaltung extrahieren. @@ -102,4 +104,4 @@ A: Ja, das `OcrResult`‑Objekt liefert Konfidenzwerte, die Sie programmgesteuer {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/german/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..14fed514b --- /dev/null +++ b/ocr/german/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Abrufen der Aspose OCR‑Version in C# mit einem einfachen Snippet. Erfahren + Sie, wie Sie die Version der Aspose OCR‑Bibliothek mit OcrEngine.GetVersion ermitteln. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: de +og_description: Abrufen der Aspose OCR‑Version in C# schnell. Dieses Tutorial zeigt + genau, wie man die Aspose OCR‑Bibliotheksversion mit OcrEngine GetVersion abruft. +og_title: Aspose OCR-Version in C# erhalten – Vollständiger Leitfaden +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Aspose OCR-Version in C# erhalten – Komplett‑Leitfaden +url: /de/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR-Version in C# abrufen – Vollständige Anleitung + +Haben Sie sich jemals gefragt, wie Sie die **Aspose OCR-Version** aus Ihrem .NET‑Projekt heraus erhalten können? Vielleicht beheben Sie eine Versionsabweichung oder möchten einfach die genaue Bibliotheks‑Build‑Nummer protokollieren, die in der Produktion läuft. Was auch immer der Grund ist, Sie sind hier genau richtig. + +In diesem Tutorial führen wir Sie durch ein kleines, eigenständiges C#‑Programm, das `OcrEngine.GetVersion()` aufruft und das Ergebnis ausgibt. Am Ende wissen Sie nicht nur *wie* Sie die Version abrufen, sondern auch *warum* das Prüfen der Version Ihnen Kopfschmerzen beim Upgrade der **Aspose OCR‑Bibliothek** ersparen kann. + +## Was Sie lernen werden + +- Fügen Sie das Aspose.OCR‑NuGet‑Paket zu einem C#‑Projekt hinzu +- Verwenden Sie die Methode `OcrEngine.GetVersion()` (der **ocrengine getversion** Einstiegspunkt) +- Behandeln Sie mögliche Ausnahmen und überprüfen Sie die Ausgabe +- Erweitern Sie das Snippet für reale Szenarien wie Logging oder bedingte Feature‑Schalter + +Vorkenntnisse im Bereich OCR sind nicht erforderlich – nur ein grundlegendes Verständnis von C# und Visual Studio (oder Ihrer bevorzugten IDE). Lassen Sie uns beginnen. + +--- + +## Schritt 1: Projekt einrichten und die Aspose OCR‑Bibliothek einbinden + +Bevor Sie irgendeine OCR‑bezogene API aufrufen können, muss die **Aspose OCR‑Bibliothek** in Ihrem Projekt referenziert werden. + +1. Öffnen Sie ein Terminal oder die Package‑Manager‑Konsole in Visual Studio. +2. Führen Sie den folgenden Befehl aus, um die neueste stabile Version zu installieren: + +```bash +dotnet add package Aspose.OCR +``` + +> **Profi‑Tipp:** Wenn Sie .NET Framework anstelle von .NET Core anvisieren, verwenden Sie die NuGet‑Package‑Manager‑UI und wählen Sie die Version, die zu Ihrer Laufzeit passt. Das Paket enthält die `OcrEngine`‑Klasse, die wir später verwenden. + +### Warum das wichtig ist + +Wenn Sie das Paket installieren, kann die Assembly‑Version auf der Festplatte von der von der Bibliothek zur Laufzeit gemeldeten Version abweichen. Das Abfragen der Version per Code stellt sicher, dass Sie den genauen Build lesen, den die CLR geladen hat – das ist entscheidend für Debugging und für Compliance‑Audits. + +## Schritt 2: Minimalen Code schreiben, um die **Aspose OCR‑Version** zu erhalten + +Erstellen Sie eine neue Konsolen‑App (`dotnet new console -n OcrVersionDemo`) und ersetzen Sie die Standard‑`Program.cs` durch das Folgende: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Erklärung jedes Teils** + +- `using Aspose.OCR;` bringt den OCR‑Namensraum in den Gültigkeitsbereich, sodass wir `OcrEngine` aufrufen können. +- `OcrEngine.GetVersion()` ist die statische Methode **ocrengine getversion**, die einen String wie `"24.5.7"` zurückgibt. +- Das Einbetten des Aufrufs in einen `try/catch`‑Block schützt Sie vor Laufzeit‑Überraschungen – möglicherweise werden die nativen Binärdateien auf dem Zielsystem nicht gefunden. +- Der interpolierte String `$"Aspose OCR version: {version}"` gibt eine klare, menschenlesbare Zeile aus. + +### Erwartete Ausgabe + +Wenn Sie `dotnet run` im Projektordner ausführen, sollten Sie etwas Ähnliches sehen: + +``` +Aspose OCR version: 24.5.7 +``` + +Falls die Bibliothek nicht geladen werden kann, gibt der Fehlerzweig eine prägnante Meldung aus, die Ihnen hilft, das Problem schnell zu identifizieren. + +## Schritt 3: Überprüfen, ob die Version zu Ihrem NuGet‑Paket passt + +Es ist leicht anzunehmen, dass die installierte NuGet‑Version die zur Laufzeit verwendete ist, aber Umgebungs‑Eigenheiten können dazwischenkommen. Zur doppelten Überprüfung: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Das Ausführen dieses zusätzlichen Snippets gibt etwas Ähnliches aus: + +``` +Assembly file version: 24.5.7.0 +``` + +Wenn die beiden Werte unterschiedlich sind, laden Sie möglicherweise eine ältere DLL aus dem Global Assembly Cache (GAC) oder aus einem vorherigen Build‑Ordner. In diesem Fall sollten Sie Ihre Lösung bereinigen (`dotnet clean`) und neu erstellen. + +## Schritt 4: Versionsprüfung in das Produktions‑Logging einbinden + +Die meisten realen Anwendungen geben nicht nur in die Konsole aus; sie schreiben in eine Log‑Datei oder ein Telemetriesystem. Hier ein kurzes Beispiel mit `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Jetzt erscheint die Version in Ihren strukturierten Logs, sodass Sie später leicht nach `{Version}` filtern können. Dieses Muster ist besonders praktisch, wenn Sie mehrere Micro‑Services haben, die jeweils eine potenziell unterschiedliche OCR‑DLL einbinden. + +## Häufige Fragen & Sonderfälle + +### Was ist, wenn `GetVersion()` einen leeren String zurückgibt? + +Das weist meist auf eine beschädigte Installation oder eine fehlende native Abhängigkeit hin. Installieren Sie das NuGet‑Paket erneut und prüfen Sie, dass die `Aspose.OCR.Native.dll` (oder das entsprechende plattformspezifische Binary) neben Ihrer ausführbaren Datei liegt. + +### Funktioniert die Methode auf .NET Core 2.0? + +Ja, **Aspose OCR** unterstützt .NET Standard 2.0 und höher, sodass jede .NET‑Core‑Version, die diesen Standard implementiert, `OcrEngine.GetVersion()` aufrufen kann. Achten Sie nur darauf, die richtigen Runtime‑Identifiers (`win‑x64`, `linux‑x64` usw.) zu referenzieren, wenn Sie eine eigenständige Anwendung veröffentlichen. + +### Kann ich die Version ohne Lizenzdatei abrufen? + +Absolut. `GetVersion()` erfordert **keine** Lizenz; es gibt lediglich die Build‑Nummer der Bibliothek zurück. Wenn Sie jedoch versuchen, OCR ohne gültige Lizenz auszuführen, erhalten Sie eine Laufzeit‑Exception. Deshalb ist das `try/catch` in unserem Snippet wertvoll – es isoliert die Versionsprüfung vom OCR‑Ausführungsfluss. + +## Vollständiges funktionierendes Beispiel (Copy‑Paste‑bereit) + +Unten finden Sie das gesamte Programm, das Sie in ein neues Konsolen‑Projekt einfügen können. Es enthält den optionalen Logging‑Block, sodass Sie sowohl Konsolenausgabe als auch strukturierte Logs in Aktion sehen. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Führen Sie es mit `dotnet run` aus und Sie sehen zwei Zeilen, die die Version bestätigen, plus eine Debug‑Zeile, wenn Sie `LogLevel.Debug` aktivieren. + +## Fazit + +Wir haben alles behandelt, was Sie benötigen, um die **Aspose OCR‑Version** in einer C#‑Umgebung zu **erhalten** – vom Installieren der **Aspose OCR‑Bibliothek**, über den Aufruf der **ocrengine getversion**‑Methode, das Behandeln von Fehlern bis hin zum Einbetten des Ergebnisses in ein produktionsreifes Logging. Mit diesem Wissen können Sie nun zuverlässig den genauen OCR‑Build Ihrer Anwendung verifizieren, versionsbedingte Fehler vermeiden und Compliance‑Anforderungen ohne großen Aufwand erfüllen. + +Nächste Schritte? Versuchen Sie, diese Versionsprüfung mit einem echten OCR‑Aufruf (`OcrEngine` → `RecognizeImage`) zu kombinieren und sowohl die Version als auch das Erkennungsergebnis zu protokollieren. Sie können auch das Muster **retrieve aspose version** für andere Aspose‑Produkte (PDF, Slides, Cells) erkunden, um Ihre gesamte Suite synchron zu halten. + +Viel Spaß beim Coden und möge Ihre OCR‑Pipeline stets scharf bleiben! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Wie man OCR‑Ergebnisse mit Aspose.OCR für .NET erhält](/ocr/english/net/text-recognition/get-recognition-result/) +- [Bildtext in C# mit Sprachauswahl extrahieren mithilfe von Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Wie man OCR‑Bilder stapelweise mit einer Liste in Aspose.OCR für .NET verarbeitet](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/german/net/ocr-optimization/_index.md index c77c30a65..ffb61443c 100644 --- a/ocr/german/net/ocr-optimization/_index.md +++ b/ocr/german/net/ocr-optimization/_index.md @@ -68,7 +68,9 @@ Entdecken Sie Aspose.OCR für .NET. Steigern Sie die OCR‑Genauigkeit mit Vorve ### [Ergebniskorrektur mit Rechtschreibprüfung in OCR-Bilderkennung](./result-correction-with-spell-checking/) Verbessern Sie die OCR‑Genauigkeit mit Aspose.OCR für .NET. Korrigieren Sie Rechtschreibfehler, passen Sie Wörterbücher an und erreichen Sie mühelos eine fehlerfreie Texterkennung. ### [Mehrseitiges Ergebnis als Dokument speichern in OCR-Bilderkennung](./save-multipage-result-as-document/) -Entfesseln Sie das Potenzial von Aspose.OCR für .NET. Speichern Sie mühelos mehrseitige OCR‑Ergebnisse als Dokumente mit diesem umfassenden Schritt-für-Schritt‑Leitfaden. +Entfesseln Sie das Potenzial von Aspose.OCR für .NET. Speichern Sie mühelos mehrseitige OCR‑Ergebnisse als Dokumente mit diesem umfassenden Schritt‑für‑Schritt‑Leitfaden. +### [Aspose OCR C# Beispiel – GPU aktivieren, Speicherlimit festlegen & TIF‑Bilder verarbeiten](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Erfahren Sie, wie Sie mit Aspose OCR GPU‑Beschleunigung aktivieren, das Speicherlimit setzen und TIF‑Bilder effizient verarbeiten. ## Häufig gestellte Fragen diff --git a/ocr/german/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/german/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..bdfda854a --- /dev/null +++ b/ocr/german/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C#‑Beispiel, das zeigt, wie man das GPU‑Speicherlimit festlegt, + ein Bild für OCR lädt und Text aus TIF‑Dateien erkennt, mit vollständigem Code und + Tipps. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: de +og_description: 'Lernen Sie ein komplettes Aspose OCR C#‑Beispiel: GPU aktivieren, + GPU‑Speicherlimit festlegen, ein Bild für OCR laden und Text aus TIF‑Dateien erkennen. + Vollständiger Code enthalten.' +og_title: Aspose OCR C# Beispiel – GPU‑Beschleunigung, Speicherbegrenzung & TIF‑Verarbeitung +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# Beispiel – GPU aktivieren, Speicherlimit festlegen & TIF‑Bilder + verarbeiten +url: /de/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Beispiel – GPU aktivieren, Speicherlimit festlegen & TIF‑Bilder verarbeiten + +Haben Sie sich jemals gefragt, wie Sie die maximale Leistung aus dem **Aspose OCR C# example**‑Code herausholen können, wenn Sie mit riesigen TIFF‑Scans arbeiten? Sie sind nicht allein. In vielen realen Projekten – denken Sie an die Digitalisierung von Archiven oder das Extrahieren von Daten aus hochauflösenden Quittungen – liegt der Engpass nicht im OCR‑Algorithmus selbst, sondern in der Auslastung der Hardware. + +Hier ist die Sache: Aspose OCR unterstützt GPU‑Beschleunigung, aber Sie müssen ihm genau mitteilen, wie viel Speicher es verwenden darf, den richtigen Bildtyp laden und schließlich den erkannten Text aus einer .tif‑Datei extrahieren. Dieses Tutorial führt Sie durch jeden Schritt, von der Installation des SDK bis zum Anpassen der GPU‑Einstellungen, sodass Sie OCR mit blitzschneller Geschwindigkeit ausführen können, ohne den RAM Ihrer GPU zu überlasten. + +Wir werden außerdem ein paar „Was‑wenn‑“‑Szenarien einstreuen – zum Beispiel die Verarbeitung von mehrseitigen TIFFs oder das Zurückfallen auf die CPU, wenn keine GPU vorhanden ist – sodass Sie am Ende eine robuste Lösung haben und nicht nur ein einzelnes Code‑Snippet. + +## Was Sie benötigen + +Bevor wir beginnen, stellen Sie sicher, dass Sie Folgendes auf Ihrem Rechner haben: + +| Voraussetzung | Warum es wichtig ist | +|--------------|-----------------------| +| **.NET 6 SDK** (or later) | Aspose OCR zielt auf .NET Standard 2.0+ ab, sodass jede aktuelle .NET‑Version funktioniert. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | Die Kernbibliothek, die `OcrEngine`, `GpuSettings` usw. bereitstellt. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Erforderlich für GPU‑Beschleunigung; das SDK prüft zur Laufzeit auf einen kompatiblen Treiber. | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | Ohne ausreichend Speicher kann die Engine stillschweigend auf die CPU zurückfallen. | +| A **high‑resolution TIFF** image you want to process | Aspose OCR kann praktisch jedes Rasterformat lesen, aber TIF ist für Scans üblich. | +| Visual Studio 2022 (or any editor you like) | Zum Erstellen und Debuggen des C#‑Projekts. | + +Wenn einer dieser Punkte fehlt, lässt sich der Code zwar noch kompilieren, aber Sie werden nicht die gewünschten Leistungsgewinne sehen. + +## Schritt 1: Erstellen der Aspose OCR C# Example Engine + +Das Erste in jedem **Aspose OCR C# example** ist das Instanziieren der OCR‑Engine. Betrachten Sie `OcrEngine` als den Regisseur eines Films – sie koordiniert alles von der Bild‑Ladung bis zur Textextraktion. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro‑Tipp:** Wenn Sie planen, viele Bilder nacheinander zu verarbeiten, halten Sie eine einzelne `OcrEngine` am Leben. Das Neuerstellen pro Bild verursacht Overhead, der die OCR‑Zeit bei weitem übersteigen kann. + +## Schritt 2: GPU‑Speicherlimit festlegen (und Beschleunigung aktivieren) + +Jetzt kommt der Teil, der häufig für Verwirrung sorgt: **GPU‑Speicherlimit festlegen**. Standardmäßig versucht Aspose OCR, so viel VRAM wie möglich zu nutzen, was auf einem gemeinsam genutzten Arbeitsplatz andere Anwendungen verhungern lassen kann. Das Objekt `GpuSettings` ermöglicht es Ihnen, die Zuweisung zu begrenzen. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Warum ein Speicherlimit festlegen? + +- **Stabilität:** Verhindert Out‑of‑Memory‑Abstürze bei der Verarbeitung riesiger Bilder. +- **Koexistenz:** Ermöglicht anderen GPU‑intensiven Anwendungen (z. B. TensorFlow‑Modelle), nebeneinander zu laufen. +- **Vorhersagbarkeit:** Macht Leistungstests wiederholbar, da die GPU nicht mit Swapping beginnt. + +Wenn Sie `MemoryLimitMb` weglassen, wird Aspose den Speicher nach eigenem Ermessen zuweisen, was auf einem dedizierten Inferenz‑Server in Ordnung sein kann, aber auf einem Entwickler‑Laptop riskant ist. + +## Schritt 3: Bild für OCR laden + +Das Laden des richtigen Dateiformats ist das nächste entscheidende Element. Die Methode `OcrImage.FromFile` erkennt den Bildtyp automatisch, aber Sie sollten dennoch prüfen, ob die Datei existiert und ob es sich um eine unterstützte TIFF‑Variante handelt (z. B. LZW‑komprimiert oder CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Umgang mit mehrseitigen TIFFs + +Wenn Ihr TIFF mehrere Seiten enthält, liest Aspose OCR standardmäßig nur die erste. Um alle Seiten zu verarbeiten, können Sie über `image.Pages` (verfügbar in neueren SDK‑Versionen) iterieren und jede Seite separat an die Engine übergeben. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Das obige Snippet demonstriert ein **load image for OCR**‑Muster, das sowohl für einseitige als auch für mehrseitige Dateien funktioniert. + +## Schritt 4: Text aus TIF (oder jedem Raster) erkennen + +Jetzt, wo das Bild im Speicher ist, lassen wir Aspose seine Magie wirken. Die Methode `Recognize` gibt ein `OcrResult` zurück, das den Klartext, Konfidenzwerte und sogar Begrenzungs‑Box‑Informationen enthält, falls Sie diese benötigen. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Warum das gut mit TIF funktioniert + +- **Verlustfreie Kompression:** TIFF speichert häufig Rohpixel‑Daten, was der OCR‑Engine die höchste Treue liefert. +- **Mehrere Farbräume:** Aspose kann Graustufen-, RGB‑ oder sogar CMYK‑TIFFs ohne zusätzlichen Konvertierungscode verarbeiten. + +Wenn Sie Sprachpakete anpassen müssen (z. B. Französisch oder Japanisch), setzen Sie `ocrEngine.Settings.Language = "fr"` bevor Sie `Recognize` aufrufen. + +## Schritt 5: Erkannten Text anzeigen + +Abschließend geben wir den Text in der Konsole aus. In einer echten Anwendung könnten Sie ihn in eine Datenbank, eine JSON‑Datei schreiben oder die Zeichenkette in eine nachgelagerte NLP‑Pipeline einspeisen. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Erwartete Ausgabe + +Das Ausführen des Programms auf einem klaren 300 dpi‑Scan einer gedruckten Seite liefert typischerweise etwas wie: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Wenn das Bild unscharf ist oder das GPU‑Speicherlimit zu niedrig ist, können Sie verzerrte Zeichen oder ein abgeschnittenes Ergebnis sehen. Das Senken von `MemoryLimitMb` unter den Speicherbedarf des Bildes (oft ~1 GB für ein 6000×8000‑Pixel‑TIFF) kann dazu führen, dass die Engine automatisch auf die CPU zurückfällt. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das komplette, sofort ausführbare Programm. Kopieren Sie es in ein neues Console‑App‑Projekt, ersetzen Sie `YOUR_DIRECTORY/large_photo.tif` durch den Pfad zu Ihrem eigenen TIFF und drücken Sie **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Schnelle Checkliste + +- ✅ **Aspose OCR C# example** ohne Fehler kompiliert. +- ✅ **GPU aktiviert** (`Enable = true`). +- ✅ **GPU‑Speicherlimit** auf 2048 MB gesetzt. +- ✅ **Bild geladen** aus einer TIF‑Datei. +- ✅ **Text erkannt** und ausgegeben. + +## Häufige Fallstricke & wie man sie vermeidet + +| Symptom | Wahrscheinliche Ursache | Lösung | +|---------|--------------------------|--------| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA‑Runtime nicht installiert oder Versionskonflikt. | Installieren Sie CUDA 11.x (oder 12.x), das zu Ihrem Treiber passt. | +| OCR returns empty string | Bild ist zu dunkel oder DPI < 150. | Vorverarbeiten mit `image.AdjustContrast()` oder auf 300 dpi neu sampeln. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` zu niedrig für das Bild. | Erhöhen Sie das Limit oder teilen Sie das Bild in Kacheln mittels `image.Crop`. | +| `Unsupported image format` error | TIFF verwendet eine exotische Kompression (z. B. JPEG‑2000). | Konvertieren Sie das TIFF mit ImageMagick in ein unterstütztes Format vor dem OCR. | + +## Demo erweitern + +Jetzt, da Sie ein solides **aspose ocr c# example** haben, möchten Sie vielleicht Folgendes erkunden: + +- **Batch‑Verarbeitung:** Durchlaufen Sie einen Ordner mit TIFs und schreiben Sie jedes Ergebnis in eine `.txt`‑Datei. +- **Sprachpakete:** `ocrEngine.Settings.Language = "es"` für Spanisch oder laden Sie benutzerdefinierte Wörterbücher. +- **Begrenzungs‑Boxen:** Verwenden Sie `ocrResult.Regions`, um die Koordinaten jedes Wortes zu erhalten – praktisch für Redaktions‑Tools. +- **CPU‑Fallback:** Packen Sie den GPU‑Block in ein try/catch; bei einem Fehler setzen Sie `ocrEngine.Settings.Gpu.Enable = false` und versuchen es erneut. + +These extensions keep the core pattern intact while adding value for specific use‑ + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/german/net/skew-angle-calculation/_index.md b/ocr/german/net/skew-angle-calculation/_index.md index 4dd291814..057d47712 100644 --- a/ocr/german/net/skew-angle-calculation/_index.md +++ b/ocr/german/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Entdecken Sie Aspose.OCR für .NET, eine leistungsstarke OCR-Lösung für die ge Nutzen Sie die Leistungsfähigkeit von Aspose.OCR für .NET, einer robusten Lösung für die Bilderkennung. Erfahren Sie, wie Sie Schräglaufwinkel mühelos berechnen. ### [Berechnen Sie den Schrägwinkel aus URI in der OCR-Bilderkennung](./calculate-skew-angle-from-uri/) Entdecken Sie Aspose.OCR für .NET, um Schräglaufwinkel bei der OCR-Bilderkennung mühelos zu berechnen. Verbessern Sie Ihre Projekte mit Präzision und Effizienz. +### [OCR-Dokument mit Drehung – Automatische Schrägkorrektur und Rotationsfix in C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Erfahren Sie, wie Sie mit Aspose.OCR für .NET gedrehte Dokumente automatisch begradigen und rotieren. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/german/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..9116e2eb6 --- /dev/null +++ b/ocr/german/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: OCR‑Tutorial für gedrehte Dokumente, das zeigt, wie man Schräglage automatisch + korrigiert und die Drehung mit Aspose OCR in C# erkennt. Lernen Sie Schritt für + Schritt mit vollständigem Code. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: de +og_description: Das OCR‑Tutorial für gedrehte Dokumente zeigt Ihnen, wie Sie Schräglage + automatisch korrigieren und die Drehung mit Aspose OCR in C# erkennen können. Folgen + Sie der vollständigen Anleitung. +og_title: OCR‑Tutorial für gedrehte Dokumente – automatische Schräglagen‑ und Drehungs­korrektur + in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR-Dokument mit Rotation – Automatische Schräglagenkorrektur und Rotationsfix + in C# +url: /de/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Rotated Document Tutorial – Vollständige Anleitung für C#‑Entwickler + +Ever stumbled upon an **ocr rotated document tutorial** when a scanned form came in sideways or slanted? You’re not alone. Those wonky images can ruin a clean text extraction, but the good news is that Aspose OCR can straighten things out for you automatically. + +In this step‑by‑step guide we’ll spin up an `OcrEngine`, turn on **automatic skew correction** and **auto detect rotation**, run the engine against a rotated image, and print the clean text. By the end you’ll know exactly why each setting matters, how to tweak it for edge cases, and you’ll have a ready‑to‑run C# program. + +## Was Sie lernen werden + +* Wie man **Aspose OCR** in einem .NET‑Projekt installiert und referenziert. +* Warum das Aktivieren von `AutoCorrectSkew` und `AutoDetectRotation` der Schlüssel zu einem zuverlässigen **ocr rotated document tutorial** ist. +* Wie man jedes Bild (JPG, PNG, TIFF) lädt und die Engine die schwere Arbeit erledigen lässt. +* Tipps zum Umgang mit mehrseitigen PDFs, niedrigauflösenden Scans und benutzerdefinierten Sprachpaketen. + +> **Voraussetzungen:** Visual Studio 2022 (oder jede C#‑IDE), .NET 6+ Runtime und eine gültige Aspose OCR‑Lizenz (oder die kostenlose Testversion). Keine vorherige OCR‑Erfahrung erforderlich. + +--- + +## Schritt 1 – Aspose OCR installieren und das Projekt einrichten + +Zuerst das Wichtigste. Holen Sie sich das NuGet‑Paket: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro‑Tipp:** Wenn Sie eine Testlizenz verwenden, legen Sie die Datei `Aspose.OCR.lic` im selben Ordner wie Ihre ausführbare Datei ab oder registrieren Sie sie programmgesteuert mit `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Erstellen Sie eine neue Konsolenanwendung: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Jetzt haben Sie eine saubere Basis für unser **ocr rotated document tutorial**. + +## Schritt 2 – Die OCR‑Engine initialisieren + +Die Engine ist das Herzstück des Prozesses. Denken Sie an sie wie an ein Schweizer Taschenmesser für die Textextraktion; Sie müssen ihr nur mitteilen, welche Tricks aktiviert werden sollen. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Warum diese Einstellungen?** +* `AutoCorrectSkew` analysiert die Grundlinie der Zeichen und dreht das Bild gerade genug, um die Zeilen horizontal zu machen. +* `AutoDetectRotation` prüft die Gesamtausrichtung (0°, 90°, 180°, 270°) und dreht die Seite, wenn sie verkehrt herum ist. Ohne diese würde die Engine “pɹᴉʍ” statt “word” lesen. + +## Schritt 3 – Laden Sie das Bild, das Sie verarbeiten möchten + +Aspose OCR funktioniert mit jedem gängigen Rasterformat. Ersetzen Sie den Platzhalterpfad durch den tatsächlichen Speicherort Ihres gedrehten Formulars. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Randfall:** Wenn Sie ein mehrseitiges TIFF erhalten, verwenden Sie `OcrImage.FromMultiPageTiff(filePath)` und iterieren Sie über `image.Pages`. + +## Schritt 4 – Die Erkennung ausführen + +Jetzt führt die Engine die Magie aus. Sie richtet zuerst das Bild gerade (dank unserer Schräg‑/Rotations‑Flags) und extrahiert dann die Zeichen. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Wenn Sie Sprachunterstützung über Englisch hinaus benötigen, setzen Sie sie, bevor Sie `Recognize` aufrufen: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Schritt 5 – Den erkannten Text ausgeben + +Zum Schluss geben Sie den bereinigten Text in der Konsole aus – oder leiten ihn in eine Datei, eine Datenbank usw. weiter, je nach Ihrem Workflow. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Erwartete Ausgabe** (angenommen, das Beispielbild enthält “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Beachten Sie, dass der Text korrekt erscheint, obwohl das Quellbild um 90° gedreht und leicht schief war. + +--- + +## Häufige Stolperfallen behandeln + +| Problem | Warum es passiert | Lösung | +|------|----------------|-----| +| **Leere Ausgabe** | Schrägkorrektur deaktiviert oder Bild zu dunkel. | Aktivieren Sie `AutoCorrectSkew` (bereits aktiviert) und erhöhen Sie den Bildkontrast über `image.AdjustContrast(1.2)`. | +| **Fehlerhafte Zeichen** | Falsche Spracheinstellung. | Setzen Sie `ocrEngine.Settings.Language` auf die Sprache des Dokuments. | +| **Leistungsverzögerung bei großen PDFs** | Die Engine verarbeitet jede Seite nacheinander. | Verwenden Sie `Parallel.ForEach` auf `image.Pages`, um Mehrkern‑CPUs zu nutzen. | +| **Lizenzausnahme** | Testversion abgelaufen. | Erwerben Sie eine permanente Lizenz oder bleiben Sie innerhalb der Testlimits (5 Seiten pro Durchlauf). | + +## Pro‑Tipps für ein robustes OCR Rotated Document Tutorial + +* **Batch‑Verarbeitung:** Packen Sie den gesamten Ablauf in eine Methode, die einen Ordnerpfad akzeptiert, über jedes Bild iteriert und jedes Ergebnis in eine `.txt`‑Datei schreibt. +* **Vorverarbeitung:** Manchmal profitiert ein verrauschter Scan von `image.Denoise()` vor der Erkennung. +* **Nachverarbeitung:** Verwenden Sie reguläre Ausdrücke, um häufige OCR‑Fehlinterpretationen zu bereinigen, z. B. ersetzen Sie “0” durch “O”, nur wenn es von Buchstaben umgeben ist. +* **Logging:** Aspose OCR stellt `ocrEngine.Logger` bereit – verbinden Sie es mit einem Dateilogger, um Warnungen über niedrige Vertrauenswerte zu erfassen. + +## Vollständiger, sofort ausführbarer Code + +Speichern Sie das Folgende als `Program.cs` in Ihrem Konsolenprojekt. Es enthält alle Schritte, Kommentare und einen kleinen Helfer für die Batch‑Verarbeitung. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Führen Sie es aus: + +```bash +dotnet run +``` + +Sie sollten den bereinigten Text in der Konsole sehen, was beweist, dass unser **ocr rotated document tutorial** End‑zu‑End funktioniert. + +## Fazit + +Sie haben jetzt ein vollständiges **ocr rotated document tutorial**, das Schräglagen automatisch korrigiert, Rotationen erkennt und sauberen Text mit Aspose OCR in C# extrahiert. Die wichtigste Erkenntnis? Das Aktivieren von `AutoCorrectSkew` **und** `AutoDetectRotation` verwandelt einen hoffnungslos schiefen Scan in perfekt lesbare Ausgabe mit nur wenigen Codezeilen. + +Ab hier können Sie zu Batch‑Jobs erweitern, Sprachpakete integrieren oder die Ergebnisse in nachgelagerte Analyse‑Pipelines einspeisen. Möchten Sie **automatic skew correction** weiter erkunden? Schauen Sie sich Asposes Bildvorverarbeitungs‑API an oder experimentieren Sie mit benutzerdefinierten Schwellenwerten für verrauschte Scans. + +Haben Sie Fragen zum Umgang mit PDFs, mehrseitigen TIFFs oder zur Integration mit Azure Functions? Hinterlassen Sie einen Kommentar und happy coding! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige funktionierende Codebeispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, zusätzliche API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [ocr-Dokumentmodus – Erkennungsbereiche-Modus in OCR-Bilderkennung](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Bildtext in C# extrahieren mit Sprachauswahl mittels Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optische Zeichenerkennung](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/german/net/text-recognition/_index.md index 164bd821b..fec95674f 100644 --- a/ocr/german/net/text-recognition/_index.md +++ b/ocr/german/net/text-recognition/_index.md @@ -27,7 +27,7 @@ Entdecken Sie die Funktionen von Aspose.OCR für .NET und verändern Sie die Art ## Erhalten Sie das Ergebnis als JSON in der OCR-Bilderkennung -Nutzen Sie das volle Potenzial von Aspose.OCR für .NET, indem Sie lernen, wie Sie mühelos OCR-Ergebnisse im JSON-Format erhalten. Diese Schritt-für-Schritt-Anleitung gewährleistet einen reibungslosen Weg zur Verbesserung Ihrer Bilderkennungsfähigkeiten. Steigern Sie die Effizienz Ihrer Anwendung mit den robusten Funktionen und der branchenführenden Technologie von Aspose.OCR. +Nutzen Sie das volle Potenzial von Aspose.OCR für .NET, indem Sie lernen, wie Sie mühelos OCR-Ergebnisse im JSON-Format erhalten. Diese Schritt‑für‑Schritt‑Anleitung gewährleistet einen reibungslosen Weg zur Verbesserung Ihrer Bilderkennungsfähigkeiten. Steigern Sie die Effizienz Ihrer Anwendung mit den robusten Funktionen und der branchenführenden Technologie von Aspose.OCR. ## Modus „OCR-Erkennungsbereiche“ in der OCR-Bilderkennung @@ -44,20 +44,31 @@ Navigieren Sie mit Aspose.OCR für .NET durch die Komplexität der Tabellenerken Sind Sie bereit, Ihre .NET-Anwendungen zu revolutionieren? Tauchen Sie ein in unsere Tutorials zur Texterkennung und nutzen Sie die Leistungsfähigkeit von Aspose.OCR für eine genaue und effiziente Texterkennung in Bildern. Laden Sie es jetzt herunter und begeben Sie sich auf eine Reise mit erweiterten OCR-Funktionen. ## Tutorials zur Texterkennung ### [Erhalten Sie Auswahlmöglichkeiten für erkannte Zeichen bei der OCR-Bilderkennung](./get-choices-for-recognized-characters/) -Erweitern Sie Ihre .NET-Anwendungen mit Aspose.OCR für eine genaue Zeichenerkennung. Befolgen Sie unsere Schritt-für-Schritt-Anleitung, um Auswahlmöglichkeiten für erkannte Zeichen bei der Bilderkennung abzurufen. +Erweitern Sie Ihre .NET-Anwendungen mit Aspose.OCR für eine genaue Zeichenerkennung. Befolgen Sie unsere Schritt‑für‑Schritt‑Anleitung, um Auswahlmöglichkeiten für erkannte Zeichen bei der Bilderkennung abzurufen. ### [Erhalten Sie das Erkennungsergebnis bei der OCR-Bilderkennung](./get-recognition-result/) Entdecken Sie Aspose.OCR für .NET, eine leistungsstarke OCR-Lösung für die nahtlose Texterkennung in Bildern. ### [Erhalten Sie das Ergebnis als JSON in der OCR-Bilderkennung](./get-result-as-json/) -Nutzen Sie die Leistungsfähigkeit von Aspose.OCR für .NET. Erfahren Sie, wie Sie mühelos OCR-Ergebnisse im JSON-Format erhalten. Verbessern Sie Ihre Bilderkennung mit dieser Schritt-für-Schritt-Anleitung. +Nutzen Sie die Leistungsfähigkeit von Aspose.OCR für .NET. Erfahren Sie, wie Sie mühelos OCR-Ergebnisse im JSON-Format erhalten. Verbessern Sie Ihre Bilderkennung mit dieser Schritt‑für‑Schritt‑Anleitung. ### [Modus „OCR-Erkennungsbereiche“ in der OCR-Bilderkennung](./ocr-detect-areas-mode/) Erweitern Sie Ihre .NET-Anwendungen mit Aspose.OCR für eine effiziente Bildtexterkennung. Entdecken Sie den OCR-Erkennungsmodus für präzise Ergebnisse. ### [Erkennen Sie PDF mit der OCR-Bilderkennung](./recognize-pdf/) Nutzen Sie das Potenzial von OCR in .NET mit Aspose.OCR. Extrahieren Sie mühelos Text aus PDFs. Laden Sie es jetzt herunter und genießen Sie eine nahtlose Integration. +### [OCR auf PDF mit Aspose OCR ausführen – Vollständiger C#‑Leitfaden](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Erfahren Sie, wie Sie mit Aspose OCR PDFs in C# verarbeiten und Text extrahieren – Schritt‑für‑Schritt‑Anleitung für Entwickler. ### [Tabelle in der OCR-Bilderkennung erkennen](./recognize-table/) Nutzen Sie das Potenzial von Aspose.OCR für .NET mit unserem umfassenden Leitfaden zum Erkennen von Tabellen in der OCR-Bilderkennung. +### [OCR auf Bild mit Aspose OCR ausführen – Hindi‑Leitfaden](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Erfahren Sie, wie Sie mit Aspose OCR Text aus Bildern extrahieren und dabei die Hindi‑Sprache unterstützen. +### [Wie Sie Aspose verwenden: Bild mit OCR in HTML konvertieren](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Erfahren Sie, wie Sie mit Aspose OCR ein Bild in HTML umwandeln und den Text extrahieren. +### [OCR auf Bild ausführen und Rechtschreibfehler in C# erkennen](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Erfahren Sie, wie Sie mit Aspose OCR Bilder verarbeiten und dabei falsch geschriebene Wörter in C# erkennen. +### [Video‑Untertitel‑OCR in C# – Vollständiger Leitfaden](./video-subtitle-ocr-in-c-complete-guide/) +Erfahren Sie, wie Sie mit Aspose.OCR Untertitel aus Videos extrahieren und in C# verarbeiten – Schritt‑für‑Schritt‑Anleitung. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/german/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..ba77c7207 --- /dev/null +++ b/ocr/german/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-06-03 +description: Wie man Aspose verwendet, um ein Bild in HTML zu konvertieren und Text + aus einem Bild in C# zu extrahieren. Lernen Sie, schnell HTML aus einem Bild zu + erzeugen und ein Bild per OCR in HTML zu konvertieren. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: de +og_description: Wie man Aspose verwendet, um ein Bild in HTML zu konvertieren, Text + aus dem Bild zu extrahieren und HTML aus dem Bild mit OCR in C# zu erzeugen. Folgen + Sie diesem vollständigen Leitfaden. +og_title: 'Wie man Aspose verwendet: Bild in HTML mit OCR konvertieren' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Wie man Aspose verwendet: Bild in HTML mit OCR konvertieren' +url: /de/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man Aspose verwendet: Bild mit OCR in HTML konvertieren + +Haben Sie sich schon einmal gefragt, **wie man Aspose** nutzt, um ein gescanntes Bild in sauberes HTML zu verwandeln? Vielleicht haben Sie eine Magazinseite, einen Kassenbon oder eine handschriftliche Notiz und benötigen den Text sowie das Layout für die Web‑Veröffentlichung erhalten. Die gute Nachricht: Sie müssen keinen eigenen Parser schreiben oder sich mit Low‑Level‑Bildverarbeitung herumschlagen – Aspose.OCR übernimmt die schwere Arbeit für Sie. + +In diesem Tutorial gehen wir Schritt für Schritt durch ein **vollständiges, ausführbares Beispiel**, das zeigt, wie man **ein Bild in HTML konvertiert**, **Text aus einem Bild extrahiert** und **HTML aus einem Bild erzeugt** mit der Aspose OCR‑Bibliothek in C#. Am Ende haben Sie eine kleine Konsolen‑App, die eine HTML‑Datei mit dem ursprünglichen Seitenlayout erzeugt, bereit, in jede Website eingebunden zu werden. + +## Voraussetzungen + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes auf Ihrem Rechner haben: + +- **.NET 6.0 SDK** oder neuer (der Code funktioniert sowohl mit .NET Core als auch mit .NET Framework). +- **Visual Studio 2022** (oder ein beliebiger anderer Editor). +- **Aspose.OCR für .NET** – Installation via NuGet: `dotnet add package Aspose.OCR`. +- Eine Bilddatei (JPEG/PNG), die Sie umwandeln möchten, z. B. `magazine_page.jpg`. + +Keine zusätzlichen Konfigurationsdateien sind nötig; die Bibliothek liefert alles, was für OCR und HTML‑Layout‑Generierung erforderlich ist. + +## Schritt 1: Projekt einrichten und Aspose.OCR hinzufügen + +Erstellen Sie zunächst ein neues Konsolen‑Projekt und binden Sie das Aspose‑OCR‑Paket ein. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro‑Tipp:** Wenn Sie Visual Studio verwenden, klicken Sie einfach mit der rechten Maustaste auf das Projekt → *NuGet‑Pakete verwalten* → nach **Aspose.OCR** suchen und installieren. Dieser Schritt stellt sicher, dass Sie **ocr image to html** ohne fehlende Verweise ausführen können. + +## Schritt 2: OCR‑Engine initialisieren + +Der Kern des Prozesses ist die Klasse `OcrEngine`. Stellen Sie sich sie als das Gehirn vor, das das Bild liest und entscheidet, wie das Ergebnis ausgegeben wird. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Hier instanziieren wir `OcrEngine`. Für die kostenlose Version müssen Sie keine Zugangsdaten übergeben; die Bibliothek nutzt ihre eingebauten Erkennungs‑Modelle. + +## Schritt 3: Quellbild laden + +Als Nächstes geben Sie der Engine die Datei an, die Sie verarbeiten möchten. Aspose stellt die praktische Methode `OcrImage.FromFile` bereit, die die meisten Bildformate unterstützt. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Ersetzen Sie `YOUR_DIRECTORY` durch den absoluten oder relativen Pfad, in dem Ihr Bild liegt. Befindet sich das Bild im selben Ordner wie die ausführbare Datei, können Sie einfach `"magazine_page.jpg"` verwenden. + +## Schritt 4: Erkennen und HTML mit Layout anfordern + +Dies ist das Herzstück des Tutorials. Durch die Angabe von `OutputFormat.HtmlWithLayout` teilen wir Aspose mit, **HTML aus dem Bild zu erzeugen**, wobei die ursprüngliche Positionierung von Textblöcken, Bildern und Tabellen erhalten bleibt. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Die Eigenschaft `recognitionResult.Text` enthält nun ein vollständiges HTML‑Dokument. Wenn Sie nur reinen Text benötigen, könnten Sie `OutputFormat.Text` verwenden, aber wir konzentrieren uns auf **convert image to html** mit Layout‑Treue. + +## Schritt 5: HTML‑Datei speichern + +Abschließend schreiben wir die HTML‑Zeichenkette auf die Festplatte. Damit erhalten Sie eine sofort einsetzbare Datei, die Sie in jedem Browser öffnen können. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Beim Ausführen des Programms entsteht `magazine.html`. Öffnen Sie diese Datei, und Sie sehen den Text der Originalseite exakt an den Stellen positioniert, an denen er im Quellbild erschien – ideal für Archivierung oder Web‑Publishing. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das **komplette, copy‑paste‑bereite** Programm. Es wurden keine Teile ausgelassen, sodass Sie es sofort nach dem Anpassen der Pfade kompilieren und ausführen können. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Erwartete Ausgabe + +Wenn Sie `magazine.html` in einem Browser öffnen, sollte etwa Folgendes erscheinen (vereinfacht zur Veranschaulichung): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Die genauen `style`‑Attribute unterscheiden sich je nach Ausgangsbild, aber die Struktur garantiert, dass **extract text from image** und **generate html from image** in einem einzigen, nahtlosen Schritt erfolgen. + +## Häufige Fragen & Sonderfälle + +### Was, wenn das Bild eine niedrige Auflösung hat? + +Aspose.OCR arbeitet am besten mit Bildern, die mindestens **300 DPI** besitzen. Ist Ihre Datei unscharf, versuchen Sie, sie vorher mit einer Bild‑Verbesserungs‑Bibliothek (z. B. ImageSharp) aufzubereiten, bevor Sie sie an die OCR‑Engine übergeben. Schlechte Qualität kann sowohl die **extract text from image**‑Genauigkeit als auch die Treue des erzeugten HTML‑Layouts beeinträchtigen. + +### Kann ich die Sprache der OCR festlegen? + +Ja. Setzen Sie die Eigenschaft `Language` der `OcrEngine`, bevor Sie `Recognize` aufrufen: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Damit verbessern Sie die Erkennung, wenn Sie nicht‑englische Zeichen verarbeiten. + +### Wie erhalte ich reinen Text statt HTML? + +Wenn Sie nur die Zeichenkette benötigen, ersetzen Sie `OutputFormat.HtmlWithLayout` durch `OutputFormat.Text`. Dann enthält `recognitionResult.Text` ausschließlich die extrahierten Zeichen. + +### Gibt es eine Möglichkeit, Bilder in das erzeugte HTML einzubetten? + +Aspose.OCR kann das Originalbild als Base‑64‑Data‑URI einbetten, wenn Sie `OutputFormat.HtmlWithLayoutAndImages` verwenden. Das ist praktisch, wenn Sie eine einzelne HTML‑Datei ohne externe Ressourcen wünschen. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Wie gehe ich mit großen Stapeln um? + +Für die Stapelverarbeitung packen Sie die Logik in eine `foreach`‑Schleife über eine Liste von Dateipfaden. Die Wiederverwendung derselben `OcrEngine`‑Instanz reduziert den Overhead und beschleunigt die **convert image to html**‑Pipeline. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tipps für produktionsreifen Code + +- **Ressourcen freigeben**: Sowohl `OcrEngine` als auch `OcrImage` implementieren `IDisposable`. Verwenden Sie `using`‑Blöcke, um nativen Speicher zügig freizugeben. +- **Fehlerbehandlung**: Fangen Sie `IOException` für dateibezogene Probleme und `OcrException` für Erkennungsfehler ab. +- **Performance**: Bei vielen Bildern sollten Sie **Parallelisierung** (`Parallel.ForEach`) in Betracht ziehen, aber achten Sie auf die CPU‑Auslastung – OCR ist CPU‑intensiv. +- **Logging**: Integrieren Sie einen Logger (z. B. Serilog), um OCR‑Vertrauenswerte (`recognitionResult.Confidence`) für Qualitäts‑Monitoring zu erfassen. + +## Fazit + +Wir haben gezeigt, **wie man Aspose** nutzt, um **ein Bild in HTML zu konvertieren**, **Text aus einem Bild zu extrahieren** und **HTML aus einem Bild zu erzeugen** in wenigen klaren Schritten. Der vollständige Code‑Beispiel demonstriert, wie man **ocr image to html** mit Layout‑Erhaltung umsetzt – eine solide Basis für jedes Dokument‑Digitalisierungs‑Projekt. + +Von hier aus können Sie: + +- Verschiedene `OutputFormat`‑Optionen ausprobieren, um Ihre Anforderungen zu erfüllen. +- Die HTML‑Ausgabe mit einem CSS‑Framework für responsives Design kombinieren. +- Den extrahierten Text in einen Such‑Index oder eine Machine‑Learning‑Pipeline einspeisen. + +Probieren Sie es aus, passen Sie die Einstellungen an und sehen Sie, wie mühelos Aspose Bilder in web‑fertigen Content verwandelt. Wenn Sie auf Probleme stoßen, hinterlassen Sie einen Kommentar – happy coding! + +![Diagramm, das die OCR‑Pipeline von Bild zu HTML‑Layout – wie man Aspose verwendet](/images/ocr-pipeline.png "how to use aspose") + +--- + + +## Was sollten Sie als Nächstes lernen? + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/german/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..913328000 --- /dev/null +++ b/ocr/german/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-03 +description: Führen Sie OCR auf einem Bild durch und extrahieren Sie Text aus dem + Bild mit Aspose.OCR. Erfahren Sie, wie Sie falsch geschriebene Wörter erkennen und + Rechtschreibvorschläge erhalten – alles in einer einzigen C#‑Demo. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: de +og_description: Führen Sie OCR auf einem Bild aus, um den Text zu extrahieren, erkennen + Sie anschließend falsch geschriebene Wörter und erhalten Sie Rechtschreibvorschläge + mit Aspose.OCR in C#. +og_title: OCR auf Bild ausführen und Rechtschreibfehler in C# erkennen +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: OCR auf Bild ausführen und Rechtschreibfehler in C# erkennen +url: /de/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR auf Bild ausführen und Rechtschreibfehler in C# erkennen + +Haben Sie sich jemals gefragt, wie man **perform OCR on image** Dateien erledigt, ohne sich die Haare zu raufen? Sie sind nicht allein. Ob Sie alte Briefe digitalisieren, Belege scannen oder einen intelligenten Dokumenten‑Workflow aufbauen, sauberen Text aus Bildern zu extrahieren ist die erste Hürde. Die gute Nachricht? Mit Aspose.OCR können Sie in wenigen Minuten eine Lösung erstellen, und das Besondere ist, dass Sie gleichzeitig **detect misspelled words** und **get spelling suggestions** durchführen können. + +In diesem Tutorial führen wir Sie durch eine vollständige, sofort ausführbare C#‑Konsolen‑App, die **extracts text from image**, einen englischen Rechtschreibprüfer ausführt und jeden Fehler mit praktischen Korrekturvorschlägen ausgibt. Am Ende wissen Sie genau **how to extract text**, wie Sie die Spell‑Check‑API anbinden und wie die erwartete Konsolenausgabe aussieht. + +## Was Sie bauen werden + +- Laden Sie ein Bitmap (oder PNG), das typografische Fehler enthält. +- Führen Sie Aspose.OCR aus, um **perform OCR on image** zu erledigen und Roh‑String‑Daten zu erhalten. +- Initialisieren Sie den integrierten englischen Rechtschreibprüfer. +- **Detect misspelled words** und **get spelling suggestions** für jedes Wort. +- Geben Sie einen übersichtlichen Bericht in der Konsole aus. + +Keine externen Dienste, keine umständlichen HTTP‑Aufrufe — nur ein einzelnes NuGet‑Paket und ein paar Code‑Zeilen. + +## Voraussetzungen + +- .NET 6.0 SDK oder neuer (der Code funktioniert auch mit .NET Framework 4.7+). +- Visual Studio 2022 (oder ein beliebiger Editor Ihrer Wahl). +- Aspose.OCR für .NET NuGet‑Paket (`Aspose.OCR`). +- Eine Bilddatei (`letter_with_typos.png`), die Sie im Projekt referenzieren können. + +Wenn Sie Aspose noch nie verwendet haben, keine Sorge — die Installation des Pakets ist so einfach wie: + +```bash +dotnet add package Aspose.OCR +``` + +Jetzt tauchen wir in die Implementierung ein. + +## Schritt 1: Projekt einrichten und Aspose.OCR installieren + +Erstellen Sie ein neues Konsolen‑Projekt und binden Sie die OCR‑Bibliothek ein: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Nach Abschluss des Restores öffnen Sie `Program.cs`. Wir ersetzen den Standardinhalt später durch den vollständigen Demo‑Code, aber zunächst ein kurzer Überblick, warum jeder Namespace wichtig ist. + +- `Aspose.OCR` – Kern‑OCR‑Engine und Bildverarbeitung. +- `Aspose.OCR.SpellCheck` – Rechtschreib‑Utilities, die mit der Bibliothek geliefert werden. +- `System` – Standard‑.NET‑Basisklassen (z. B. `Console`). + +## Schritt 2: Bild laden und OCR auf Bild ausführen + +Die eigentliche Arbeit beginnt damit, das Bild an die OCR‑Engine zu übergeben. Aspose.OCR liest viele Formate (PNG, JPEG, TIFF). Hier ist das Snippet, das die schwere Arbeit übernimmt: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Why this matters:** `OcrImage.FromFile` abstrahiert die Pixel‑Details, während `OcrEngine.Recognize` das trainierte neuronale Modell ausführt, das visuelle Glyphen in Unicode‑Zeichen übersetzt. Die Eigenschaft `ocrResult.Text` enthält nun den Roh‑String — genau das, was Sie benötigen, um **extracts text from image** zu erhalten. +> **Pro tip:** Wenn Ihr Bild mehrere Sprachen enthält, können Sie vor dem Aufruf von `Recognize` `ocrEngine.Language = OcrLanguage.Multilingual;` setzen. + +## Schritt 3: Englischen Rechtschreib‑Checker initialisieren + +Aspose.OCR liefert einen integrierten Rechtschreibprüfer, der Englisch sofort versteht. Die Initialisierung erfolgt in einer Zeile: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Why this step is crucial:** Die OCR‑Ausgabe kann falsch erkannte Zeichen (z. B. „l“ vs. „1“) oder echte Tippfehler aus dem Quell‑Dokument enthalten. Der Rechtschreibprüfer scannt den String, findet verdächtige Tokens und schlägt Alternativen vor. + +## Schritt 4: Rechtschreibfehler erkennen und Rechtschreibungsvorschläge erhalten + +Jetzt übergeben wir den OCR‑Text an den Prüfer: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` ist eine Sammlung, in der jeder Eintrag das fehlerhafte Wort und ein Array möglicher Korrekturen enthält. + +## Schritt 5: Ergebnisse ausgeben + +Abschließend iterieren wir über die Sammlung und geben einen menschenlesbaren Bericht aus: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Erwartete Konsolenausgabe + +Angenommen, `letter_with_typos.png` enthält den Satz: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Das Ausführen der Demo erzeugt etwa Folgendes: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Beachten Sie, wie jeder Tippfehler mit einer Handvoll plausibler Korrekturen gekoppelt ist — genau das, was Sie für eine benutzerfreundliche Korrektur‑UI benötigen. + +## Vollständiges, funktionierendes Beispiel + +Unten finden Sie das **complete, copy‑paste‑ready** Programm. Ersetzen Sie `YOUR_DIRECTORY` durch den tatsächlichen Pfad zu Ihrer Bilddatei. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Edge Cases to Consider** +> - **Empty Image:** Wenn die OCR‑Engine einen leeren String zurückgibt, liefert `spellChecker.Check` einfach eine leere Sammlung — kein Absturz. +> - **Non‑English Text:** Ersetzen Sie `OcrLanguage.English` durch `OcrLanguage.French` (oder eine andere unterstützte Sprache), um **detect misspelled words** in anderen Locale zu erkennen. +> - **Large Documents:** Bei mehrseitigen PDFs würden Sie über jede Seite iterieren, OCR ausführen und dann die Ergebnisse vor dem Rechtschreib‑Check aggregieren. + +## Visueller Überblick (Image Alt Text) + +![Diagramm, das den Ablauf zeigt, um OCR auf Bild auszuführen, Text aus Bild zu extrahieren und dann Rechtschreibfehler mit Rechtschreibungsvorschlägen zu erkennen](perform-ocr-on-image-flow.png) + +*Das obige Diagramm illustriert die End‑zu‑End‑Pipeline: Bild → OCR‑Engine → Roh‑Text → Rechtschreib‑Checker → Vorschläge.* + +## Häufige Fragen & Pro‑Tipps + +| Frage | Antwort | +|-------|----------| +| **Brauche ich eine Internetverbindung?** | Nein. Aspose.OCR läuft vollständig lokal; ideal für Offline‑ oder sichere Umgebungen. | +| **Wie genau ist der Rechtschreib‑Checker?** | Er verwendet ein Wörterbuch mit ~150 k englischen Wörtern und Fuzzy‑Matching, sodass die meisten gängigen Tippfehler erkannt werden. | +| **Kann ich das Wörterbuch anpassen?** | Ja. `SpellChecker.AddUserDictionary("custom.txt")` ermöglicht das Laden domänenspezifischer Begriffe (z. B. Produktnamen). | +| **Was, wenn das Bild schief steht?** | Die OCR‑Engine erkennt die Orientierung automatisch, Sie können jedoch bei hartnäckigen Fällen `ocrEngine.ImagePreprocessing.Rotate(angle)` manuell aufrufen. | +| **Gibt es eine Möglichkeit, Vorschläge in der UI hervorzuheben?** | Sobald Sie die `misspellings`‑Sammlung haben, können Sie jedes `entry.Word` zurück zu seiner Position in `ocrResult.Text` mapen und es in einer RichTextBox oder Web‑View unterstreichen. | + +## Fazit + +Wir haben Ihnen gezeigt, **how to perform OCR on image**, **extract text from image** und anschließend **detect misspelled words** sowie **get spelling suggestions** — alles mit einer kompakten C#‑Konsolen‑App. Die Kernidee ist simpel: Lassen Sie Aspose.OCR die schwere Arbeit der Zeichen­erkennung übernehmen und nutzen Sie den integrierten Rechtschreib‑Checker, um das Ergebnis zu säubern. Von hier aus können Sie das Demo‑Projekt zu einem vollwertigen Dokumenten‑Verarbeitungs‑Service ausbauen, in eine Web‑API integrieren oder in einen Desktop‑Editor einbinden. + +Bereit für den nächsten Schritt? Versuchen Sie, die Sprache zu Spanisch zu wechseln, ein mehrseitiges PDF zu verarbeiten oder ein kleines WPF‑Frontend zu bauen, das dem Nutzer erlaubt, ein Wort anzuklicken, um einen Vorschlag zu übernehmen. Die Bausteine stehen bereits – experimentieren Sie weiter. + +Wenn Sie auf Probleme stoßen oder Ideen für Erweiterungen haben, hinterlassen Sie unten einen Kommentar. Viel Spaß beim Coden! + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren Projekten zu erkunden. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/german/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/german/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..b921d1d38 --- /dev/null +++ b/ocr/german/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: Führen Sie OCR auf einem Bild mit Aspose OCR in C# durch. Erfahren Sie, + wie Sie ein Bild für OCR laden und Hindi‑Text offline extrahieren, mit Schritt‑für‑Schritt‑Code. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: de +og_description: Führen Sie OCR auf einem Bild mit Aspose OCR in C# durch. Dieses Tutorial + zeigt, wie man ein Bild für OCR lädt und offline Hindi‑Text aus dem Bild extrahiert, + inklusive ausführbarem Code. +og_title: OCR auf Bild ausführen – Aspose OCR Hindi‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: OCR auf Bild mit Aspose OCR durchführen – Hindi-Anleitung +url: /de/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR auf Bild mit Aspose OCR – Hindi‑Leitfaden + +Haben Sie jemals **OCR auf Bild**‑Dateien durchführen müssen, waren aber unsicher, wie Sie Hindi‑Zeichen daraus extrahieren können? Sie sind nicht allein – viele Entwickler stoßen an diese Grenze, wenn sie zum ersten Mal nicht‑lateinische Schriften lesen wollen. Die gute Nachricht ist, dass Aspose OCR das ziemlich einfach macht und Sie es sogar komplett offline ausführen können. + +In diesem Leitfaden werden wir **Bild für OCR laden**, die Engine auf Ihre Offline‑Sprachpakete verweisen und schließlich **Hindi‑Text aus Bild**‑Daten extrahieren, ohne jemals das Internet zu berühren. Am Ende haben Sie eine sofort ausführbare C#‑Konsolen‑App, die eine Hindi‑Quittung liest und den Text in der Konsole ausgibt. + +## Was Sie benötigen + +- **.NET 6.0** oder höher (der Code funktioniert auch mit .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet‑Paket + `dotnet add package Aspose.OCR` +- Ein Ordner, der die **offline Hindi‑Sprachressourcen** enthält (Download über das Aspose‑Portal) +- Eine Bilddatei mit Hindi‑Text, z. B. `receipt_hindi.png` + +Das war’s – keine externen Dienste, keine API‑Schlüssel, nur geradliniger Code. + +## OCR auf Bild ausführen – Schritt‑für‑Schritt‑Implementierung + +Im Folgenden teilen wir den Prozess in sieben klare Schritte auf. Jeder Schritt wird erklärt **warum** er wichtig ist, nicht nur **was** Sie eingeben müssen. + +### Schritt 1: OCR‑Engine‑Instanz erstellen + +Die Engine ist das Herz von Aspose OCR. Durch das Instanziieren erhalten Sie Zugriff auf alle Einstellungen, die Sie später anpassen können. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Warum?** +> Ohne ein `OcrEngine`‑Objekt haben Sie kein Objekt, auf dem Sie `Recognize` aufrufen können. Denken Sie an es als die „Kamera“, die später Ihr Bild scannt. + +### Schritt 2: Engine auf Offline‑Ressourcen verweisen + +Aspose liefert Sprachpakete, die Sie lokal speichern können. Das Setzen von `ResourcesFolder` teilt der Engine mit, wo sie suchen soll. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tipp:** +> Verwenden Sie während der Entwicklung einen absoluten Pfad und wechseln Sie für die Produktion zu einem relativen Pfad oder einer Konfigurationseinstellung. + +### Schritt 3: Offline‑Modus erzwingen + +Sie fragen sich vielleicht: „Muss ich wirklich die Online‑Suche deaktivieren?“ +Wenn Sie hinter einer Firewall arbeiten oder deterministische Ergebnisse wollen, setzen Sie `UseOfflineResources` auf `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro‑Tipp:** +> Wenn dieses Flag `false` bleibt, kann die Engine zusätzliche Daten herunterladen, was Latenz erzeugt und möglicherweise Sicherheitsrichtlinien verletzt. + +### Schritt 4: Hindi als Erkennungssprache auswählen + +Hier **extrahieren wir Hindi‑Text aus Bild**, indem wir der Engine mitteilen, welche Sprache erwartet wird. Das verbessert die Genauigkeit erheblich. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Warum das hilft:** +> OCR‑Engines verwenden sprachspezifische Zeichenmodelle. Durch das Festlegen auf Hindi verhindern Sie, dass die Engine zwischen Dutzenden von Schriften rät. + +### Schritt 5: Bild für OCR laden + +Jetzt **laden wir das Bild für OCR**. Die Methode `OcrImage.FromFile` liest das Bitmap in ein Format ein, das die Engine versteht. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Häufiges Stolpersteine:** +> Ein Pfad mit Vorwärtsschrägstrichen funktioniert unter Windows, aber die Verwendung von `Path.Combine` macht Ihren Code plattformunabhängig. + +### Schritt 6: Erkennung ausführen + +Mit allen Einstellungen führen wir schließlich **OCR auf Bild aus**, indem wir `Recognize` aufrufen. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Was passiert?** +> Die Engine scannt jedes Pixel, vergleicht Muster mit der Hindi‑Glyph‑Datenbank und erstellt eine Zeichenkette aus Unicode‑Zeichen. + +### Schritt 7: Erkannten Text ausgeben + +Das Ergebnisobjekt enthält die Eigenschaft `Text`, die die extrahierte Zeichenkette hält. Wir schreiben sie einfach in die Konsole. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Erwartete Ausgabe:** +> Wenn `receipt_hindi.png` „भुगतान सफल“ enthält, gibt die Konsole genau diese Zeile aus und bewahrt die Diakritika. + +## Bild für OCR laden – Ressource vorbereiten + +Falls Sie sich fragen, ob Sie der Engine einen Stream anstelle einer Datei übergeben können, lautet die Antwort ja. Ersetzen Sie `OcrImage.FromFile` durch: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Warum einen Stream verwenden?** +> Streams ermöglichen die Arbeit mit Bildern, die in Datenbanken, Cloud‑Blobs oder eingebetteten Ressourcen gespeichert sind – ideal für skalierbare Dienste. + +## Hindi‑Text aus Bild extrahieren – Sonderfälle behandeln + +1. **Fehlendes Sprachpaket** – Wenn das Hindi‑Paket nicht gefunden wird, wirft `Recognize` eine Ausnahme. Umgeben Sie den Aufruf mit try/catch und protokollieren Sie eine freundliche Meldung. +2. **Niedrigauflösende Bilder** – Die OCR‑Genauigkeit sinkt unter 300 dpi. Verarbeiten Sie das Bild vor (Größe ändern, schärfen), bevor Sie es laden. +3. **Dokumente mit gemischten Sprachen** – Sie können mehrere Sprachen aktivieren: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Diese Anpassungen stellen sicher, dass Ihre **perform OCR on image**‑Routine in der Produktion robust bleibt. + +## Vollständiges Beispiel ausführen + +Speichern Sie die folgende Datei als `Program.cs`, ersetzen Sie die Platzhalter‑Pfade und führen Sie sie aus: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Wenn Sie `dotnet run` ausführen, sollten Sie etwas Ähnliches sehen: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Falls Sie eine leere Zeichenkette erhalten, prüfen Sie, ob der **ResourcesFolder** auf den Ordner zeigt, der `Hindi.traineddata` enthält, und ob das Bild ausreichend klar ist. + +## Fazit + +Wir haben erklärt, wie man **perform OCR on image**‑Dateien mit Aspose OCR verarbeitet, von **load image for OCR** bis **extract Hindi text image** in einem vollständig offline Szenario. Der oben stehende vollständige, ausführbare Code bietet Ihnen eine solide Grundlage, und die Tipps zu Streams, Fehlerbehandlung und Mehrsprachunterstützung helfen Ihnen, die Lösung für reale Projekte anzupassen. + +Bereit für den nächsten Schritt? Versuchen Sie, die Sprache zu **OcrLanguage.Tamil** zu wechseln oder Bilder aus einem Azure‑Blob‑Speicher zu laden. Sie können auch mit den `ImagePreprocessing`‑Einstellungen experimentieren, um die Genauigkeit bei verrauschten Quittungen zu erhöhen. + +Haben Sie Fragen oder sind Sie auf ein Problem gestoßen? Hinterlassen Sie einen Kommentar – happy coding! + +![Perform OCR on image example + + +## Was sollten Sie als Nächstes lernen? + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, um Ihnen zu helfen, weitere API‑Funktionen zu meistern und alternative Implementierungsansätze in Ihren eigenen Projekten zu erkunden. + +- [Bildtext in C# mit Sprachauswahl mithilfe von Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Text aus Bild mit Aspose OCR für mehrere Sprachen erkennen](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Text aus Bild extrahieren – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/german/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..f5483360a --- /dev/null +++ b/ocr/german/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,306 @@ +--- +category: general +date: 2026-06-03 +description: Führen Sie OCR auf PDF durch und konvertieren Sie gescannte PDFs in durchsuchbare + PDFs mit Aspose.OCR. Erfahren Sie, wie Sie Text aus PDFs erkennen und in wenigen + Minuten durchsuchbare PDFs erstellen. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: de +og_description: Führen Sie OCR auf PDF durch und erstellen Sie sofort ein durchsuchbares + PDF. Dieses Tutorial zeigt Schritt für Schritt, wie man Text aus PDF mit Aspose.OCR + erkennt. +og_title: OCR auf PDF ausführen – Vollständiger C#‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: OCR auf PDF mit Aspose.OCR durchführen – Vollständiger C#‑Leitfaden +url: /de/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR in PDF mit Aspose.OCR – Vollständiger C#‑Leitfaden + +Haben Sie sich schon einmal gefragt, **wie man OCR in PDF**‑Dateien durchführt, ohne sich mit Dutzenden von Kommandozeilen‑Tools herumzuschlagen? Sie sind nicht allein. Ob Sie Rechnungen digitalisieren, alte Berichte archivieren oder einfach nur eine durchsuchbare Version eines gescannten Vertrags benötigen – ein statisches PDF in etwas zu verwandeln, das Sie tatsächlich durchsuchen können, ist ein echter Game‑Changer. + +In diesem Leitfaden zeigen wir Ihnen **wie man durchsuchbare PDF**‑Dateien aus gescannten PDFs (und sogar aus einfachen Bildern) mit Aspose.OCR für .NET erstellt. Am Ende können Sie **Text aus PDF** mit wenigen Zeilen C#‑Code erkennen und verstehen das „Warum“ hinter jedem Schritt, sodass Sie die Lösung an Ihre eigenen Projekte anpassen können. + +> **Kurzfassung:** Der gesamte Prozess lässt sich auf drei Dinge reduzieren – die OCR‑Engine initialisieren, die Quelle (PDF oder Bild) zuführen und das durchsuchbare PDF‑Ergebnis speichern. Los geht’s. + +--- + +## Was Sie benötigen + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes haben: + +| Voraussetzung | Warum wichtig | +|--------------|----------------| +| **.NET 6.0+** (oder .NET Framework 4.6+) | Aspose.OCR zielt auf moderne Laufzeiten; ältere Versionen können API‑Updates verpassen. | +| **Aspose.OCR for .NET** NuGet‑Paket | Stellt die Klasse `OcrEngine` und PDF‑Verarbeitungs‑Utilities bereit. | +| **Eine gültige Aspose‑Lizenz** (oder die kostenlose Evaluation) | Ohne Lizenz stoßen Sie nach 30 Tagen auf ein Evaluations‑Limit und Wasserzeichen. | +| **Ein gescanntes PDF** (oder eine Bilddatei), das durchsuchbar gemacht werden soll | Das ist das Quell‑Dokument für das OCR. | +| **Visual Studio 2022** (oder ein beliebiger C#‑Editor) | Erleichtert das Debuggen, aber jede IDE funktioniert. | + +Sie können die Bibliothek mit folgendem NuGet‑Befehl installieren: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro‑Tipp:** Wenn Sie in einer CI‑Pipeline arbeiten, fügen Sie die Lizenzdatei zu den Build‑Artefakten hinzu und laden Sie sie zur Laufzeit, um harte Pfade zu vermeiden. + +--- + +## OCR in PDF durchführen – Aspose.OCR einrichten + +Das Erste, was wir benötigen, ist eine frische `OcrEngine`‑Instanz. Denken Sie daran als das Gehirn, das Ihr Dokument liest. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Warum jedes Mal eine neue Instanz? Die Engine hält Konfigurationen (wie Spracheinstellungen), die pro Dokument unterschiedlich sein können. Durch die Instanziierung pro Lauf wird ein sauberer Ausgangszustand garantiert und ein „Cross‑Talk“ zwischen Jobs vermieden. + +--- + +## Durchsuchbares PDF erstellen – Passwörter konfigurieren (optional) + +Falls Ihr PDF geschützt ist, müssen Sie der Engine das Passwort mitteilen, bevor sie die Seiten lesen kann: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Wird dieser Schritt bei einer geschützten Datei übersprungen, wirft die Engine eine `PdfPasswordException`. Packen Sie ihn immer in ein try‑catch, wenn Sie sich über den Schutzstatus nicht sicher sind. + +--- + +## Gescanntes PDF in durchsuchbares PDF umwandeln – Quelle laden + +Aspose.OCR arbeitet mit der Abstraktion `OcrImage`, die PDFs, TIFFs, JPEGs usw. einpacken kann. So laden Sie ein gescanntes PDF in den Speicher: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Im Hintergrund parst `FromFile` jede Seite in Rasterbilder, die die OCR‑Engine verarbeiten kann. Bei einem mehrseitigen PDF iteriert die Engine automatisch über jede Seite. + +--- + +## Text aus PDF erkennen – OCR ausführen + +Jetzt zum Kern des Tutorials: Die Engine auffordern, den Text zu erkennen und ein durchsuchbares PDF auszugeben. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` weist die Engine an, eine unsichtbare Textebene über den ursprünglichen gescannten Bildern einzubetten. Das resultierende PDF behält die visuelle Treue des Scans bei und wird vollständig durchsuchbar – genau das, was Sie für Compliance‑Audits benötigen. + +--- + +## Bild in durchsuchbares PDF umwandeln – Ergebnis speichern + +Zum Schluss schreiben wir die Binärdaten auf die Festplatte: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Die Eigenschaft `Binary` enthält die rohen PDF‑Bytes. Sie könnten sie auch direkt an eine Web‑Response streamen, wenn Sie eine API bauen. + +--- + +![Diagramm, das den OCR‑Konvertierungsablauf zur Erstellung eines durchsuchbaren PDFs zeigt](https://example.com/ocr-flow.png "OCR‑in‑PDF‑Ablaufdiagramm") + +*Bild‑Alt‑Text: OCR‑in‑PDF‑Ablaufdiagramm, das illustriert, wie ein gescanntes PDF in ein durchsuchbares PDF umgewandelt wird.* + +--- + +## Sonderfälle & Praxis‑Tipps + +### 1. Große Dateien & Speicherverwaltung +Verarbeiten Sie PDFs, die größer als 100 MB sind, sollten Sie `OcrEngineSettings.MemoryLimit` verwenden, um den Speicherverbrauch zu begrenzen. Zusätzlich können Sie Seiten stapelweise verarbeiten, um `OutOfMemoryException` zu vermeiden. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Sprachunterstützung +Standardmäßig geht Aspose.OCR von Englisch aus. Um andere Sprachen zu erkennen, setzen Sie die Eigenschaft `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Mehr‑Thread‑Szenarien +`OcrEngine` ist **nicht** thread‑sicher. Wenn Sie Parallelverarbeitung benötigen, erstellen Sie pro Thread eine separate Engine. + +### 4. OCR‑Genauigkeit debuggen +Sie können den Klartext aus `ocrResult` extrahieren, um zu debuggen: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Sieht die Ausgabe wirr aus, experimentieren Sie mit `PreprocessSettings` (z. B. Deskew, Despeckle), um die Qualität zu verbessern. + +### 5. Lizenz‑Fallstricke +Wenn Sie die Evaluationsversion ausführen, fügt Aspose ein Wasserzeichen zum Ausgabepdf hinzu. Registrieren Sie Ihre Lizenz früh im Anwendungscode: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Vollständiges Beispiel – Von Anfang bis Ende + +Unten finden Sie das komplette, sofort ausführbare Programm, das alle oben genannten Tipps integriert. Kopieren Sie es gern in ein neues Konsolen‑Projekt. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Erwartete Ausgabe:** Nach dem Ausführen sehen Sie eine Konsolenzeile, die den Dateipfad bestätigt. Öffnen Sie `output.pdf` in einem beliebigen PDF‑Betrachter; tippen Sie ein Wort ein, von dem Sie wissen, dass es im Original‑Scan vorkommt. Wenn das Wort hervorgehoben wird, haben Sie erfolgreich **OCR in PDF** durchgeführt und ein durchsuchbares Dokument erstellt. + +--- + +## Häufig gestellte Fragen + +**F: Kann ich damit ein einzelnes Bild (PNG/JPEG) in ein durchsuchbares PDF umwandeln?** +A: Absolut. Ersetzen Sie `OcrImage.FromFile("input.pdf")` durch den Pfad zu Ihrer Bilddatei. Die Engine rasterisiert das Bild und bettet die OCR‑Ebene genauso ein. + +**F: Was, wenn mein PDF sowohl gescannte Seiten als auch nativen Text enthält?** +A: Die Engine legt den OCR‑Text über den vorhandenen Inhalt, sodass nativer Text auswählbar bleibt, während gescannte Seiten durchsuchbar werden. + +**F: Wie genau ist das OCR?** +A: Die Genauigkeit hängt von der Quellqualität ab. Saubere, hochauflösende Scans (>300 dpi) erreichen >95 % Genauigkeit. Bei verrauschten Dokumenten aktivieren Sie `PreprocessSettings` (Deskew, Despeckle) vor dem Aufruf von `Recognize`. + +--- + +## Nächste Schritte – Ihr OCR‑Toolkit erweitern + +Jetzt, da Sie **Text aus PDF** erkennen und **gescannte PDFs in durchsuchbare PDFs** umwandeln können, denken Sie an folgende weiterführende Themen: + +- **Batch‑Verarbeitung**: Durchlaufen Sie einen Ordner mit PDFs und erzeugen Sie automatisch durchsuchbare Versionen. +- **Textextraktion**: Nutzen Sie `ocrResult.Text`, um einen Such‑Index (z. B. Elasticsearch) zu füttern. +- **Benutzerdefinierte Sprachpakete**: Laden Sie zusätzliche Sprachdaten von Aspose herunter, um asiatische Schriften zu unterstützen. +- **PDF/A‑Konformität**: Kombinieren Sie Aspose.PDF mit dem OCR‑Ergebnis, um archivierungs‑fertige PDFs zu erstellen. + +All diese Punkte bauen auf den Kernschritten auf, die wir behandelt haben, sodass Sie gut gerüstet sind, Ihre Lösung zu erweitern. + +--- + +## Fazit + +Wir haben Ihnen gezeigt, **wie man OCR in PDF**‑Dateien mit Aspose.OCR durchführt, gescannte PDFs in vollständig durchsuchbare PDFs verwandelt und sogar die Umwandlung von reinen Bildern in durchsuchbare PDFs behandelt. Der Code + +## Was Sie als Nächstes lernen sollten + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden demonstrierten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, damit Sie weitere API‑Features meistern und alternative Implementierungs‑Ansätze in Ihren eigenen Projekten erkunden können. + +- [PDF‑Text erkennen – OCR‑Operationen mit Aspose.OCR für Java](/ocr/english/java/ocr-operations/) +- [Wie man PDF in .NET mit Aspose.OCR OCR‑t](/ocr/english/net/text-recognition/recognize-pdf/) +- [Bilder zu PDF C# – Mehrseitiges OCR‑Ergebnis speichern](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/german/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..86e86834a --- /dev/null +++ b/ocr/german/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-03 +description: Video-Untertitel-OCR‑Tutorial, das zeigt, wie man Frames aus einem Video + extrahiert und Text aus Videodateien wie MP4 mit Aspose.OCR liest. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: de +og_description: Lernen Sie Video-Untertitel-OCR mit Aspose.OCR. Extrahieren Sie Frames + aus einem Video, lesen Sie Text aus dem Video und extrahieren Sie Text aus MP4 in + wenigen Minuten. +og_title: Video‑Untertitel‑OCR in C# – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: Video-Untertitel-OCR in C# – Vollständiger Leitfaden +url: /de/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Video‑Untertitel‑OCR in C# – Komplett‑Anleitung + +Hast du jemals **Video‑Subtitle‑OCR** gebraucht, wusstest aber nicht, wo du anfangen sollst? Du bist nicht allein. Egal, ob du Vorlesungsaufzeichnungen digitalisierst, Untertitel aus Trainingsvideos extrahierst oder einfach nur neugierig bist, wie man Text aus einem Video liest – dieses Tutorial zeigt dir genau, wie du das mit C# und Aspose.OCR machst. + +In den nächsten Minuten extrahieren wir Frames aus einem Video, führen OCR auf diesen Frames aus und zeigen schließlich den Untertitel‑Text Frame für Frame an. Am Ende kannst du **Text aus Video**‑Dateien – inklusive MP4 – lesen, ohne nach Drittanbieter‑Tools zu suchen. + +## Was du bauen wirst + +Wir erstellen eine kleine Konsolen‑App, die: + +1. Ein MP4 (oder ein beliebiges unterstütztes Format) in einzelne `Bitmap`‑Frames dekodiert. +2. Den OCR‑Bereich auf das Untertitel‑Band beschränkt, damit die Engine nicht vom gesamten Bild abgelenkt wird. +3. Jeden Frame mit Asposes `VideoOcrProcessor` verarbeitet. +4. Den erkannten Untertitel‑Text in der Konsole ausgibt. + +Kein Schnickschnack, nur ein funktionierendes End‑zu‑End‑Beispiel, das du in ein echtes Projekt übernehmen kannst. + +## Voraussetzungen + +- **.NET 6.0** oder höher (der Code funktioniert auch mit .NET Framework 4.7+). +- **Aspose.OCR für .NET** – Installation via NuGet: `Install-Package Aspose.OCR`. +- Eine Videodatei (MP4 funktioniert hervorragend). +- Eine Möglichkeit, Videoframes zu dekodieren – das Demo verwendet eine Platzhaltermethode, du kannst aber FFmpeg, OpenCV oder jede Bibliothek einsetzen, die `Bitmap`‑Objekte zurückgibt. + +> Pro‑Tipp: Unter Windows funktioniert das Paket `System.Drawing.Common` einwandfrei für `Bitmap`. Unter Linux/macOS benötigst du die native Abhängigkeit `libgdiplus`. + +## Schritt 1 – Frames aus dem Video extrahieren + +Die erste Hürde besteht darin, ein bewegtes Bild in Standbilder zu verwandeln. Die Methode `GetVideoFrames` unten ist bewusst leer gelassen; ersetze sie durch deinen bevorzugten Decoder. Hier ein kurzer Sketch mit FFmpeg‑Core (nur um die Datenstruktur zu veranschaulichen): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Warum das wichtig ist:** Das Extrahieren von Frames liefert der OCR‑Engine ein statisches Bild, was die Genauigkeit im Vergleich zum direkten Lesen aus einem Videostream dramatisch erhöht. + +## Schritt 2 – VideoOcrProcessor einrichten + +Jetzt, wo wir eine Sequenz von `Bitmap`‑Objekten haben, können wir sie an Aspose.OCR übergeben. Der `VideoOcrProcessor` ermöglicht das Definieren einer **Region of Interest (ROI)** – ideal für Untertitel, die meist am oberen oder unteren Bildrand liegen. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Warum die ROI begrenzen?** Indem wir den Rest des Bildes ignorieren, reduzieren wir Rauschen, verkürzen die Verarbeitungszeit und vermeiden Fehlinterpretationen durch Hintergrundgrafiken. + +## Schritt 3 – OCR auf der Frame‑Sequenz ausführen + +Ist der Processor bereit, das Einspeisen der Frames einzeilig: Die Methode `Process` liefert eine Aufzählung von `OcrResult`‑Objekten, die jeweils den erkannten Text für den entsprechenden Frame enthalten. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Was im Hintergrund passiert:** Aspose.OCR normalisiert intern jedes Bitmap, führt einen neuronalen Netzwerk‑basierten Erkenner aus und post‑processiert anschließend das Ergebnis, um Interpunktion und Zeilenumbrüche zu verbessern. + +## Schritt 4 – Extrahierten Text anzeigen + +Abschließend iterieren wir über die Ergebnisse und geben jede Untertitelzeile aus. Du könntest sie auch in eine SRT‑Datei, eine Datenbank schreiben oder an einen Übersetzungs‑Service weiterleiten. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Vollständiges funktionierendes Beispiel + +Alles zusammengefügt ergibt ein eigenständiges Konsolen‑Programm: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Erwartete Ausgabe (Beispiel)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Wenn das OCR bei einem bestimmten Frame Schwierigkeiten hat, erscheint ein leerer String – das ist ein Hinweis, die ROI anzupassen oder die Frame‑Extraktionsrate zu erhöhen. + +## Häufige Stolperfallen & Lösungen + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| **Garbage‑Zeichen** | Frames mit niedriger Auflösung oder starker Kompression | Frames mit höherer Bitrate extrahieren oder das Bitmap vor dem OCR hochskalieren (`Bitmap.Clone(new Size(...), ...)`). | +| **Kein Text zurückgegeben** | ROI deckt das Untertitel‑Band nicht ab | Rechteckkoordinaten überprüfen (mit einem Screenshot‑Tool messen). | +| **Leistungsengpass** | Jede Frame mit 30 fps zu verarbeiten ist übertrieben | Auf 1‑2 fps herunterstufen – das reicht für die meisten Untertitel‑Streams, du kannst trotzdem jede Untertitel‑Änderung erfassen. | +| **FFmpeg nicht gefunden** | `ffmpeg.exe` ist nicht im `PATH` | Vollständigen Pfad in `ProcessStartInfo.FileName` angeben oder FFmpeg global installieren. | + +## Erweiterung der Lösung + +- **Export nach SRT** – Zeitstempel mit dem OCR‑Text verknüpfen und eine SubRip‑Datei schreiben. +- **Mehrsprachige Unterstützung** – `ocrProcessor.Language = OcrLanguage.Spanish` setzen (oder jede andere unterstützte Sprache). +- **Echtzeit‑Verarbeitung** – Frames direkt aus einem Live‑Stream pipen, anstatt sie von der Festplatte zu lesen. + +All diese Varianten drehen sich weiterhin um die Kernideen **Frames aus Video extrahieren**, **Text aus Video lesen** und **Text aus MP4 extrahieren**. + +## Fazit + +Wir haben gerade einen kompletten **Video‑Subtitle‑OCR**‑Workflow in C# durchlaufen. Durch das Extrahieren von Frames, das Fokussieren des OCR auf das Untertitel‑Band und das Durchlaufen der Ergebnisse kannst du zuverlässig **Text aus Video**‑Dateien wie MP4 lesen. Der Code ist copy‑paste‑fertig, und das modulare Design erlaubt dir, jeden gewünschten Frame‑Decoder einzusetzen. + +Nächste Schritte? Exportiere die Ergebnisse in eine SRT‑Datei, experimentiere mit verschiedenen ROI‑Größen oder speise die Untertitel in eine Übersetzungs‑API für mehrsprachige Captions ein. Sobald du die Grundlagen des Text‑Extrahierens aus Videos beherrschst, sind deiner Kreativität keine Grenzen gesetzt. + +Viel Spaß beim Coden, und mögen deine Untertitel immer kristallklar sein! + + +## Was du als Nächstes lernen solltest + + +Die folgenden Tutorials behandeln eng verwandte Themen, die auf den in diesem Leitfaden gezeigten Techniken aufbauen. Jede Ressource enthält vollständige, funktionierende Code‑Beispiele mit Schritt‑für‑Schritt‑Erklärungen, damit du weitere API‑Funktionen meistern und alternative Implementierungsansätze in deinen eigenen Projekten erkunden kannst. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/ocr-configuration/_index.md b/ocr/greek/net/ocr-configuration/_index.md index 3c21d17fc..f9efb0ca0 100644 --- a/ocr/greek/net/ocr-configuration/_index.md +++ b/ocr/greek/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ weight: 24 Αποκτήστε ισχυρές δυνατότητες OCR με το Aspose.OCR για .NET. Εξάγετε κείμενο από εικόνες απρόσκοπτα. ### [OCROperation με Λίστα σε Αναγνώριση Εικόνας OCR](./ocr-operation-with-list/) Αποκτήστε το δυναμικό του Aspose.OCR για .NET. Εκτελέστε αναγνώριση εικόνων OCR με λίστες εύκολα. Αυξήστε την παραγωγικότητα και την εξαγωγή δεδομένων στις εφαρμογές σας. +### [Αποκτήστε την έκδοση Aspose OCR σε C# – Πλήρης Οδηγός](./get-aspose-ocr-version-in-c-complete-guide/) +Μάθετε πώς να εντοπίσετε την έκδοση της βιβλιοθήκης Aspose OCR σε εφαρμογές C# με απλό κώδικα. ### Κοινές Περιπτώσεις Χρήσης - **Εξαγωγή κειμένου από εικόνες** σε σαρωμένα τιμολόγια για αυτοματοποιημένη λογιστική. @@ -100,4 +102,4 @@ A: Ναι, το αντικείμενο `OcrResult` παρέχει τιμές ε {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/greek/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..440321f47 --- /dev/null +++ b/ocr/greek/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-03 +description: Αποκτήστε την έκδοση του Aspose OCR σε C# με ένα απλό απόσπασμα. Μάθετε + πώς να ανακτήσετε την έκδοση της βιβλιοθήκης Aspose OCR χρησιμοποιώντας το OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: el +og_description: Αποκτήστε γρήγορα την έκδοση του Aspose OCR σε C#. Αυτό το σεμινάριο + δείχνει ακριβώς πώς να ανακτήσετε την έκδοση της βιβλιοθήκης Aspose OCR χρησιμοποιώντας + το OcrEngine GetVersion. +og_title: Αποκτήστε την έκδοση Aspose OCR σε C# – Πλήρης οδηγός +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Αποκτήστε την έκδοση Aspose OCR σε C# – Πλήρης οδηγός +url: /el/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Απόκτηση Έκδοσης Aspose OCR σε C# – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ πώς να **αποκτήσετε την έκδοση Aspose OCR** από το .NET project σας; Ίσως αντιμετωπίζετε ένα πρόβλημα ασυμφωνίας, ή απλώς θέλετε να καταγράψετε την ακριβή έκδοση της βιβλιοθήκης που τρέχει στην παραγωγή. Όποιος και αν είναι ο λόγος, βρίσκεστε στο σωστό μέρος. + +Σε αυτό το tutorial θα περάσουμε βήμα-βήμα από ένα μικρό, αυτόνομο πρόγραμμα C# που καλεί το `OcrEngine.GetVersion()` και εκτυπώνει το αποτέλεσμα. Στο τέλος θα γνωρίζετε όχι μόνο *πώς* να ανακτήσετε την έκδοση, αλλά και *γιατί* ο έλεγχος της έκδοσης μπορεί να σας εξοικονομήσει προβλήματα κατά την αναβάθμιση της **βιβλιοθήκης Aspose OCR**. + +## Τι Θα Μάθετε + +- Προσθέστε το πακέτο NuGet Aspose.OCR σε ένα έργο C# +- Χρησιμοποιήστε τη μέθοδο `OcrEngine.GetVersion()` (το σημείο εισόδου **ocrengine getversion**) +- Διαχειριστείτε πιθανές εξαιρέσεις και επαληθεύστε το αποτέλεσμα +- Επεκτείνετε το απόσπασμα για πραγματικές περιπτώσεις όπως καταγραφή ή συνθήκες ενεργοποίησης λειτουργιών + +Δεν απαιτείται προηγούμενη εμπειρία με OCR — απλώς μια βασική κατανόηση του C# και του Visual Studio (ή του αγαπημένου σας IDE). Ας ξεκινήσουμε. + +--- + +## Βήμα 1: Ρύθμιση του Έργου και Ενσωμάτωση της Βιβλιοθήκης Aspose OCR + +Πριν μπορέσετε να καλέσετε οποιαδήποτε API σχετικό με OCR, χρειάζεται η **βιβλιοθήκη Aspose OCR** να αναφέρεται στο έργο σας. + +1. Ανοίξτε ένα τερματικό ή το Package Manager Console στο Visual Studio. +2. Εκτελέστε την παρακάτω εντολή για να εγκαταστήσετε την πιο πρόσφατη σταθερή έκδοση: + +```bash +dotnet add package Aspose.OCR +``` + +> **Συμβουλή:** Εάν στοχεύετε στο .NET Framework αντί για .NET Core, χρησιμοποιήστε το UI του NuGet Package Manager και επιλέξτε την έκδοση που ταιριάζει στο runtime σας. Το πακέτο περιλαμβάνει την κλάση `OcrEngine` που θα χρησιμοποιήσουμε αργότερα. + +### Γιατί είναι σημαντικό + +Όταν εγκαθιστάτε το πακέτο, η έκδοση του assembly στο δίσκο μπορεί να διαφέρει από την έκδοση που αναφέρει η βιβλιοθήκη κατά την εκτέλεση. Η ανάκτηση της έκδοσης μέσω κώδικα εξασφαλίζει ότι διαβάζετε την ακριβή κατασκευή που φόρτωσε το CLR, κάτι που είναι κρίσιμο για τον εντοπισμό σφαλμάτων και για ελέγχους συμμόρφωσης. + +--- + +## Βήμα 2: Γράψτε τον Ελάχιστο Κώδικα για **Απόκτηση Έκδοσης Aspose OCR** + +Δημιουργήστε μια νέα εφαρμογή κονσόλας (`dotnet new console -n OcrVersionDemo`) και αντικαταστήστε το προεπιλεγμένο `Program.cs` με το παρακάτω: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Επεξήγηση κάθε μέρους** + +- `using Aspose.OCR;` φέρνει το namespace OCR στο πεδίο ορατότητας, επιτρέποντάς μας να καλέσουμε το `OcrEngine`. +- `OcrEngine.GetVersion()` είναι η στατική μέθοδος **ocrengine getversion** που επιστρέφει μια συμβολοσειρά όπως `"24.5.7"`. +- Η περιτύλιξη της κλήσης σε μπλοκ `try/catch` σας προστατεύει από απρόσμενα σφάλματα εκτέλεσης — ίσως τα εγγενή δυαδικά αρχεία να μην βρεθούν στο στόχο. +- Η διασυνδεδεμένη συμβολοσειρά `$"Aspose OCR version: {version}"` εκτυπώνει μια σαφή, ανθρώπινα αναγνώσιμη γραμμή. + +### Αναμενόμενη έξοδος + +Όταν εκτελέσετε `dotnet run` μέσα στο φάκελο του έργου, θα πρέπει να δείτε κάτι παρόμοιο με: + +``` +Aspose OCR version: 24.5.7 +``` + +Εάν η βιβλιοθήκη δεν μπορεί να φορτωθεί, το κλαδί σφάλματος θα εμφανίσει ένα συνοπτικό μήνυμα, βοηθώντας σας να εντοπίσετε το πρόβλημα γρήγορα. + +--- + +## Βήμα 3: Επαλήθευση ότι η Έκδοση Συμφωνεί με το Πακέτο NuGet σας + +Είναι εύκολο να υποθέσετε ότι η έκδοση NuGet που εγκαταστήσατε είναι αυτή που χρησιμοποιείται κατά την εκτέλεση, αλλά ιδιαιτερότητες του περιβάλλοντος μπορούν να επηρεάσουν. Για διπλό έλεγχο: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Η εκτέλεση αυτού του επιπλέον αποσπάσματος θα εκτυπώσει κάτι όπως: + +``` +Assembly file version: 24.5.7.0 +``` + +Εάν οι δύο τιμές διαφέρουν, μπορεί να φορτώνετε ένα παλιότερο DLL από το Global Assembly Cache (GAC) ή από έναν προηγούμενο φάκελο κατασκευής. Σε αυτήν την περίπτωση, καθαρίστε τη λύση σας (`dotnet clean`) και ξαναχτίστε. + +--- + +## Βήμα 4: Ενσωμάτωση του Ελέγχου Έκδοσης στην Καταγραφή Παραγωγής + +Οι περισσότερες πραγματικές εφαρμογές δεν εκτυπώνουν μόνο στην κονσόλα· γράφουν σε αρχείο καταγραφής ή σύστημα τηλεμετρίας. Εδώ είναι ένα γρήγορο παράδειγμα χρησιμοποιώντας το `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Τώρα η έκδοση εμφανίζεται στα δομημένα logs σας, καθιστώντας εύκολο το φιλτράρισμα με `{Version}` αργότερα. Αυτό το μοτίβο είναι ιδιαίτερα χρήσιμο όταν έχετε πολλαπλές μικρο‑υπηρεσίες που ενδέχεται να φορτώνουν διαφορετικό OCR DLL. + +--- + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +### Τι γίνεται αν το `GetVersion()` επιστρέψει κενή συμβολοσειρά; + +Αυτό συνήθως υποδηλώνει κατεστραμμένη εγκατάσταση ή έλλειψη εγγενούς εξάρτησης. Επανεγκαταστήστε το πακέτο NuGet και βεβαιωθείτε ότι το `Aspose.OCR.Native.dll` (ή το αντίστοιχο δυαδικό για την πλατφόρμα) βρίσκεται δίπλα στο εκτελέσιμο σας. + +### Λειτουργεί η μέθοδος σε .NET Core 2.0; + +Ναι, το **Aspose OCR** υποστηρίζει .NET Standard 2.0 και νεότερο, έτσι οποιαδήποτε έκδοση .NET Core που υλοποιεί αυτό το πρότυπο μπορεί να καλέσει το `OcrEngine.GetVersion()`. Απλώς βεβαιωθείτε ότι αναφέρετε τα σωστά αναγνωριστικά runtime (`win-x64`, `linux-x64`, κλπ.) εάν δημοσιεύετε μια αυτόνομη εφαρμογή. + +### Μπορώ να ανακτήσω την έκδοση χωρίς αρχείο άδειας; + +Απολύτως. Το `GetVersion()` **δεν** απαιτεί άδεια· απλώς αναφέρει τον αριθμό κατασκευής της βιβλιοθήκης. Ωστόσο, εάν προσπαθήσετε να εκτελέσετε OCR χωρίς έγκυρη άδεια, θα λάβετε μια εξαίρεση χρόνου εκτέλεσης. Γι' αυτό το `try/catch` στο απόσπασμά μας είναι χρήσιμο—απομονώνει τον έλεγχο έκδοσης από τη ροή εκτέλεσης OCR. + +--- + +## Πλήρες Παράδειγμα Εργασίας (Έτοιμο για Αντιγραφή‑Επικόλληση) + +Παρακάτω βρίσκεται ολόκληρο το πρόγραμμα, έτοιμο να τοποθετηθεί σε ένα νέο έργο κονσόλας. Περιλαμβάνει το προαιρετικό μπλοκ καταγραφής, ώστε να δείτε τόσο την έξοδο κονσόλας όσο και τα δομημένα logs σε δράση. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Τρέξτε το με `dotnet run` και θα δείτε δύο γραμμές που επιβεβαιώνουν την έκδοση, καθώς και μια γραμμή εντοπισμού σφαλμάτων εάν ενεργοποιήσετε το `LogLevel.Debug`. + +--- + +## Συμπέρασμα + +Καλύψαμε όλα όσα χρειάζεστε για να **αποκτήσετε την έκδοση Aspose OCR** σε περιβάλλον C# — από την εγκατάσταση της **βιβλιοθήκης Aspose OCR**, την κλήση της μεθόδου **ocrengine getversion**, τη διαχείριση σφαλμάτων, έως την ενσωμάτωση του αποτελέσματος σε καταγραφή επιπέδου παραγωγής. Εξοπλισμένοι με αυτή τη γνώση, μπορείτε πλέον να επαληθεύετε αξιόπιστα την ακριβή έκδοση OCR που χρησιμοποιεί η εφαρμογή σας, να αποφεύγετε σφάλματα σχετιζόμενα με εκδόσεις και να ικανοποιείτε απαιτήσεις συμμόρφωσης χωρίς κόπο. + +Επόμενα βήματα; Δοκιμάστε να συνδυάσετε αυτόν τον έλεγχο έκδοσης με μια πραγματική κλήση OCR (`OcrEngine` → `RecognizeImage`) και καταγράψτε τόσο την έκδοση όσο και το αποτέλεσμα αναγνώρισης. Μπορείτε επίσης να εξερευνήσετε το μοτίβο **retrieve aspose version** για άλλα προϊόντα Aspose (PDF, Slides, Cells) ώστε να διατηρείτε ολόκληρη τη σουίτα σας συγχρονισμένη. + +Καλό κώδικα, και εύχομαι οι OCR αγωγοί σας να παραμείνουν οξυοδόντες! + +## Τι Θα Μάθετε Στη Σύντομη Μελλοντική; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/greek/net/ocr-optimization/_index.md index afd528c89..5b6aade85 100644 --- a/ocr/greek/net/ocr-optimization/_index.md +++ b/ocr/greek/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ weight: 25 Αυξήστε την ακρίβεια OCR με Aspose.OCR for .NET. Διορθώστε ορθογραφικά λάθη, προσαρμόστε λεξικά και επιτύχετε αναγνώριση κειμένου χωρίς σφάλματα με ευκολία. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) Αποκτήστε το πλήρες δυναμικό του Aspose.OCR for .NET. Αποθηκεύστε άνετα πολυσέλιδα αποτελέσματα OCR ως έγγραφα με αυτόν τον ολοκληρωμένο βήμα‑βήμα οδηγό. +### [Παράδειγμα Aspose OCR C# – Ενεργοποίηση GPU, Ορισμός Ορίου Μνήμης & Επεξεργασία Αρχείων TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Μάθετε πώς να ενεργοποιήσετε την GPU, να ορίσετε όριο μνήμης και να επεξεργαστείτε εικόνες TIF με Aspose OCR σε C#. ## Συχνές Ερωτήσεις diff --git a/ocr/greek/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/greek/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..2e0cf8486 --- /dev/null +++ b/ocr/greek/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-03 +description: Παράδειγμα Aspose OCR σε C# που δείχνει πώς να ορίσετε όριο μνήμης GPU, + να φορτώσετε εικόνα για OCR και να αναγνωρίσετε κείμενο από αρχεία TIF με πλήρη + κώδικα και συμβουλές. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: el +og_description: 'Μάθετε ένα πλήρες παράδειγμα Aspose OCR C#: ενεργοποίηση GPU, ορισμός + ορίου μνήμης GPU, φόρτωση εικόνας για OCR και αναγνώριση κειμένου από αρχεία TIF. + Περιλαμβάνεται ο πλήρης κώδικας.' +og_title: Παράδειγμα Aspose OCR C# – Επιτάχυνση GPU, Όριο Μνήμης & Επεξεργασία TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Παράδειγμα Aspose OCR C# – Ενεργοποίηση GPU, Ορισμός ορίου μνήμης & Επεξεργασία + εικόνων TIF +url: /el/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Παράδειγμα Aspose OCR C# – Ενεργοποίηση GPU, Ορισμός Ορίου Μνήμης & Επεξεργασία Εικόνων TIF + +Έχετε αναρωτηθεί ποτέ πώς να εξάγετε την μέγιστη απόδοση από τον κώδικα **Aspose OCR C# example** όταν εργάζεστε με τεράστιες σάρωση TIFF; Δεν είστε μόνοι. Σε πολλά πραγματικά έργα—π.χ. ψηφιοποίηση αρχείων ή εξαγωγή δεδομένων από αποδείξεις υψηλής ανάλυσης—το στενό λαιμό δεν είναι ο αλγόριθμος OCR, αλλά η αξιοποίηση του υλικού. + +Εδώ είναι το θέμα: το Aspose OCR υποστηρίζει επιτάχυνση GPU, αλλά πρέπει να του πείτε ακριβώς πόση μνήμη μπορεί να χρησιμοποιήσει, να φορτώσετε τον σωστό τύπο εικόνας και, τέλος, να εξάγετε το αναγνωρισμένο κείμενο από ένα αρχείο .tif. Αυτό το tutorial σας καθοδηγεί βήμα‑βήμα, από την εγκατάσταση του SDK μέχρι τη ρύθμιση του GPU, ώστε να τρέχετε OCR με αστραπιαία ταχύτητα χωρίς να εξαντλείτε τη μνήμη της GPU. + +Θα προσθέσουμε επίσης μερικά σενάρια “τι γίνεται αν” — όπως η διαχείριση πολυ‑σελίδων TIFF ή η επιστροφή στη CPU όταν δεν υπάρχει GPU — ώστε να καταλήξετε με μια αξιόπιστη λύση, όχι μόνο με ένα αποσπασματικό κομμάτι κώδικα. + +## Τι Θα Χρειαστείτε + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε τα παρακάτω στη μηχανή σας: + +| Προαπαιτούμενο | Γιατί είναι σημαντικό | +|----------------|-----------------------| +| **.NET 6 SDK** (ή νεότερο) | Το Aspose OCR στοχεύει στο .NET Standard 2.0+, επομένως οποιαδήποτε πρόσφατη έκδοση του .NET λειτουργεί. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | Η κύρια βιβλιοθήκη που παρέχει `OcrEngine`, `GpuSettings`, κ.λπ. | +| **CUDA 11+** (NVIDIA) **ή ROCm 5+** (AMD) | Απαιτείται για επιτάχυνση GPU· το SDK θα ελέγξει για συμβατό οδηγό κατά την εκτέλεση. | +| Μια **GPU με τουλάχιστον 2 GB VRAM** (θα περιορίσουμε στα 2048 MB) | Χωρίς αρκετή μνήμη, η μηχανή μπορεί να επιστρέψει σιωπηλά στη CPU. | +| Μια **υψηλής ανάλυσης εικόνα TIFF** που θέλετε να επεξεργαστείτε | Το Aspose OCR μπορεί να διαβάσει σχεδόν οποιαδήποτε μορφή raster, αλλά το TIF είναι κοινό για σάρωση. | +| Visual Studio 2022 (ή οποιονδήποτε επεξεργαστή προτιμάτε) | Για τη δημιουργία και αποσφαλμάτωση του έργου C#. | + +Αν λείπει κάποιο από αυτά, ο κώδικας θα μεταγλωττιστεί, αλλά δεν θα δείτε τις επιδόσεις που επιδιώκουμε. + +## Βήμα 1: Δημιουργία της Μηχανής Aspose OCR C# Example + +Το πρώτο βήμα σε κάθε **Aspose OCR C# example** είναι η δημιουργία μιας στιγμής του OCR engine. Σκεφτείτε το `OcrEngine` ως τον σκηνοθέτη μιας ταινίας — συντονίζει τα πάντα, από τη φόρτωση της εικόνας μέχρι την εξαγωγή του κειμένου. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** Αν σκοπεύετε να επεξεργαστείτε πολλές εικόνες διαδοχικά, κρατήστε ζωντανή μια μόνο `OcrEngine`. Η επανδημιουργία της για κάθε εικόνα προσθέτει επιπλέον φόρτο που μπορεί να υπερκαλύψει τον χρόνο OCR. + +## Βήμα 2: Ορισμός Ορίου Μνήμης GPU (και Ενεργοποίηση Επιτάχυνσης) + +Τώρα έρχεται το μέρος που συχνά προκαλεί προβλήματα: **ορισμός ορίου μνήμης GPU**. Από προεπιλογή, το Aspose OCR θα προσπαθήσει να χρησιμοποιήσει όλη τη διαθέσιμη VRAM, κάτι που σε κοινόχρηστη σταθμό εργασίας μπορεί να στερήσει άλλες εφαρμογές από πόρους. Το αντικείμενο `GpuSettings` σας επιτρέπει να περιορίσετε αυτήν την εκχώρηση. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Γιατί να ορίσετε όριο μνήμης; + +- **Stability:** Αποτρέπει καταρρίψεις λόγω έλλειψης μνήμης όταν επεξεργάζεστε τεράστιες εικόνες. +- **Co‑existence:** Επιτρέπει σε άλλες εφαρμογές βαριάς χρήσης GPU (π.χ. μοντέλα TensorFlow) να λειτουργούν παράλληλα. +- **Predictability:** Κάνει τις δοκιμές απόδοσης επαναλήψιμες, επειδή η GPU δεν θα ξεκινήσει ανταλλαγή (swapping). + +Αν παραλείψετε το `MemoryLimitMb`, το Aspose θα εκχωρήσει ό,τι κρίνει απαραίτητο, κάτι που μπορεί να είναι εντάξει σε dedicated server, αλλά είναι ριψοκίνδυνο σε φορητό υπολογιστή προγραμματιστή. + +## Βήμα 3: Φόρτωση Εικόνας για OCR + +Η φόρτωση του σωστού τύπου αρχείου είναι το επόμενο κρίσιμο βήμα. Η μέθοδος `OcrImage.FromFile` ανιχνεύει αυτόματα τον τύπο της εικόνας, αλλά θα πρέπει να ελέγξετε ότι το αρχείο υπάρχει και ότι είναι μια υποστηριζόμενη παραλλαγή TIFF (π.χ. LZW‑compressed ή CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Διαχείριση πολυ‑σελίδων TIFF + +Αν το TIFF σας περιέχει πολλές σελίδες, το Aspose OCR θα διαβάσει μόνο την πρώτη από προεπιλογή. Για να επεξεργαστείτε όλες τις σελίδες, μπορείτε να κάνετε βρόχο πάνω στο `image.Pages` (διαθέσιμο σε νεότερες εκδόσεις SDK) και να περάσετε κάθε σελίδα στη μηχανή ξεχωριστά. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Το παραπάνω απόσπασμα δείχνει ένα πρότυπο **load image for OCR** που λειτουργεί τόσο για μονο‑ όσο και για πολυ‑σελίδες αρχεία. + +## Βήμα 4: Αναγνώριση Κειμένου από TIF (ή οποιοδήποτε raster) + +Τώρα που η εικόνα βρίσκεται στη μνήμη, ζητάμε από το Aspose να κάνει τη μαγεία του. Η μέθοδος `Recognize` επιστρέφει ένα `OcrResult` που περιέχει το απλό κείμενο, τις βαθμολογίες εμπιστοσύνης και ακόμη πληροφορίες bounding‑box αν τις χρειάζεστε. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Γιατί αυτό λειτουργεί καλά με TIF + +- **Lossless compression:** Τα TIFF συχνά αποθηκεύουν ακατέργαστα δεδομένα εικονοστοιχείων, παρέχοντας στην μηχανή OCR τη μέγιστη πιστότητα. +- **Multiple color spaces:** Το Aspose μπορεί να διαχειριστεί grayscale, RGB ή ακόμη και CMYK TIFF χωρίς επιπλέον κώδικα μετατροπής. + +Αν χρειάζεται να ρυθμίσετε πακέτα γλώσσας (π.χ. Γαλλικά ή Ιαπωνικά), ορίστε `ocrEngine.Settings.Language = "fr"` πριν καλέσετε το `Recognize`. + +## Βήμα 5: Εμφάνιση του Αναγνωρισμένου Κειμένου + +Τέλος, εκτυπώνουμε το κείμενο στην κονσόλα. Σε μια πραγματική εφαρμογή μπορεί να γράψετε σε βάση δεδομένων, σε αρχείο JSON ή να περάσετε τη συμβολοσειρά σε επόμενη διαδικασία NLP. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Αναμενόμενη έξοδος + +Εκτελώντας το πρόγραμμα σε μια καθαρή σάρωση 300 dpi μιας τυπωμένης σελίδας συνήθως παίρνετε κάτι σαν: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Αν η εικόνα είναι θολή ή το όριο μνήμης GPU είναι πολύ χαμηλό, μπορεί να δείτε ακατάστατους χαρακτήρες ή κομμένο αποτέλεσμα. Η μείωση του `MemoryLimitMb` κάτω από το αποτύπωμα της εικόνας (συχνά ~1 GB για TIFF 6000×8000 pixel) μπορεί να κάνει τη μηχανή να επιστρέψει αυτόματα στη CPU. + +## Πλήρες Παράδειγμα Λειτουργίας + +Παρακάτω είναι το πλήρες, έτοιμο‑για‑εκτέλεση πρόγραμμα. Αντιγράψτε‑και‑επικολλήστε το σε ένα νέο Console App project, αντικαταστήστε `YOUR_DIRECTORY/large_photo.tif` με τη διαδρομή του δικού σας TIFF και πατήστε **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Γρήγορη λίστα ελέγχου + +- ✅ **Aspose OCR C# example** compiled without errors. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** set to 2048 MB. +- ✅ **Image loaded** from a TIF file. +- ✅ **Text recognized** and printed. + +## Συνηθισμένα Προβλήματα & Πώς να τα Αποφύγετε + +| Σύμπτωμα | Πιθανή αιτία | Διόρθωση | +|----------|--------------|----------| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA runtime not installed or version mismatch. | Install CUDA 11.x (or 12.x) matching your driver. | +| OCR returns empty string | Image is too dark or DPI < 150. | Pre‑process with `image.AdjustContrast()` or resample to 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` too low for the image. | Raise the limit or split the image into tiles via `image.Crop`. | +| `Unsupported image format` error | TIFF uses an exotic compression (e.g., JPEG‑2000). | Convert the TIFF to a supported format with ImageMagick before OCR. | + +## Επέκταση της Επίδειξης + +Τώρα που έχετε ένα σταθερό **aspose ocr c# example**, ίσως θέλετε να εξερευνήσετε: + +- **Batch processing:** Loop over a folder of TIFs, write each result to a `.txt` file. +- **Language packs:** `ocrEngine.Settings.Language = "es"` for Spanish, or load custom dictionaries. +- **Bounding boxes:** Use `ocrResult.Regions` to get coordinates for each word—handy for redaction tools. +- **CPU fallback:** Wrap the GPU block in a try/catch; on failure, set `ocrEngine.Settings.Gpu.Enable = false` and retry. + +These extensions keep the core pattern intact while adding value for specific use‑ + +## Τι Θα Μάθετε Στη Σύντομη Μελλοντική; + +Οι παρακάτω οδηγίες καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να κατακτήσετε πρόσθετες δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στην δική σας υλοποίηση. + +- [Εξαγωγή Κειμένου από Εικόνα Χρησιμοποιώντας Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Εξαγωγή Κειμένου από Εικόνα – Βελτιστοποίηση OCR με Aspose.OCR για .NET](/ocr/english/net/ocr-optimization/) +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/skew-angle-calculation/_index.md b/ocr/greek/net/skew-angle-calculation/_index.md index da9d4d220..ba9a6c2a6 100644 --- a/ocr/greek/net/skew-angle-calculation/_index.md +++ b/ocr/greek/net/skew-angle-calculation/_index.md @@ -32,7 +32,7 @@ url: /el/net/skew-angle-calculation/ ## [Υπολογίστε τη γωνία κλίσης από το URI στην Αναγνώριση εικόνας OCR](./calculate-skew-angle-from-uri/) Ενσωματώστε εύκολα το Aspose.OCR για .NET στα έργα σας και βελτιώστε την αναγνώριση εικόνων OCR. Το σεμινάριο μας για τον υπολογισμό των γωνιών λοξής από URI σάς δίνει τη δυνατότητα να φέρετε την ακρίβεια και την αποτελεσματικότητα στο προσκήνιο. Μείνετε μπροστά στο αναπτυξιακό σας ταξίδι! -Εν κατακλείδι, τα σεμινάρια υπολογισμού λοξής γωνίας μας χρησιμεύουν ως πυξίδα σας στον τομέα της αναγνώρισης εικόνων OCR. Είτε είστε λάτρης της C# είτε λάτρης της Java, το Aspose.OCR σάς εξοπλίζει με τα εργαλεία για να κατακτήσετε λοξές γωνίες και να ανυψώσετε τα έργα σας σε νέα ύψη. Εξερευνήστε, μάθετε και φέρτε την επανάσταση στο αναπτυξιακό σας ταξίδι μαζί μας! +Εν κατακλείδι, τα σεμινάρια υπολογμού λοξής γωνίας μας χρησιμεύουν ως πυξίδα σας στον τομέα της αναγνώρισης εικόνων OCR. Είτε είστε λάτρης της C# είτε λάτρης της Java, το Aspose.OCR σάς εξοπλίζει με τα εργαλεία για να κατακτήσετε λοξές γωνίες και να ανυψώσετε τα έργα σας σε νέα ύψη. Εξερευνήστε, μάθετε και φέρτε την επανάσταση στο αναπτυξιακό σας ταξίδι μαζί μας! ## Σεμινάρια υπολογισμού γωνίας λοξής ### [Υπολογίστε τη γωνία κλίσης στην Αναγνώριση εικόνας OCR](./calculate-skew-angle/) Εξερευνήστε το Aspose.OCR για .NET, μια ισχυρή λύση OCR για ακριβή αναγνώριση κειμένου στις εφαρμογές σας C#. @@ -40,9 +40,11 @@ url: /el/net/skew-angle-calculation/ Απελευθερώστε τη δύναμη του Aspose.OCR για .NET, μια ισχυρή λύση για την αναγνώριση εικόνων. Μάθετε πώς να υπολογίζετε τις γωνίες λοξής χωρίς κόπο. ### [Υπολογίστε τη γωνία κλίσης από το URI στην Αναγνώριση εικόνας OCR](./calculate-skew-angle-from-uri/) Εξερευνήστε το Aspose.OCR για .NET για να υπολογίσετε εύκολα τις γωνίες λοξής στην αναγνώριση εικόνας OCR. Βελτιώστε τα έργα σας με ακρίβεια και αποτελεσματικότητα. +### [Οδηγός OCR για Περιστραμμένο Έγγραφο – Αυτόματη Διόρθωση Λοξότητας & Περιστροφής σε C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Μάθετε πώς να εντοπίζετε και να διορθώνετε αυτόματα τη λοξότητα και την περιστροφή σε έγγραφα OCR χρησιμοποιώντας το Aspose.OCR για .NET σε C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/greek/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..3f8bd971b --- /dev/null +++ b/ocr/greek/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Οδηγός OCR για περιστραμμένο έγγραφο που δείχνει πώς να διορθώσετε αυτόματα + την κλίση και να εντοπίσετε την περιστροφή χρησιμοποιώντας το Aspose OCR σε C#. + Μάθετε βήμα‑βήμα με πλήρη κώδικα. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: el +og_description: Το σεμινάριο OCR για περιστραμμένο έγγραφο σας διδάσκει πώς να διορθώνετε + αυτόματα την κλίση και να ανιχνεύετε την περιστροφή χρησιμοποιώντας το Aspose OCR + σε C#. Ακολουθήστε τον πλήρη οδηγό. +og_title: Οδηγός OCR για Περιστραμμένο Έγγραφο – Αυτόματη Διόρθωση Στρέψης & Περιστροφής + σε C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Οδηγός OCR για Περιστρεφόμενα Έγγραφα – Αυτόματη Διόρθωση Κλίσης & Περιστροφής + σε C# +url: /el/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Οδηγός OCR για Περιστρεφόμενα Έγγραφα – Πλήρης Εγχειρίδιο για Προγραμματιστές C# + +Έχετε ποτέ βρεθεί αντιμέτωποι με ένα **ocr rotated document tutorial** όταν μια σαρωμένη φόρμα ήρθε πλαγίως ή λοξά; Δεν είστε μόνοι. Αυτές οι παραμορφωμένες εικόνες μπορούν να χαλάσουν την καθαρή εξαγωγή κειμένου, αλλά το καλό νέο είναι ότι το Aspose OCR μπορεί να τα διορθώσει αυτόματα. + +Σε αυτόν τον οδηγό βήμα‑βήμα θα δημιουργήσουμε ένα `OcrEngine`, θα ενεργοποιήσουμε την **automatic skew correction** και την **auto detect rotation**, θα τρέξουμε τη μηχανή σε μια περιστρεφόμενη εικόνα και θα εκτυπώσουμε το καθαρό κείμενο. Στο τέλος θα γνωρίζετε ακριβώς γιατί κάθε ρύθμιση είναι σημαντική, πώς να την προσαρμόσετε για ειδικές περιπτώσεις, και θα έχετε ένα έτοιμο προς εκτέλεση πρόγραμμα C#. + +## Τι Θα Μάθετε + +* Πώς να εγκαταστήσετε και να αναφέρετε το **Aspose OCR** σε ένα έργο .NET. +* Γιατί η ενεργοποίηση των `AutoCorrectSkew` και `AutoDetectRotation` είναι το κλειδί για ένα αξιόπιστο **ocr rotated document tutorial**. +* Πώς να φορτώσετε οποιαδήποτε εικόνα (JPG, PNG, TIFF) και να αφήσετε τη μηχανή να κάνει τη βαριά δουλειά. +* Συμβουλές για τη διαχείριση πολυσελίδων PDF, σαρώσεων χαμηλής ανάλυσης και προσαρμοσμένων πακέτων γλώσσας. + +> **Προαπαιτούμενα:** Visual Studio 2022 (ή οποιοδήποτε IDE C#), .NET 6+ runtime, και μια έγκυρη άδεια Aspose OCR (ή η δωρεάν δοκιμή). Δεν απαιτείται προηγούμενη εμπειρία OCR. + +--- + +## Βήμα 1 – Εγκατάσταση Aspose OCR και Ρύθμιση του Έργου + +Πρώτα απ' όλα. Κατεβάστε το πακέτο NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Συμβουλή:** Εάν χρησιμοποιείτε δοκιμαστική άδεια, τοποθετήστε το αρχείο `Aspose.OCR.lic` στον ίδιο φάκελο με το εκτελέσιμο σας, ή καταχωρίστε το προγραμματιστικά με `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Δημιουργήστε μια νέα εφαρμογή κονσόλας: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Τώρα έχετε ένα καθαρό περιβάλλον για το **ocr rotated document tutorial** μας. + +## Βήμα 2 – Αρχικοποίηση του OCR Engine + +Η μηχανή είναι η καρδιά της διαδικασίας. Σκεφτείτε την ως ένα πολυεργαλείο για εξαγωγή κειμένου· χρειάζεται μόνο να της πείτε ποιες λειτουργίες να ενεργοποιήσετε. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Γιατί αυτές οι ρυθμίσεις;** + +* `AutoCorrectSkew` αναλύει τη βάση των χαρακτήρων και περιστρέφει την εικόνα ακριβώς όσο χρειάζεται ώστε οι γραμμές να είναι οριζόντιες. +* `AutoDetectRotation` εξετάζει τη συνολική προσανατολισμό (0°, 90°, 180°, 270°) και αναστρέφει τη σελίδα αν είναι ανάποδη. Χωρίς αυτές, η μηχανή θα διάβαζε “pɹᴉʍ” αντί για “word”. + +## Βήμα 3 – Φόρτωση της Εικόνας που Θέλετε να Επεξεργαστείτε + +Το Aspose OCR λειτουργεί με οποιαδήποτε κοινή μορφή raster. Αντικαταστήστε τη διαδρομή placeholder με την πραγματική θέση της περιστρεφόμενης φόρμας σας. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Ειδική περίπτωση:** Εάν λάβετε ένα πολυσελίδων TIFF, χρησιμοποιήστε `OcrImage.FromMultiPageTiff(filePath)` και κάντε βρόχο μέσω `image.Pages`. + +## Βήμα 4 – Εκτέλεση της Αναγνώρισης + +Τώρα η μηχανή κάνει τη μαγεία. Θα διορθώσει πρώτα την εικόνα (ευχαριστώντας τις σημαίες skew/rotation) και στη συνέχεια θα εξάγει τους χαρακτήρες. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Εάν χρειάζεστε υποστήριξη γλώσσας πέρα από τα Αγγλικά, ορίστε την πριν καλέσετε το `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Βήμα 5 – Έξοδος του Αναγνωρισμένου Κειμένου + +Τέλος, εκτυπώστε το καθαρό κείμενο στην κονσόλα—ή το δρομολογήστε σε αρχείο, βάση δεδομένων, ό,τι ταιριάζει στη ροή εργασίας σας. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Αναμενόμενη έξοδος** (υποθέτοντας ότι η δείγμα εικόνας περιέχει “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Παρατηρήστε πώς το κείμενο εμφανίζεται σωστά παρόλο που η αρχική εικόνα ήταν περιστραμμένη 90° και ελαφρώς λοξή. + +--- + +## Διαχείριση Συνηθισμένων Προβλημάτων + +| Πρόβλημα | Γιατί Συμβαίνει | Διόρθωση | +|------|----------------|-----| +| **Κενή έξοδος** | Η διόρθωση skew είναι απενεργοποιημένη ή η εικόνα είναι πολύ σκοτεινή. | Ενεργοποιήστε το `AutoCorrectSkew` (ήδη ενεργό) και αυξήστε την αντίθεση της εικόνας μέσω `image.AdjustContrast(1.2)`. | +| **Ασυνήθιστοι χαρακτήρες** | Λάθος ρύθμιση γλώσσας. | Ορίστε το `ocrEngine.Settings.Language` ώστε να ταιριάζει με τη γλώσσα του εγγράφου. | +| **Καθυστέρηση απόδοσης σε μεγάλα PDFs** | Η μηχανή επεξεργάζεται κάθε σελίδα διαδοχικά. | Χρησιμοποιήστε `Parallel.ForEach` στο `image.Pages` για να αξιοποιήσετε πολυπύρηνους επεξεργαστές. | +| **Αδυναμία άδειας** | Η δοκιμαστική άδεια έληξε. | Αποκτήστε μόνιμη άδεια ή παραμείνετε εντός των περιορισμών της δοκιμής (5 σελίδες ανά εκτέλεση). | + +## Συμβουλές για Ένα Αξιόπιστο OCR Rotated Document Tutorial + +* **Επεξεργασία παρτίδας:** Τυλίξτε όλη τη ροή σε μια μέθοδο που δέχεται διαδρομή φακέλου, διασχίζει κάθε εικόνα και γράφει κάθε αποτέλεσμα σε αρχείο `.txt`. +* **Προεπεξεργασία:** Μερικές φορές μια θορυβώδης σάρωση ωφελείται από `image.Denoise()` πριν την αναγνώριση. +* **Μεταεπεξεργασία:** Χρησιμοποιήστε κανονικές εκφράσεις για να καθαρίσετε κοινά σφάλματα OCR, π.χ., αντικαταστήστε το “0” με “O” μόνο όταν περιβάλλεται από γράμματα. +* **Καταγραφή:** Το Aspose OCR παρέχει το `ocrEngine.Logger` – συνδέστε το με έναν καταγραφέα αρχείων για να συλλάβετε προειδοποιήσεις σχετικά με χαμηλές βαθμολογίες εμπιστοσύνης. + +## Πλήρης, Έτοιμος‑για‑Εκτέλεση Κώδικας + +Αποθηκεύστε το παρακάτω ως `Program.cs` μέσα στο κονσόλα έργο σας. Περιλαμβάνει όλα τα βήματα, σχόλια, και έναν μικρό βοηθό για επεξεργασία παρτίδας. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Τρέξτε το: + +```bash +dotnet run +``` + +Θα πρέπει να δείτε το καθαρισμένο κείμενο να εκτυπώνεται στην κονσόλα, αποδεικνύοντας ότι το **ocr rotated document tutorial** μας λειτουργεί από άκρη σε άκρη. + +## Συμπέρασμα + +Τώρα έχετε ένα πλήρες **ocr rotated document tutorial** που διορθώνει αυτόματα το skew, εντοπίζει την περιστροφή και εξάγει καθαρό κείμενο χρησιμοποιώντας το Aspose OCR σε C#. Το βασικό συμπέρασμα; Η ενεργοποίηση του `AutoCorrectSkew` **και** του `AutoDetectRotation` μετατρέπει μια πολύ κεκλιμένη σάρωση σε τέλεια αναγνώσιμη έξοδο με λίγες μόνο γραμμές κώδικα. + +Από εδώ, μπορείτε να επεκτείνετε σε εργασίες παρτίδας, να ενσωματώσετε πακέτα γλώσσας, ή να τροφοδοτήσετε τα αποτελέσματα σε downstream pipelines ανάλυσης. Θέλετε να εξερευνήσετε περαιτέρω το **automatic skew correction**; Ρίξτε μια ματιά στο API προεπεξεργασίας εικόνας του Aspose, ή πειραματιστείτε με προσαρμοσμένα όρια για θορυβώδεις σαρώσεις. + +Έχετε ερωτήσεις σχετικά με τη διαχείριση PDF, πολυσελίδων TIFF, ή την ενσωμάτωση με Azure Functions; Αφήστε ένα σχόλιο, και καλή κωδικοποίηση! + +## Τι Θα Μάθετε Στη Σύντομη Μελλοντική Περίοδο; + +Τα παρακάτω tutorials καλύπτουν στενά σχετιζόμενα θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη λειτουργικό κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κατακτήσετε πρόσθετα χαρακτηριστικά του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στην δική σας υλοποίηση. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/greek/net/text-recognition/_index.md index 7c0b04e8c..a3f15e4d5 100644 --- a/ocr/greek/net/text-recognition/_index.md +++ b/ocr/greek/net/text-recognition/_index.md @@ -37,6 +37,9 @@ url: /el/net/text-recognition/ Ξεκλειδώστε τις δυνατότητες του OCR στο .NET με το Aspose.OCR. Εξάγετε κείμενο από αρχεία PDF χωρίς κόπο και ενσωματώστε απρόσκοπτα στις εφαρμογές σας. Αυτό το σεμινάριο παρέχει έναν περιεκτικό οδηγό για την αναγνώριση κειμένου σε PDF, διασφαλίζοντας μια απρόσκοπτη και αποτελεσματική εμπειρία ενσωμάτωσης. +### [Εκτέλεση OCR σε PDF με Aspose.OCR – Πλήρης Οδηγός C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Μάθετε πώς να εκτελείτε OCR σε αρχεία PDF χρησιμοποιώντας το Aspose.OCR με πλήρη οδηγό C# βήμα προς βήμα. + ## Αναγνώριση πίνακα στην Αναγνώριση εικόνας OCR Περιηγηθείτε στην πολυπλοκότητα της αναγνώρισης πινάκων στην αναγνώριση εικόνας OCR με το Aspose.OCR για .NET. Ο περιεκτικός οδηγός μας σάς δίνει τη δυνατότητα να ξεκλειδώσετε πλήρως τις δυνατότητες του Aspose.OCR, διασφαλίζοντας ακριβή και αποτελεσματική αναγνώριση πινάκων στις εφαρμογές σας. Αναβαθμίστε τα έργα σας με την κορυφαία στον κλάδο λύση OCR. @@ -55,9 +58,18 @@ url: /el/net/text-recognition/ Ξεκλειδώστε τις δυνατότητες του OCR στο .NET με το Aspose.OCR. Εξαγωγή κειμένου από αρχεία PDF χωρίς κόπο. Κάντε λήψη τώρα για μια απρόσκοπτη εμπειρία ενσωμάτωσης. ### [Αναγνώριση πίνακα στην Αναγνώριση εικόνας OCR](./recognize-table/) Ξεκλειδώστε τις δυνατότητες του Aspose.OCR για .NET με τον ολοκληρωμένο οδηγό μας για την αναγνώριση πινάκων στην αναγνώριση εικόνας OCR. +### [Εκτέλεση OCR σε εικόνα με Aspose OCR – Οδηγός Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Μάθετε πώς να εκτελέσετε OCR σε εικόνα με το Aspose OCR ακολουθώντας τον οδηγό στα Χίντι. +### [Εκτέλεση OCR σε εικόνα και ανίχνευση ορθογραφικών λαθών σε C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Μάθετε πώς να εκτελείτε OCR σε εικόνα και να εντοπίζετε ορθογραφικά λάθη χρησιμοποιώντας C# και Aspose.OCR. +### [Πώς να χρησιμοποιήσετε το Aspose: Μετατροπή εικόνας σε HTML με OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Μάθετε πώς να μετατρέψετε εικόνες σε HTML χρησιμοποιώντας το Aspose OCR σε βήμα-βήμα οδηγό. +### [OCR υπότιτλων βίντεο σε C# – Πλήρης Οδηγός](./video-subtitle-ocr-in-c-complete-guide/) +Μάθετε πώς να εξάγετε υπότιτλους βίντεο χρησιμοποιώντας Aspose.OCR σε C# με πλήρη βήμα-βήμα οδηγό. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/greek/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..524183d94 --- /dev/null +++ b/ocr/greek/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Πώς να χρησιμοποιήσετε το Aspose για να μετατρέψετε εικόνα σε HTML και + να εξάγετε κείμενο από εικόνα σε C#. Μάθετε πώς να δημιουργείτε HTML από εικόνα + και να κάνετε OCR εικόνας σε HTML γρήγορα. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: el +og_description: Πώς να χρησιμοποιήσετε το Aspose για να μετατρέψετε εικόνα σε HTML, + να εξάγετε κείμενο από εικόνα και να δημιουργήσετε HTML από εικόνα με OCR σε C#. + Ακολουθήστε αυτόν τον πλήρη οδηγό. +og_title: 'Πώς να χρησιμοποιήσετε το Aspose: Μετατροπή εικόνας σε HTML με OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Πώς να χρησιμοποιήσετε το Aspose: Μετατροπή εικόνας σε HTML με OCR' +url: /el/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να χρησιμοποιήσετε το Aspose: Μετατροπή εικόνας σε HTML με OCR + +Έχετε αναρωτηθεί ποτέ **πώς να χρησιμοποιήσετε το Aspose** για να μετατρέψετε μια σαρωμένη εικόνα σε καθαρό HTML; Ίσως έχετε μια σελίδα περιοδικού, μια απόδειξη ή ένα χειρόγραφο σημείωμα και χρειάζεστε το κείμενο και τη διάταξη να διατηρηθούν για δημοσίευση στο web. Τα καλά νέα είναι ότι δεν χρειάζεται να γράψετε έναν προσαρμοσμένο parser ή να ασχοληθείτε με επεξεργασία εικόνας χαμηλού επιπέδου—το Aspose.OCR κάνει τη σκληρή δουλειά για εσάς. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα **πλήρες, εκτελέσιμο παράδειγμα** που δείχνει πώς να **convert image to HTML**, **extract text from image**, και **generate HTML from image** χρησιμοποιώντας τη βιβλιοθήκη Aspose OCR σε C#. Στο τέλος θα έχετε μια μικρή εφαρμογή console που παράγει ένα αρχείο HTML με τη διατήρηση της αρχικής διάταξης της σελίδας, έτοιμο να ενσωματωθεί σε οποιονδήποτε ιστότοπο. + +## Απαιτούμενα + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε τα εξής στον υπολογιστή σας: + +- **.NET 6.0 SDK** ή νεότερο (ο κώδικας λειτουργεί τόσο με .NET Core όσο και με .NET Framework). +- **Visual Studio 2022** (ή οποιονδήποτε επεξεργαστή προτιμάτε). +- **Aspose.OCR for .NET** – εγκαταστήστε μέσω NuGet: `dotnet add package Aspose.OCR`. +- Ένα αρχείο εικόνας (JPEG/PNG) που θέλετε να μετατρέψετε, π.χ., `magazine_page.jpg`. + +Δεν απαιτούνται επιπλέον αρχεία ρυθμίσεων· η βιβλιοθήκη περιλαμβάνει όλα όσα χρειάζονται για OCR και δημιουργία HTML διάταξης. + +## Βήμα 1: Ρύθμιση του έργου και προσθήκη του Aspose.OCR + +Πρώτα, δημιουργήστε ένα νέο project console και προσθέστε το πακέτο Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Αν χρησιμοποιείτε Visual Studio, απλώς κάντε δεξί‑κλικ στο project → *Manage NuGet Packages* → αναζητήστε **Aspose.OCR** και εγκαταστήστε το. Αυτό το βήμα εξασφαλίζει ότι μπορείτε να **ocr image to html** χωρίς ελλείψεις αναφορών. + +## Βήμα 2: Αρχικοποίηση του μηχανήματος OCR + +Ο πυρήνας της διαδικασίας είναι η κλάση `OcrEngine`. Σκεφτείτε το ως τον εγκέφαλο που διαβάζει την εικόνα και αποφασίζει πώς θα παραχθεί το αποτέλεσμα. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Εδώ δημιουργούμε ένα αντικείμενο `OcrEngine`. Δεν χρειάζεται να περάσετε διαπιστευτήρια για τη δωρεάν έκδοση· η βιβλιοθήκη θα χρησιμοποιήσει τα ενσωματωμένα μοντέλα αναγνώρισης. + +## Βήμα 3: Φόρτωση της πηγαίας εικόνας + +Στη συνέχεια, δείξτε στο engine το αρχείο που θέλετε να επεξεργαστείτε. Το Aspose παρέχει τη βολική μέθοδο `OcrImage.FromFile` που υποστηρίζει τις περισσότερες μορφές εικόνας. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Αντικαταστήστε το `YOUR_DIRECTORY` με την απόλυτη ή σχετική διαδρομή όπου βρίσκεται η εικόνα σας. Αν η εικόνα βρίσκεται στον ίδιο φάκελο με το εκτελέσιμο, μπορείτε απλώς να χρησιμοποιήσετε `"magazine_page.jpg"`. + +## Βήμα 4: Αναγνώριση και αίτηση HTML με διάταξη + +Αυτή είναι η καρδιά του tutorial. Με το `OutputFormat.HtmlWithLayout` λέμε στο Aspose να **generate HTML from image** διατηρώντας την αρχική θέση των μπλοκ κειμένου, εικόνων και πινάκων. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Η ιδιότητα `recognitionResult.Text` περιέχει τώρα ένα πλήρες έγγραφο HTML. Αν χρειάζεστε μόνο απλό κείμενο, μπορείτε να χρησιμοποιήσετε `OutputFormat.Text`, αλλά εστιάζουμε στο **convert image to html** με πιστότητα διάταξης. + +## Βήμα 5: Αποθήκευση του αρχείου HTML + +Τέλος, γράψτε το string HTML στο δίσκο. Αυτό σας δίνει ένα έτοιμο‑για‑χρήση αρχείο που μπορείτε να ανοίξετε σε οποιονδήποτε περιηγητή. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Η εκτέλεση του προγράμματος θα παραγάγει το `magazine.html`. Ανοίξτε το και θα δείτε το κείμενο της αρχικής σελίδας τοποθετημένο ακριβώς όπως εμφανιζόταν στην πηγή—τέλειο για αρχειοθέτηση ή δημοσίευση στο web. + +## Πλήρες λειτουργικό παράδειγμα + +Παρακάτω είναι το **complete, copy‑paste‑ready** πρόγραμμα. Δεν λείπουν μέρη, ώστε να μπορείτε να το μεταγλωττίσετε και να το τρέξετε αμέσως μετά τον ορισμό των σωστών διαδρομών. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Αναμενόμενη έξοδος + +Όταν ανοίξετε το `magazine.html` σε έναν περιηγητή, θα πρέπει να δείτε κάτι παρόμοιο (απλοποιημένο για παράδειγμα): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Τα ακριβή `style` attributes θα διαφέρουν ανάλογα με την αρχική εικόνα, αλλά η δομή εγγυάται ότι **extract text from image** και **generate html from image** συμβαίνουν σε ένα ενιαίο, αδιάσπαστο βήμα. + +## Συχνές ερωτήσεις & ειδικές περιπτώσεις + +### Τι γίνεται αν η εικόνα είναι χαμηλής ανάλυσης; + +Το Aspose.OCR λειτουργεί καλύτερα με εικόνες που έχουν τουλάχιστον **300 DPI**. Αν το αρχείο σας είναι θολό, δοκιμάστε να το προεπεξεργαστείτε με μια βιβλιοθήκη βελτίωσης εικόνας (π.χ., ImageSharp) πριν το περάσετε στο OCR engine. Η χαμηλή ποιότητα μπορεί να επηρεάσει τόσο την **extract text from image** ακρίβεια όσο και την πιστότητα της παραγόμενης HTML διάταξης. + +### Μπορώ να ελέγξω τη γλώσσα του OCR; + +Ναι. Ορίστε την ιδιότητα `Language` στο `OcrEngine` πριν καλέσετε `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Αυτό βελτιώνει την αναγνώριση όταν εργάζεστε με μη‑αγγλικά χαρακτήρες. + +### Πώς μπορώ να λάβω απλό κείμενο αντί για HTML; + +Αν χρειάζεστε μόνο το ακατέργαστο string, αντικαταστήστε το `OutputFormat.HtmlWithLayout` με `OutputFormat.Text`. Η ίδια ιδιότητα `recognitionResult.Text` θα περιέχει τότε μόνο τους εξαγόμενους χαρακτήρες. + +### Υπάρχει τρόπος να ενσωματώσω εικόνες στο παραγόμενο HTML; + +Το Aspose.OCR μπορεί να ενσωματώσει την αρχική εικόνα ως base‑64 data URI όταν χρησιμοποιείτε `OutputFormat.HtmlWithLayoutAndImages`. Αυτό είναι χρήσιμο όταν θέλετε ένα ενιαίο αρχείο HTML χωρίς εξωτερικά assets. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Πώς να διαχειριστώ μεγάλες παρτίδες; + +Για επεξεργασία σε batch, τυλίξτε τη λογική σε έναν βρόχο `foreach` πάνω σε λίστα διαδρομών αρχείων. Η επαναχρησιμοποίηση του ίδιου αντικειμένου `OcrEngine` μειώνει το overhead και επιταχύνει το pipeline **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Συμβουλές για κώδικα έτοιμο για παραγωγή + +- **Dispose resources**: Τanto `OcrEngine` όσο και `OcrImage` υλοποιούν το `IDisposable`. Τυλίξτε τα σε δηλώσεις `using` για άμεση απελευθέρωση της εγγενούς μνήμης. +- **Error handling**: Πιάστε `IOException` για προβλήματα σχετιζόμενα με αρχεία και `OcrException` για ζητήματα αναγνώρισης. +- **Performance**: Αν επεξεργάζεστε πολλές εικόνες, σκεφτείτε την ενεργοποίηση **parallelism** (`Parallel.ForEach`) αλλά προσέξτε τη χρήση CPU—το OCR είναι απαιτητικό σε επεξεργαστική ισχύ. +- **Logging**: Ενσωματώστε έναν logger (π.χ., Serilog) για να καταγράψετε τα OCR confidence scores (`recognitionResult.Confidence`) για παρακολούθηση ποιότητας. + +## Συμπέρασμα + +Μόλις καλύψαμε **πώς να χρησιμοποιήσετε το Aspose** για **convert image to HTML**, **extract text from image**, και **generate HTML from image** σε λίγα απλά βήματα. Το πλήρες δείγμα κώδικα δείχνει πώς να **ocr image to html** διατηρώντας τη διάταξη, παρέχοντας μια σταθερή βάση για οποιοδήποτε έργο ψηφιοποίησης εγγράφων. + +Από εδώ μπορείτε: + +- Πειραματιστείτε με διαφορετικές επιλογές `OutputFormat` για να ταιριάζουν στις ανάγκες σας. +- Συνδυάστε το HTML αποτέλεσμα με ένα CSS framework για ανταποκρινόμενο στυλ. +- Ενσωματώστε το εξαγόμενο κείμενο σε ευρετήριο αναζήτησης ή σε pipeline μηχανικής μάθησης. + +Δοκιμάστε το, προσαρμόστε τις ρυθμίσεις, και δείτε πόσο εύκολα το Aspose μετατρέπει εικόνες σε περιεχόμενο έτοιμο για web. Αν αντιμετωπίσετε δυσκολίες, αφήστε ένα σχόλιο—καλή προγραμματιστική! + +![Διάγραμμα που δείχνει τη διαδικασία OCR από εικόνα σε διάταξη HTML – πώς να χρησιμοποιήσετε το Aspose](/images/ocr-pipeline.png "πώς να χρησιμοποιήσετε το aspose") + +--- + +## Τι πρέπει να μάθετε στη συνέχεια; + +Οι παρακάτω οδηγίες καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε επιπλέον δυνατότητες του API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας έργα. + +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Μετατροπή εικόνας σε κείμενο – Εκτέλεση OCR σε εικόνα από URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Αναγνώριση κειμένου εικόνας με 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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/greek/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..2b922623d --- /dev/null +++ b/ocr/greek/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-03 +description: Πραγματοποιήστε OCR σε εικόνα και εξάγετε κείμενο από την εικόνα χρησιμοποιώντας + το Aspose.OCR. Μάθετε πώς να εντοπίζετε λανθασμένες λέξεις και να λαμβάνετε προτάσεις + ορθογραφίας σε μια ενιαία επίδειξη C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: el +og_description: Εκτελέστε OCR σε εικόνα για να εξάγετε κείμενο από αυτήν, στη συνέχεια + εντοπίστε ορθογραφικά λάθη και λάβετε προτάσεις διόρθωσης με το Aspose.OCR σε C#. +og_title: Εκτελέστε OCR σε εικόνα και εντοπίστε λανθασμένες λέξεις σε C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Εκτέλεση OCR σε εικόνα και ανίχνευση ορθογραφικών λαθών σε C# +url: /el/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εκτέλεση OCR σε εικόνα και ανίχνευση λανθασμένων λέξεων σε C# + +Έχετε αναρωτηθεί ποτέ πώς να **εκτελέσετε OCR σε εικόνα** αρχεία χωρίς να τρελαίνεστε; Δεν είστε οι μόνοι. Είτε ψηφιοποιείτε παλιά γράμματα, σαρώνετε αποδείξεις, είτε δημιουργείτε μια έξυπνη ροή εργασίας εγγράφων, η εξαγωγή καθαρού κειμένου από εικόνες είναι το πρώτο εμπόδιο. Τα καλά νέα; Με το Aspose.OCR μπορείτε να δημιουργήσετε μια λύση σε λίγα λεπτά, και το επιπλέον είναι ότι μπορείτε επίσης **να ανιχνεύσετε λανθασμένες λέξεις** και **να λάβετε προτάσεις ορθογραφίας** στην ίδια εκτέλεση. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από μια πλήρη, έτοιμη‑για‑εκτέλεση C# κονσόλα εφαρμογή που **εξάγει κείμενο από εικόνα**, εκτελεί έναν αγγλικό ορθογραφικό ελεγκτή, και εκτυπώνει κάθε σφάλμα με χρήσιμες ιδέες διόρθωσης. Στο τέλος θα γνωρίζετε ακριβώς **πώς να εξάγετε κείμενο**, πώς να συνδέσετε το spell‑check API, και πώς φαίνεται η αναμενόμενη έξοδος της κονσόλας. + +## Τι θα δημιουργήσετε + +- Φορτώστε ένα bitmap (ή PNG) που περιέχει τυπογραφικά λάθη. +- Εκτελέστε το Aspose.OCR για **εκτελέσετε OCR σε εικόνα** και λάβετε ακατέργαστα δεδομένα συμβολοσειράς. +- Αρχικοποιήστε τον ενσωματωμένο αγγλικό ορθογραφικό ελεγκτή. +- **να ανιχνεύσετε λανθασμένες λέξεις** και **να λάβετε προτάσεις ορθογραφίας** για κάθε ένα. +- Εκτυπώστε μια τακτοποιημένη αναφορά στην κονσόλα. + +Χωρίς εξωτερικές υπηρεσίες, χωρίς περίπλοκες κλήσεις HTTP—μόνο ένα ενιαίο πακέτο NuGet και λίγες γραμμές κώδικα. + +## Προαπαιτούμενα + +- .NET 6.0 SDK ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+). +- Visual Studio 2022 (ή οποιονδήποτε επεξεργαστή προτιμάτε). +- Πακέτο NuGet Aspose.OCR για .NET (`Aspose.OCR`). +- Ένα αρχείο εικόνας (`letter_with_typos.png`) τοποθετημένο κάπου που μπορείτε να το αναφέρετε από το έργο. + +Αν δεν έχετε χρησιμοποιήσει ποτέ το Aspose, μην ανησυχείτε—η εγκατάσταση του πακέτου είναι τόσο εύκολη όσο η εκτέλεση: + +```bash +dotnet add package Aspose.OCR +``` + +Τώρα ας βουτήξουμε στην υλοποίηση. + +## Βήμα 1: Ρύθμιση του έργου και εγκατάσταση του Aspose.OCR + +Δημιουργήστε ένα νέο έργο κονσόλας και προσθέστε τη βιβλιοθήκη OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Αφού ολοκληρωθεί η επαναφορά, ανοίξτε το `Program.cs`. Θα αντικαταστήσουμε το προεπιλεγμένο περιεχόμενο με τον πλήρη κώδικα επίδειξης αργότερα, αλλά πρώτα ας συζητήσουμε γιατί κάθε namespace είναι σημαντικό. + +- `Aspose.OCR` – Πυρήνας μηχανής OCR και διαχείριση εικόνων. +- `Aspose.OCR.SpellCheck` – Εργαλεία ορθογραφικού ελέγχου που παρέχονται με τη βιβλιοθήκη. +- `System` – Πρότυπες βασικές κλάσεις .NET (π.χ., `Console`). + +## Βήμα 2: Φόρτωση της εικόνας και εκτέλεση OCR σε εικόνα + +Η πρώτη πραγματική εργασία είναι η παροχή της εικόνας στη μηχανή OCR. Το Aspose.OCR διαβάζει πολλές μορφές (PNG, JPEG, TIFF). Εδώ είναι το απόσπασμα κώδικα που κάνει τη βαριά δουλειά: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Γιατί είναι σημαντικό:** `OcrImage.FromFile` αφαιρεί τις λεπτομέρειες σε επίπεδο pixel, ενώ `OcrEngine.Recognize` εκτελεί το εκπαιδευμένο νευρωνικό μοντέλο που μετατρέπει τα οπτικά σύμβολα σε χαρακτήρες Unicode. Η ιδιότητα `ocrResult.Text` τώρα περιέχει την ακατέργαστη συμβολοσειρά—ακριβώς ό,τι χρειάζεστε για **εξάγετε κείμενο από εικόνα**. +> **Συμβουλή:** Εάν η εικόνα σας περιέχει πολλαπλές γλώσσες, μπορείτε να ορίσετε `ocrEngine.Language = OcrLanguage.Multilingual;` πριν καλέσετε το `Recognize`. + +## Βήμα 3: Αρχικοποίηση του αγγλικού Spell‑Checker + +Το Aspose.OCR περιλαμβάνει μια ενσωματωμένη μηχανή ορθογραφικού ελέγχου που καταλαβαίνει τα Αγγλικά αμέσως. Η αρχικοποίησή της γίνεται με μία γραμμή: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Γιατί αυτό το βήμα είναι κρίσιμο:** Η έξοδος OCR μπορεί να περιλαμβάνει λανθασμένα αναγνωρισμένους χαρακτήρες (π.χ., “l” vs “1”) ή πραγματικά τυπογραφικά λάθη από το αρχικό έγγραφο. Ο ορθογραφικός ελεγκτής θα σαρώσει τη συμβολοσειρά, θα εντοπίσει ύποπτα tokens, και θα προτείνει εναλλακτικές. + +## Βήμα 4: Ανίχνευση λανθασμένων λέξεων και λήψη προτάσεων ορθογραφίας + +Τώρα τροφοδοτούμε το κείμενο OCR στον ελεγκτή: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` είναι μια συλλογή όπου κάθε καταχώρηση περιέχει τη λανθασμένη λέξη και έναν πίνακα πιθανών διορθώσεων. + +## Βήμα 5: Εξαγωγή των αποτελεσμάτων + +Τέλος, επαναλαμβάνουμε τη συλλογή και εκτυπώνουμε μια αναφορά φιλική προς τον χρήστη: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Αναμενόμενη έξοδος κονσόλας + +Υποθέτοντας ότι το `letter_with_typos.png` περιέχει την πρόταση: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Η εκτέλεση της επίδειξης θα παράγει κάτι όπως: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Παρατηρήστε πώς κάθε τυπογραφικό λάθος συνδυάζεται με μια σειρά πιθανών διορθώσεων—ακριβώς ό,τι χρειάζεστε όταν δημιουργείτε ένα φιλικό προς το χρήστη UI διόρθωσης. + +## Πλήρες λειτουργικό παράδειγμα + +Παρακάτω βρίσκεται το **πλήρες, έτοιμο για αντιγραφή‑επικόλληση** πρόγραμμα. Αντικαταστήστε το `YOUR_DIRECTORY` με την πραγματική διαδρομή του αρχείου εικόνας σας. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Περιπτώσεις Άκρων προς εξέταση** +> - **Κενή εικόνα:** Εάν η μηχανή OCR επιστρέψει μια κενή συμβολοσειρά, το `spellChecker.Check` θα επιστρέψει απλώς μια κενή συλλογή—χωρίς κατάρρευση. +> - **Μη‑Αγγλικό κείμενο:** Αντικαταστήστε το `OcrLanguage.English` με `OcrLanguage.French` (ή οποιαδήποτε υποστηριζόμενη γλώσσα) για **να ανιχνεύσετε λανθασμένες λέξεις** σε άλλες περιοχές. +> - **Μεγάλα έγγραφα:** Για PDF πολλαπλών σελίδων, θα επαναλάβετε για κάθε σελίδα, θα εκτελέσετε OCR, και στη συνέχεια θα συγκεντρώσετε τα αποτελέσματα πριν τον ορθογραφικό έλεγχο. + +## Οπτική επισκόπηση (Κείμενο alt εικόνας) + +![Διάγραμμα που δείχνει τη ροή για εκτέλεση OCR σε εικόνα, εξαγωγή κειμένου από εικόνα, και στη συνέχεια ανίχνευση λανθασμένων λέξεων με προτάσεις ορθογραφίας](perform-ocr-on-image-flow.png) + +*Το παραπάνω διάγραμμα απεικονίζει τη διαδικασία από άκρη σε άκρη: εικόνα → μηχανή OCR → ακατέργαστο κείμενο → ορθογραφικός ελεγκτής → προτάσεις.* + +## Συχνές ερωτήσεις & Συμβουλές Pro + +| Ερώτηση | Απάντηση | +|----------|--------| +| **Χρειάζομαι σύνδεση στο internet;** | Όχι. Το Aspose.OCR λειτουργεί εξ ολοκλήρου τοπικά· ιδανικό για περιβάλλοντα εκτός σύνδεσης ή ασφαλή. | +| **Πόσο ακριβής είναι ο ορθογραφικός ελεγκτής;** | Χρησιμοποιεί λεξικό περίπου 150k αγγλικών λέξεων και ασαφή αντιστοίχιση, έτσι τα περισσότερα κοινά τυπογραφικά λάθη εντοπίζονται. | +| **Μπορώ να προσαρμόσω το λεξικό;** | Ναι. `SpellChecker.AddUserDictionary("custom.txt")` σας επιτρέπει να φορτώσετε όρους ειδικούς για το domain (π.χ., ονόματα προϊόντων). | +| **Τι γίνεται αν η εικόνα είναι κεκλιμένη;** | Η μηχανή OCR ανιχνεύει αυτόματα τον προσανατολισμό, αλλά μπορείτε να καλέσετε χειροκίνητα `ocrEngine.ImagePreprocessing.Rotate(angle)` για επίμονες περιπτώσεις. | +| **Υπάρχει τρόπος να επισημάνω τις προτάσεις στο UI;** | Αφού έχετε τη συλλογή `misspellings`, μπορείτε να αντιστοιχίσετε κάθε `entry.Word` στην θέση του στο `ocrResult.Text` και να το υπογραμμίσετε σε RichTextBox ή web view. | + +## Συμπέρασμα + +Μόλις σας δείξαμε **πώς να εκτελέσετε OCR σε εικόνα**, **πώς να εξάγετε κείμενο από εικόνα**, και στη συνέχεια **πώς να ανιχνεύσετε λανθασμένες λέξεις** ενώ **λαμβάνετε προτάσεις ορθογραφίας**—όλα με μια σύντομη C# κονσόλα εφαρμογή. Η βασική ιδέα είναι απλή: αφήστε το Aspose.OCR να κάνει τη βαριά δουλειά της αναγνώρισης χαρακτήρων, και στη συνέχεια αφήστε τον ενσωματωμένο ορθογραφικό ελεγκτή να καθαρίσει την έξοδο. Από εδώ μπορείτε να επεκτείνετε την επίδειξη σε μια πλήρη υπηρεσία επεξεργασίας εγγράφων, να την ενσωματώσετε με ένα web API, ή να την συνδέσετε με έναν επεξεργαστή επιφάνειας εργασίας. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να αλλάξετε τη γλώσσα στα Ισπανικά, τροφοδοτήστε ένα PDF πολλαπλών σελίδων, ή δημιουργήστε ένα μικρό WPF front‑end που επιτρέπει στους χρήστες να κάνουν κλικ σε μια λέξη για να αποδεχτούν μια πρόταση. Τα δομικά στοιχεία είναι ήδη στη θέση τους—συνεχίστε να πειραματίζεστε. + +Αν αντιμετωπίσατε προβλήματα ή έχετε ιδέες για επεκτάσεις, αφήστε ένα σχόλιο παρακάτω. Καλή προγραμματιστική! + +## Τι πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετικά θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Εξαγωγή κειμένου από εικόνα χρησιμοποιώντας Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Εξαγωγή κειμένου από εικόνα – Βελτιστοποίηση 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/greek/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/greek/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..1bdaa33dc --- /dev/null +++ b/ocr/greek/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Πραγματοποιήστε OCR σε εικόνα χρησιμοποιώντας το Aspose OCR σε C#. Μάθετε + πώς να φορτώνετε εικόνα για OCR και να εξάγετε κείμενο στα Χίντι από εικόνα εκτός + σύνδεσης με βήμα‑βήμα κώδικα. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: el +og_description: Εκτελέστε OCR σε εικόνα με το Aspose OCR σε C#. Αυτό το σεμινάριο + δείχνει πώς να φορτώσετε μια εικόνα για OCR και να εξάγετε κείμενο στα Χίντι εκτός + σύνδεσης, με πλήρη εκτελέσιμο κώδικα. +og_title: Εκτέλεση OCR σε εικόνα – Οδηγός Aspose OCR Hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Εκτελέστε OCR σε εικόνα με το Aspose OCR – Οδηγός στα Χίντι +url: /el/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εκτέλεση OCR σε εικόνα με Aspose OCR – Οδηγός για τα Χίντι + +Έχετε ποτέ χρειαστεί να **εκτελέσετε OCR σε εικόνα** αρχεία αλλά να μην ξέρατε πώς να εξάγετε τους χαρακτήρες Χίντι; Δεν είστε μόνοι—πολλοί προγραμματιστές συναντούν αυτό το εμπόδιο όταν προσπαθούν για πρώτη φορά να διαβάσουν μη‑λατινικά σενάρια. Τα καλά νέα είναι ότι το Aspose OCR το κάνει αρκετά απλό, και μπορείτε ακόμη και να το κάνετε εντελώς εκτός σύνδεσης. + +Σε αυτόν τον οδηγό θα **φορτώσουμε εικόνα για OCR**, θα κατευθύνουμε τη μηχανή στα τοπικά πακέτα γλώσσας, και τελικά θα **εξάγουμε δεδομένα κειμένου Χίντι από εικόνα** χωρίς ποτέ να χρειαστεί πρόσβαση στο διαδίκτυο. Στο τέλος θα έχετε μια έτοιμη για εκτέλεση εφαρμογή κονσόλας C# που διαβάζει μια απόδειξη στα Χίντι και εκτυπώνει το κείμενο στην κονσόλα. + +## Τι θα χρειαστείτε + +- **.NET 6.0** ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+) +- **Aspose.OCR for .NET** πακέτο NuGet + `dotnet add package Aspose.OCR` +- Ένας φάκελος που περιέχει τους **τοπικούς πόρους γλώσσας Χίντι** (κατεβάστε από το portal της Aspose) +- Ένα αρχείο εικόνας με κείμενο Χίντι, π.χ., `receipt_hindi.png` + +Αυτό είναι όλο—χωρίς εξωτερικές υπηρεσίες, χωρίς κλειδιά API, μόνο απλός κώδικας. + +## Εκτέλεση OCR σε εικόνα – Βήμα‑βήμα Υλοποίηση + +Παρακάτω χωρίζουμε τη διαδικασία σε επτά σαφή βήματα. Κάθε βήμα εξηγείται **γιατί** είναι σημαντικό, όχι μόνο **τι** πρέπει να πληκτρολογήσετε. + +### Βήμα 1: Δημιουργία του παραδείγματος OCR Engine + +Η μηχανή είναι η καρδιά του Aspose OCR. Η δημιουργία της σας δίνει πρόσβαση σε όλες τις ρυθμίσεις που θα ρυθμίσετε αργότερα. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Γιατί;** +> Χωρίς ένα `OcrEngine` δεν έχετε αντικείμενο για να καλέσετε το `Recognize`. Σκεφτείτε το ως την “κάμερα” που θα σαρώσει αργότερα την εικόνα σας. + +### Βήμα 2: Κατεύθυνση της μηχανής στους τοπικούς πόρους + +Το Aspose παρέχει πακέτα γλώσσας που μπορείτε να αποθηκεύσετε τοπικά. Η ρύθμιση του `ResourcesFolder` λέει στη μηχανή πού να ψάξει. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Συμβουλή:** +> Χρησιμοποιήστε απόλυτη διαδρομή κατά την ανάπτυξη, στη συνέχεια μεταβείτε σε σχετική διαδρομή ή ρύθμιση παραμέτρων για την παραγωγή. + +### Βήμα 3: Εξαναγκασμός λειτουργίας εκτός σύνδεσης + +Μπορεί να αναρωτιέστε, “Χρειάζεται πραγματικά να απενεργοποιήσω την online αναζήτηση?” +Αν εργάζεστε πίσω από τείχος προστασίας ή απλώς θέλετε καθοριστικά αποτελέσματα, ορίστε το `UseOfflineResources` σε `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> Η διατήρηση αυτής της σημαίας σε `false` μπορεί να κάνει τη μηχανή να κατεβάσει πρόσθετα δεδομένα, κάτι που προσθέτει καθυστέρηση και μπορεί να παραβιάσει πολιτικές ασφαλείας. + +### Βήμα 4: Επιλογή Χίντι ως γλώσσα αναγνώρισης + +Εδώ **εξάγουμε κείμενο Χίντι από εικόνα** λέγοντας στη μηχανή ποια γλώσσα να περιμένει. Αυτό βελτιώνει δραματικά την ακρίβεια. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Γιατί βοηθά:** +> Οι μηχανές OCR χρησιμοποιούν μοντέλα χαρακτήρων ειδικά για κάθε γλώσσα. Κλειδώνοντας στο Χίντι, αποφεύγετε τη μηχανή να μαντεύει ανάμεσα σε δεκάδες γραφές. + +### Βήμα 5: Φόρτωση εικόνας για OCR + +Τώρα πραγματικά **φορτώνουμε εικόνα για OCR**. Η μέθοδος `OcrImage.FromFile` διαβάζει το bitmap σε μορφή που καταλαβαίνει η μηχανή. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Συνηθισμένο λάθος:** +> Η παροχή διαδρομής με μπροστινά κάθετα (forward slashes) στα Windows λειτουργεί, αλλά η χρήση του `Path.Combine` κάνει τον κώδικά σας ανεξάρτητο από την πλατφόρμα. + +### Βήμα 6: Εκτέλεση της αναγνώρισης + +Με όλα ρυθμισμένα, τελικά **εκτελούμε OCR σε εικόνα** καλώντας το `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Τι συμβαίνει;** +> Η μηχανή σαρώει κάθε pixel, ταιριάζει μοτίβα με τη βάση δεδομένων γλυφών Χίντι, και δημιουργεί μια συμβολοσειρά χαρακτήρων Unicode. + +### Βήμα 7: Εξαγωγή του αναγνωρισμένου κειμένου + +Το αντικείμενο αποτελέσματος περιέχει την ιδιότητα `Text` που κρατά τη εξαγόμενη συμβολοσειρά. Απλώς την γράφουμε στην κονσόλα. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Αναμενόμενη έξοδος:** +> Αν το `receipt_hindi.png` περιέχει “भुगतान सफल”, η κονσόλα θα εκτυπώσει ακριβώς αυτή τη γραμμή, διατηρώντας τα διακριτικά. + +## Φόρτωση εικόνας για OCR – Προετοιμασία του πόρου + +Αν αναρωτιέστε αν μπορείτε να τροφοδοτήσετε τη μηχανή με ροή αντί για αρχείο, η απάντηση είναι ναι. Αντικαταστήστε το `OcrImage.FromFile` με: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Γιατί να χρησιμοποιήσετε ροή;** +> Οι ροές σας επιτρέπουν να δουλεύετε με εικόνες αποθηκευμένες σε βάσεις δεδομένων, cloud blobs ή ενσωματωμένους πόρους—ιδανικό για κλιμακούμενες υπηρεσίες. + +## Εξαγωγή κειμένου Χίντι από εικόνα – Διαχείριση ακραίων περιπτώσεων + +1. **Απουσία πακέτου γλώσσας** – Αν το πακέτο Χίντι δεν βρεθεί, το `Recognize` ρίχνει εξαίρεση. Περιβάλλετε την κλήση με try/catch και καταγράψτε ένα φιλικό μήνυμα. +2. **Εικόνες χαμηλής ανάλυσης** – Η ακρίβεια του OCR μειώνεται κάτω από 300 dpi. Προεπεξεργαστείτε την εικόνα (αλλαγή μεγέθους, όξυνση) πριν τη φόρτωση. +3. **Έγγραφα μικτής γλώσσας** – Μπορείτε να ενεργοποιήσετε πολλαπλές γλώσσες: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Αυτές οι προσαρμογές εξασφαλίζουν ότι η ρουτίνα **εκτέλεσης OCR σε εικόνα** παραμένει αξιόπιστη στην παραγωγή. + +## Εκτέλεση του πλήρους παραδείγματος + +Αποθηκεύστε το παρακάτω αρχείο ως `Program.cs`, αντικαταστήστε τις διαδρομές placeholder και τρέξτε: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Όταν εκτελέσετε `dotnet run`, θα πρέπει να δείτε κάτι όπως: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Αν λάβετε κενή συμβολοσειρά, ελέγξτε ξανά ότι το **ResourcesFolder** δείχνει στον φάκελο που περιέχει το `Hindi.traineddata` και ότι η εικόνα είναι αρκετά καθαρή. + +## Συμπέρασμα + +Διασχίσαμε πώς να **εκτελέσετε OCR σε εικόνα** αρχεία με το Aspose OCR, καλύπτοντας τα πάντα από το **φόρτωση εικόνας για OCR** έως το **εξαγωγή κειμένου Χίντι από εικόνα** σε εντελώς εκτός σύνδεσης σενάριο. Ο πλήρης, εκτελέσιμος κώδικας παραπάνω σας παρέχει μια σταθερή βάση, και οι συμβουλές για ροές, διαχείριση σφαλμάτων και υποστήριξη πολλαπλών γλωσσών θα σας βοηθήσουν να προσαρμόσετε τη λύση σε πραγματικά έργα. + +Έτοιμοι για το επόμενο βήμα; Δοκιμάστε να αλλάξετε τη γλώσσα σε **OcrLanguage.Tamil** ή να τροφοδοτήσετε εικόνες από αποθήκευση Azure Blob. Μπορείτε επίσης να πειραματιστείτε με τις ρυθμίσεις `ImagePreprocessing` για να βελτιώσετε την ακρίβεια σε θορυβώδεις αποδείξεις. + +Έχετε ερωτήσεις ή αντιμετωπίσατε πρόβλημα; Αφήστε ένα σχόλιο—καλή προγραμματιστική! + +![Perform OCR on image example + + +## Τι θα πρέπει να μάθετε στη συνέχεια; + +Τα παρακάτω tutorials καλύπτουν στενά σχετικές θεματικές που βασίζονται στις τεχνικές που παρουσιάζονται σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσουν να κυριαρχήσετε σε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [αναγνώριση κειμένου εικόνας με Aspose OCR για πολλαπλές γλώσσες](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Εξαγωγή κειμένου από εικόνα – Βελτιστοποίηση 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/greek/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/greek/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..aad219b14 --- /dev/null +++ b/ocr/greek/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-06-03 +description: Εκτελέστε OCR σε PDF και μετατρέψτε σκαναρισμένα PDF σε αναζητήσιμα PDF + χρησιμοποιώντας το Aspose.OCR. Μάθετε πώς να αναγνωρίζετε κείμενο από PDF και να + δημιουργείτε αναζητήσιμα PDF σε λίγα λεπτά. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: el +og_description: Κάντε OCR σε PDF και δημιουργήστε αμέσως ένα PDF με δυνατότητα αναζήτησης. + Αυτό το σεμινάριο δείχνει βήμα‑βήμα πώς να αναγνωρίζετε κείμενο από PDF χρησιμοποιώντας + το Aspose.OCR. +og_title: Εκτελέστε OCR σε PDF – Πλήρης Οδηγός C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Εκτελέστε OCR σε PDF με το Aspose.OCR – Πλήρης Οδηγός C# +url: /el/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εκτέλεση OCR σε PDF με Aspose.OCR – Πλήρης Οδηγός C# + +Έχετε αναρωτηθεί ποτέ **πώς να εκτελέσετε OCR σε αρχεία PDF** χωρίς να παλεύετε με δεκάδες εργαλεία γραμμής εντολών; Δεν είστε μόνοι. Είτε ψηφιοποιείτε τιμολόγια, αρχειοθετείτε παλιά αναφορές, είτε χρειάζεστε απλώς μια αναζητήσιμη έκδοση ενός σαρωμένου συμβολαίου, η μετατροπή ενός στατικού PDF σε κάτι που μπορείτε πραγματικά να αναζητήσετε είναι πραγματική αλλαγή παιχνιδιού. + +Σε αυτόν τον οδηγό θα περάσουμε βήμα‑βήμα **πώς να δημιουργήσετε αναζητήσιμα PDF** από σαρωμένα PDF (και ακόμη και από απλές εικόνες) χρησιμοποιώντας το Aspose.OCR για .NET. Στο τέλος θα μπορείτε **να αναγνωρίσετε κείμενο από PDF** με λίγες γραμμές κώδικα C#, και θα κατανοήσετε το «γιατί» πίσω από κάθε βήμα ώστε να προσαρμόσετε τη λύση στα δικά σας έργα. + +> **Γρήγορη σύνοψη:** Η διαδικασία περιορίζεται σε τρία πράγματα—αρχικοποίηση της μηχανής OCR, παροχή της πηγής (PDF ή εικόνα) και αποθήκευση του αναζητήσιμου PDF. Ας βουτήξουμε. + +--- + +## Τι Θα Χρειαστείτε + +Πριν ξεκινήσουμε, βεβαιωθείτε ότι έχετε: + +| Προαπαιτούμενο | Γιατί είναι σημαντικό | +|----------------|-----------------------| +| **.NET 6.0+** (ή .NET Framework 4.6+) | Το Aspose.OCR στοχεύει σε σύγχρονες εκτελέσεις· παλαιότερες εκδόσεις μπορεί να λείπουν ενημερώσεις API. | +| **Aspose.OCR for .NET** πακέτο NuGet | Παρέχει την κλάση `OcrEngine` και τις βοηθητικές λειτουργίες PDF. | +| **Έγκυρη άδεια Aspose** (ή χρήση της δωρεάν αξιολόγησης) | Χωρίς άδεια θα αντιμετωπίσετε όριο 30 ημερών και υδατογραφήματα. | +| **Ένα σαρωμένο PDF** (ή αρχείο εικόνας) που θέλετε να κάνετε αναζητήσιμο | Αυτή είναι η πηγή για το OCR. | +| **Visual Studio 2022** (ή οποιονδήποτε επεξεργαστή C#) | Διευκολύνει τον εντοπισμό σφαλμάτων, αλλά λειτουργεί και με οποιοδήποτε IDE. | + +Μπορείτε να εγκαταστήσετε τη βιβλιοθήκη με την ακόλουθη εντολή NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Συμβουλή επαγγελματία:** Αν εργάζεστε σε pipeline CI, προσθέστε το αρχείο άδειας στα artefacts του build και φορτώστε το κατά το runtime για να αποφύγετε σκληρή κωδικοποίηση διαδρομών. + +--- + +## Εκτέλεση OCR σε PDF – Ρύθμιση του Aspose.OCR + +Το πρώτο που χρειαζόμαστε είναι μια νέα παρουσία της κλάσης `OcrEngine`. Σκεφτείτε την ως τον εγκέφαλο που θα διαβάσει το έγγραφό σας. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Γιατί νέα παρουσία κάθε φορά; Η μηχανή διατηρεί ρυθμίσεις (όπως γλώσσα) που μπορεί να διαφέρουν ανά έγγραφο. Η δημιουργία νέας παρουσίας σε κάθε εκτέλεση εγγυάται καθαρό περιβάλλον και αποτρέπει αλληλεπιδράσεις μεταξύ εργασιών. + +--- + +## Πώς να Δημιουργήσετε Αναζητήσιμο PDF – Ρύθμιση Κωδικών Πρόσβασης (Προαιρετικό) + +Αν το PDF σας είναι προστατευμένο, πρέπει να ενημερώσετε τη μηχανή με τον κωδικό πριν διαβάσει τις σελίδες: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Παράλειψη αυτού του βήματος σε προστατευμένο αρχείο θα προκαλέσει `PdfPasswordException`. Πάντα τυλίξτε το σε try‑catch αν δεν είστε σίγουροι για την κατάσταση προστασίας. + +--- + +## Μετατροπή Σαρωμένου PDF σε Αναζητήσιμο PDF – Φόρτωση Πηγής + +Το Aspose.OCR λειτουργεί με την αφαίρεση `OcrImage`, η οποία μπορεί να περιλαμβάνει PDF, TIFF, JPEG κ.λπ. Δείτε πώς φορτώνετε ένα σαρωμένο PDF στη μνήμη: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Πίσω από τις κουρτίνες, η μέθοδος `FromFile` αναλύει κάθε σελίδα σε raster εικόνες που η μηχανή OCR μπορεί να επεξεργαστεί. Αν έχετε PDF πολλαπλών σελίδων, η μηχανή θα επαναλάβει αυτόματα σε κάθε σελίδα. + +--- + +## Αναγνώριση Κειμένου από PDF – Εκτέλεση του OCR + +Τώρα το κύριο μέρος του οδηγού: ζητήστε από τη μηχανή να αναγνωρίσει το κείμενο και να δημιουργήσει ένα αναζητήσιμο PDF. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +Η τιμή `OutputFormat.SearchablePdf` λέει στη μηχανή να ενσωματώσει ένα αόρατο στρώμα κειμένου πάνω από τις αρχικές σαρωμένες εικόνες. Το αποτέλεσμα διατηρεί την οπτική πιστότητα της σάρωσης ενώ γίνεται πλήρως αναζητήσιμο—ακριβώς ό,τι χρειάζεστε για ελέγχους συμμόρφωσης. + +--- + +## Μετατροπή Εικόνας σε Αναζητήσιμο PDF – Αποθήκευση Αποτελέσματος + +Τέλος, γράψτε τα δυαδικά δεδομένα στο δίσκο: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Η ιδιότητα `Binary` περιέχει τα ακατέργαστα bytes του PDF. Μπορείτε επίσης να τα ρέξετε απευθείας σε απάντηση web αν χτίζετε API. + +--- + +![Διάγραμμα που δείχνει τη ροή μετατροπής OCR για δημιουργία αναζητήσιμου PDF](https://example.com/ocr-flow.png "Διάγραμμα ροής OCR σε PDF") + +*Κείμενο alt εικόνας: Διάγραμμα ροής OCR σε PDF που απεικονίζει πώς ένα σαρωμένο PDF μετατρέπεται σε αναζητήσιμο PDF.* + +--- + +## Ακραίες Περιπτώσεις & Πρακτικές Συμβουλές + +### 1. Μεγάλα Αρχεία & Διαχείριση Μνήμης +Αν επεξεργάζεστε PDF μεγαλύτερα από 100 MB, σκεφτείτε τη χρήση του `OcrEngineSettings.MemoryLimit` για περιορισμό χρήσης μνήμης. Επιπλέον, επεξεργαστείτε τις σελίδες σε παρτίδες για να αποφύγετε `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Υποστήριξη Γλωσσών +Από προεπιλογή το Aspose.OCR υποθέτει Αγγλικά. Για άλλες γλώσσες, ορίστε την ιδιότητα `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Σενάρια Πολυνηματικότητας +Η `OcrEngine` **δεν** είναι thread‑safe. Αν χρειάζεστε παράλληλη επεξεργασία, δημιουργήστε ξεχωριστή μηχανή ανά νήμα. + +### 4. Εντοπισμός Ακρίβειας OCR +Μπορείτε να εξάγετε το απλό κείμενο από το `ocrResult` για εντοπισμό σφαλμάτων: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Αν το αποτέλεσμα φαίνεται ακατάστατο, πειραματιστείτε με `PreprocessSettings` (π.χ., διόρθωση κλίσης, απομάκρυνση θορύβου) για βελτίωση ποιότητας. + +### 5. Πιθανά Προβλήματα Άδειας +Όταν τρέχετε την έκδοση αξιολόγησης, το Aspose προσθέτει υδατογράφημα στο παραγόμενο PDF. Καταχωρίστε την άδειά σας νωρίς στην εφαρμογή: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Πλήρες Παράδειγμα – Από την Αρχή ως το Τέλος + +Παρακάτω βρίσκεται το ολοκληρωμένο, έτοιμο‑για‑εκτέλεση πρόγραμμα που ενσωματώνει όλες τις παραπάνω συμβουλές. Απλώς αντιγράψτε‑και‑επικολλήστε το σε ένα νέο κονσολικό project. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Αναμενόμενο αποτέλεσμα:** Μετά την εκτέλεση, θα δείτε μια γραμμή στην κονσόλα που επιβεβαιώνει τη θέση του αρχείου. Ανοίξτε το `output.pdf` σε οποιονδήποτε προβολέα PDF· δοκιμάστε να πληκτρολογήσετε μια λέξη που γνωρίζετε ότι υπάρχει στην αρχική σάρωση. Αν το κείμενο επισημαίνεται, έχετε **εκτελέσει OCR σε PDF** και δημιουργήσει ένα αναζητήσιμο έγγραφο. + +--- + +## Συχνές Ερωτήσεις + +**Ε: Μπορώ να το χρησιμοποιήσω για μετατροπή μιας μόνο εικόνας (PNG/JPEG) σε αναζητήσιμο PDF;** +Α: Σίγουρα. Αντικαταστήστε το `OcrImage.FromFile("input.pdf")` με τη διαδρομή του αρχείου εικόνας σας. Η μηχανή θα ραστεροποιήσει την εικόνα και θα ενσωματώσει το στρώμα OCR με τον ίδιο τρόπο. + +**Ε: Τι γίνεται αν το PDF μου περιέχει τόσο σαρωμένες σελίδες όσο και ενσωματωμένο κείμενο;** +Α: Η μηχανή θα τοποθετήσει το κείμενο OCR πάνω από το υπάρχον περιεχόμενο, έτσι το ενσωματωμένο κείμενο παραμένει επιλέξιμο ενώ οι σαρωμένες σελίδες γίνονται αναζητήσιμες. + +**Ε: Πόσο ακριβές είναι το OCR;** +Α: Η ακρίβεια εξαρτάται από την ποιότητα της πηγής. Καθαρές, υψηλής ανάλυσης σάρωσεις (>300 dpi) δίνουν >95 % ακρίβεια. Για θορυβώδη έγγραφα, ενεργοποιήστε `PreprocessSettings` (διόρθωση κλίσης, απομάκρυνση θορύβου) πριν καλέσετε `Recognize`. + +--- + +## Επόμενα Βήματα – Επέκταση του Οικοσυστήματος OCR + +Τώρα που μπορείτε **να αναγνωρίσετε κείμενο από PDF** και **να μετατρέψετε σαρωμένα PDF σε αναζητήσιμα PDF**, σκεφτείτε τα εξής θέματα: + +- **Επεξεργασία παρτίδας**: Επανάληψη σε φάκελο PDF και αυτόματη δημιουργία αναζητήσιμων εκδόσεων. +- **Εξαγωγή κειμένου**: Χρησιμοποιήστε το `ocrResult.Text` για τροφοδοσία σε ευρετήριο αναζήτησης (π.χ., Elasticsearch). +- **Προσαρμοσμένα πακέτα γλώσσας**: Κατεβάστε πρόσθετα δεδομένα γλώσσας από το Aspose για υποστήριξη ασιατικών γραφών. +- **Συμμόρφωση PDF/A**: Συνδυάστε το Aspose.PDF με το αποτέλεσμα OCR για δημιουργία αρχείων έτοιμων για αρχειοθέτηση. + +Κάθε ένα από αυτά βασίζεται στα βασικά βήματα που καλύψαμε, οπότε είστε έτοιμοι να επεκτείνετε τη λύση σας. + +--- + +## Συμπέρασμα + +Σας δείξαμε **πώς να εκτελέσετε OCR σε PDF** χρησιμοποιώντας το Aspose.OCR, να μετατρέψετε σαρωμένα PDF σε πλήρως αναζητήσιμα PDF, και ακόμη να μετατρέψετε απλές εικόνες σε αναζητήσιμα PDF. Ο κώδικας + +## Τι Πρέπει Να Μάθετε Στη Σύντομη Μελλοντική + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που επεκτείνουν τις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να κυριαρχήσετε επιπλέον δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις στα δικά σας έργα. + +- [Αναγνώριση Κειμένου PDF – Λειτουργίες OCR με Aspose.OCR για Java](/ocr/english/java/ocr-operations/) +- [Πώς να κάνετε 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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/greek/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..75f636392 --- /dev/null +++ b/ocr/greek/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: Εκπαιδευτικό βίντεο OCR υποτίτλων που δείχνει πώς να εξάγετε καρέ από + βίντεο και να διαβάζετε κείμενο από αρχεία βίντεο όπως MP4 χρησιμοποιώντας το Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: el +og_description: Μάθετε OCR υποτίτλων βίντεο με το Aspose.OCR. Εξάγετε καρέ από βίντεο, + διαβάστε κείμενο από βίντεο και εξάγετε κείμενο από MP4 σε λίγα λεπτά. +og_title: OCR Υπότιτλων Βίντεο σε C# – Οδηγός Βήμα‑Βήμα +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR Υπότιτλων Βίντεο σε C# – Πλήρης Οδηγός +url: /el/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Υπότιτλων Βίντεο σε C# – Πλήρης Οδηγός + +Έχετε ποτέ χρειαστεί **video subtitle ocr** αλλά δεν ήξερες από πού να ξεκινήσεις; Δεν είστε μόνοι. Είτε ψηφιοποιείτε ηχογραφήσεις διαλέξεων, είτε εξάγετε υπότιτλους από εκπαιδευτικά βίντεο, είτε απλώς θέλετε να **διαβάσετε κείμενο από βίντεο** αρχεία—συμπεριλαμβανομένου του MP4—χωρίς να ψάχνετε για τρίτα εργαλεία. + +## Τι Θα Δημιουργήσετε + +1. Αποκωδικοποιεί ένα MP4 (ή οποιαδήποτε υποστηριζόμενη μορφή) σε μεμονωμένα `Bitmap` καρέ. +2. Περιορίζει την περιοχή OCR στη ζώνη των υποτίτλων ώστε η μηχανή να μην αποσπάται από ολόκληρη την εικόνα. +3. Επεξεργάζεται κάθε καρέ με το `VideoOcrProcessor` της Aspose. +4. Εκτυπώνει το αναγνωρισμένο κείμενο υποτίτλων στην κονσόλα. + +Χωρίς περιττά, μόνο ένα λειτουργικό παράδειγμα end‑to‑end που μπορείτε να ενσωματώσετε σε ένα πραγματικό έργο. + +## Προαπαιτούμενα + +- **.NET 6.0** ή νεότερο (ο κώδικας λειτουργεί επίσης σε .NET Framework 4.7+). +- **Aspose.OCR for .NET** – εγκαταστήστε μέσω NuGet: `Install-Package Aspose.OCR`. +- Ένα αρχείο βίντεο (το MP4 λειτουργεί άψογα). +- Ένας τρόπος για την αποκωδικοποίηση των καρέ του βίντεο – η demo χρησιμοποιεί μια placeholder μέθοδο, αλλά μπορείτε να ενσωματώσετε FFmpeg, OpenCV ή οποιαδήποτε βιβλιοθήκη που επιστρέφει αντικείμενα `Bitmap`. + +> Συμβουλή: Αν χρησιμοποιείτε Windows, το πακέτο `System.Drawing.Common` λειτουργεί καλά για `Bitmap`. Σε Linux/macOS θα χρειαστείτε την εγγενή εξάρτηση `libgdiplus`. + +## Βήμα 1 – Εξαγωγή Καρέ από Βίντεο + +Το πρώτο εμπόδιο είναι η μετατροπή μιας κινούσας εικόνας σε στατικές εικόνες. Η μέθοδος `GetVideoFrames` παρακάτω είναι σκόπιμα κενή· αντικαταστήστε την με τον αγαπημένο σας αποκωδικοποιητή. Εδώ είναι ένα γρήγορο σκίτσο χρησιμοποιώντας FFmpeg‑Core (απλώς για να δείξει τη δομή των δεδομένων): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Γιατί είναι σημαντικό:** Η εξαγωγή καρέ παρέχει στη μηχανή OCR μια στατική εικόνα για επεξεργασία, κάτι που βελτιώνει δραματικά την ακρίβεια σε σύγκριση με την προσπάθεια ανάγνωσης απευθείας από ροή βίντεο. + +## Βήμα 2 – Ρύθμιση του VideoOcrProcessor + +Τώρα που έχουμε μια ακολουθία αντικειμένων `Bitmap`, μπορούμε να τα περάσουμε στο Aspose.OCR. Το `VideoOcrProcessor` μας επιτρέπει να ορίσουμε μια **Region of Interest (ROI)** – ιδανική για υπότιτλους που συνήθως βρίσκονται στην κορυφή ή στο κάτω μέρος του καρέ. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Γιατί να περιορίσουμε το ROI;** Αγνοώντας το υπόλοιπο της εικόνας μειώνουμε τον θόρυβο, μειώνουμε το χρόνο επεξεργασίας και αποφεύγουμε ψευδώς θετικά αποτελέσματα από γραφικά φόντου. + +## Βήμα 3 – Εκτέλεση OCR στην Ακολουθία Καρέ + +Με τον επεξεργαστή έτοιμο, η τροφοδοσία των καρέ γίνεται με μία γραμμή κώδικα. Η μέθοδος `Process` επιστρέφει ένα enumerable από αντικείμενα `OcrResult`, το καθένα περιέχει το αναγνωρισμένο κείμενο για το αντίστοιχο καρέ. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Τι συμβαίνει εσωτερικά;** Το Aspose.OCR κανονικοποιεί εσωτερικά κάθε bitmap, εκτελεί έναν αναγνωριστή βασισμένο σε νευρωνικό δίκτυο και στη συνέχεια επεξεργάζεται το αποτέλεσμα για να βελτιώσει την στίξη και τις αλλαγές γραμμής. + +## Βήμα 4 – Εμφάνιση του Εξαγόμενου Κειμένου + +Τέλος, επαναλαμβάνουμε τα αποτελέσματα και εκτυπώνουμε κάθε γραμμή υποτίτλου. Μπορείτε επίσης να τα γράψετε σε αρχείο SRT, σε βάση δεδομένων ή να τα στείλετε σε υπηρεσία μετάφρασης. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα τα παραπάνω προκύπτει ένα αυτόνομο πρόγραμμα κονσόλας: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Αναμενόμενη έξοδος (παράδειγμα)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Αν το OCR αντιμετωπίζει δυσκολίες με κάποιο συγκεκριμένο καρέ, θα δείτε μια κενή συμβολοσειρά – αυτό είναι ένδειξη να προσαρμόσετε το ROI ή να αυξήσετε το ρυθμό εξαγωγής καρέ. + +## Συνηθισμένα Πιθανά Προβλήματα & Πώς να τα Διορθώσετε + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| **Αχρείαστοι χαρακτήρες** | Καρέ χαμηλής ανάλυσης ή έντονη συμπίεση | Εξάγετε καρέ με υψηλότερο bitrate, ή αυξήστε την ανάλυση του bitmap πριν το OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **Δεν επιστράφηκε κείμενο** | Το ROI δεν καλύπτει πραγματικά τη ζώνη των υποτίτλων | Επαληθεύστε τις συντεταγμένες του ορθογωνίου (χρησιμοποιήστε εργαλείο στιγμιότυπου για μέτρηση). | +| **Σημείο συμφόρησης απόδοσης** | Η επεξεργασία κάθε καρέ στα 30 fps είναι υπερβολική | Μειώστε το δείγμα σε 1‑2 fps για τις περισσότερες ροές υποτίτλων· μπορείτε ακόμα να καταγράψετε κάθε αλλαγή υποτίτλου. | +| **FFmpeg δεν βρέθηκε** | `ffmpeg.exe` δεν βρίσκεται στο `PATH` | Παρέχετε το πλήρες μονοπάτι στο `ProcessStartInfo.FileName` ή εγκαταστήστε το FFmpeg παγκοσμίως. | + +## Επέκταση της Λύσης + +- **Export to SRT** – συνδέστε τα χρονικά σημεία με το κείμενο OCR και γράψτε ένα αρχείο SubRip. +- **Multi‑language support** – ορίστε `ocrProcessor.Language = OcrLanguage.Spanish` (ή οποιαδήποτε υποστηριζόμενη γλώσσα). +- **Real‑time processing** – διοχετεύστε τα καρέ απευθείας από ζωντανή ροή αντί για ανάγνωση από δίσκο. + +Όλες αυτές οι παραλλαγές περιστρέφονται γύρω από τις βασικές ιδέες του **extract frames from video**, **read text from video**, και **extract text from mp4**. + +## Συμπέρασμα + +Μόλις περάσαμε από μια πλήρη ροή εργασίας **video subtitle ocr** σε C#. Με την εξαγωγή καρέ από το βίντεο, εστιάζοντας το OCR στη ζώνη των υποτίτλων και επαναλαμβάνοντας τα αποτελέσματα, μπορείτε αξιόπιστα να **read text from video** αρχεία όπως MP4. Ο κώδικας είναι έτοιμος για αντιγραφή‑επικόλληση, και ο μοντέλο σχεδίασης σας επιτρέπει να αντικαταστήσετε οποιονδήποτε αποκωδικοποιητή καρέ προτιμάτε. + +Επόμενα βήματα; Δοκιμάστε να εξάγετε τα αποτελέσματα σε αρχείο SRT, πειραματιστείτε με διαφορετικά μεγέθη ROI, ή στείλτε τους υπότιτλους σε API μετάφρασης για πολυγλωσσικούς υπότιτλους. Ο ουρανός είναι το όριο μόλις κατακτήσετε τα βασικά της εξαγωγής κειμένου από βίντεο. + +Καλό κώδικα, και οι υπότιτλοί σας να είναι πάντα κρυστάλλινοι! + +## Τι Θα Μάθετε Στη Σειρά; + +Τα παρακάτω tutorials καλύπτουν στενά συναφή θέματα που βασίζονται στις τεχνικές που παρουσιάστηκαν σε αυτόν τον οδηγό. Κάθε πόρος περιλαμβάνει πλήρη παραδείγματα κώδικα με βήμα‑βήμα εξηγήσεις για να σας βοηθήσει να κατακτήσετε πρόσθετες δυνατότητες API και να εξερευνήσετε εναλλακτικές προσεγγίσεις υλοποίησης στα δικά σας έργα. + +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Εξαγωγή Κειμένου από Εικόνα Χρησιμοποιώντας Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Εξαγωγή Κειμένου από Εικόνα – Βελτιστοποίηση 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/net/ocr-configuration/_index.md b/ocr/hindi/net/ocr-configuration/_index.md index cee8a4618..ef72df947 100644 --- a/ocr/hindi/net/ocr-configuration/_index.md +++ b/ocr/hindi/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Aspose.OCR के साथ .NET में OCR इमेज रिकग्न Aspose.OCR for .NET के साथ शक्तिशाली OCR क्षमताओं को बढ़ाएं। इमेज से टेक्स्ट को बिना बताए हटाएं। ### [OCR इमेज रिकग्निशन में लिस्ट के साथ OCROperation](./ocr-operation-with-list/) Aspose.OCR for .NET की क्षमताओं को बढ़ाएं। लिस्ट के साथ OCR इमेज रिकग्निशन को आसानी से करें। अपने एप्लिकेशन में प्रोडक्टिविटी और डेटा एक्सट्रैक्शन को बढ़ाएं। +### [C# में Aspose OCR संस्करण प्राप्त करें – पूर्ण गाइड](./get-aspose-ocr-version-in-c-complete-guide/) +C# में Aspose OCR का संस्करण प्राप्त करने की पूरी गाइड, कोड उदाहरण और उपयोग के टिप्स। ### कॉमन यूज़ केस - **टेक्स्ट इमेज निकालें** स्कैन किए गए इनवॉइस से टेक्स्ट निकालें ताकि ऑटोमेटेड अकाउंटिंग हो सके। @@ -104,4 +106,4 @@ A: API इनेबल्ड फाइलों को स्किप कर {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/hindi/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..ebc981717 --- /dev/null +++ b/ocr/hindi/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-06-03 +description: C# में एक सरल स्निपेट के साथ Aspose OCR संस्करण प्राप्त करें। जानें कि + OcrEngine GetVersion का उपयोग करके Aspose OCR लाइब्रेरी का संस्करण कैसे प्राप्त + किया जाए। +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: hi +og_description: C# में Aspose OCR संस्करण जल्दी प्राप्त करें। यह ट्यूटोरियल दिखाता + है कि OcrEngine GetVersion का उपयोग करके Aspose OCR लाइब्रेरी संस्करण को कैसे प्राप्त + किया जाए। +og_title: C# में Aspose OCR संस्करण प्राप्त करें – पूर्ण गाइड +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: C# में Aspose OCR संस्करण प्राप्त करें – पूर्ण गाइड +url: /hi/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में Aspose OCR संस्करण प्राप्त करें – पूर्ण गाइड + +क्या आपने कभी सोचा है कि अपने .NET प्रोजेक्ट के भीतर **Aspose OCR संस्करण** कैसे प्राप्त किया जाए? शायद आप किसी असंगति को ठीक कर रहे हैं, या आप सिर्फ प्रोडक्शन में चल रही लाइब्रेरी की सटीक बिल्ड को लॉग करना चाहते हैं। जो भी कारण हो, आप सही जगह पर आए हैं। + +इस ट्यूटोरियल में हम एक छोटा, स्वतंत्र C# प्रोग्राम देखेंगे जो `OcrEngine.GetVersion()` को कॉल करता है और परिणाम को प्रिंट करता है। अंत तक आप न केवल संस्करण कैसे प्राप्त करें, बल्कि यह भी समझेंगे कि **Aspose OCR लाइब्रेरी** को अपग्रेड करते समय संस्करण की जाँच क्यों आपके सिरदर्द को बचा सकती है। + +## आप क्या सीखेंगे + +- C# प्रोजेक्ट में Aspose.OCR NuGet पैकेज जोड़ें +- `OcrEngine.GetVersion()` मेथड का उपयोग करें (the **ocrengine getversion** एंट्री पॉइंट) +- संभव अपवादों को संभालें और आउटपुट को सत्यापित करें +- लॉगिंग या शर्तीय फीचर टॉगल जैसे वास्तविक‑दुनिया के परिदृश्यों के लिए स्निपेट को विस्तारित करें + +OCR का कोई पूर्व अनुभव आवश्यक नहीं है—सिर्फ C# और Visual Studio (या आपका पसंदीदा IDE) की बुनियादी समझ चाहिए। चलिए शुरू करते हैं। + +--- + +## चरण 1: प्रोजेक्ट सेट अप करें और Aspose OCR लाइब्रेरी को शामिल करें + +किसी भी OCR‑संबंधित API को कॉल करने से पहले, आपको अपने प्रोजेक्ट में **Aspose OCR लाइब्रेरी** का संदर्भ चाहिए। + +1. Visual Studio में टर्मिनल या पैकेज मैनेजर कंसोल खोलें। +2. नवीनतम स्थिर संस्करण स्थापित करने के लिए निम्न कमांड चलाएँ: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** यदि आप .NET Core के बजाय .NET Framework को टार्गेट कर रहे हैं, तो NuGet पैकेज मैनेजर UI का उपयोग करें और अपने रनटाइम से मेल खाने वाला संस्करण चुनें। पैकेज में वह `OcrEngine` क्लास शामिल है जिसका हम बाद में उपयोग करेंगे। + +### यह क्यों महत्वपूर्ण है + +जब आप पैकेज स्थापित करते हैं, तो डिस्क पर असेंबली संस्करण रनटाइम पर लाइब्रेरी द्वारा रिपोर्ट किए गए संस्करण से अलग हो सकता है। कोड के माध्यम से संस्करण पूछने से यह सुनिश्चित होता है कि आप वही बिल्ड पढ़ रहे हैं जो CLR ने लोड किया है, जो डिबगिंग और अनुपालन ऑडिट के लिए महत्वपूर्ण है। + +--- + +## चरण 2: **Aspose OCR संस्करण** प्राप्त करने के लिए न्यूनतम कोड लिखें + +एक नया कंसोल ऐप बनाएं (`dotnet new console -n OcrVersionDemo`) और डिफ़ॉल्ट `Program.cs` को निम्नलिखित से बदलें: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**प्रत्येक भाग की व्याख्या** + +- `using Aspose.OCR;` OCR नेमस्पेस को स्कोप में लाता है, जिससे हम `OcrEngine` को कॉल कर सकते हैं। +- `OcrEngine.GetVersion()` **ocrengine getversion** स्थैतिक मेथड है जो `"24.5.7"` जैसी स्ट्रिंग लौटाता है। +- `try/catch` ब्लॉक में कॉल को रैप करने से आप रनटाइम आश्चर्यों से बचते हैं—शायद लक्ष्य मशीन पर नेटिव बाइनरी नहीं मिल रही हों। +- इंटरपोलेटेड स्ट्रिंग `$"Aspose OCR version: {version}"` एक स्पष्ट, मानव‑पठनीय लाइन प्रिंट करती है। + +### अपेक्षित आउटपुट + +जब आप प्रोजेक्ट फ़ोल्डर के भीतर `dotnet run` चलाते हैं, तो आपको कुछ इस तरह दिखना चाहिए: + +``` +Aspose OCR version: 24.5.7 +``` + +यदि लाइब्रेरी लोड नहीं हो पाती, तो त्रुटि शाखा एक संक्षिप्त संदेश आउटपुट करेगी, जिससे आप समस्या को जल्दी पहचान सकेंगे। + +--- + +## चरण 3: संस्करण आपके NuGet पैकेज से मेल खाता है या नहीं, सत्यापित करें + +यह मानना आसान है कि आपने जो NuGet संस्करण स्थापित किया है वही रनटाइम पर उपयोग हो रहा है, लेकिन पर्यावरण की अजीबियों के कारण यह नहीं हो सकता। दोबारा जाँचने के लिए: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +इस अतिरिक्त स्निपेट को चलाने से कुछ इस तरह प्रिंट होगा: + +``` +Assembly file version: 24.5.7.0 +``` + +यदि दोनों मान अलग हैं, तो आप संभवतः Global Assembly Cache (GAC) या पिछले बिल्ड फ़ोल्डर से पुराना DLL लोड कर रहे हैं। ऐसे में, अपने सॉल्यूशन को साफ़ करें (`dotnet clean`) और पुनः बनाएं। + +--- + +## चरण 4: संस्करण जाँच को प्रोडक्शन लॉगिंग में डालें + +अधिकांश वास्तविक‑दुनिया के एप्लिकेशन केवल कंसोल में प्रिंट नहीं करते; वे लॉग फ़ाइल या टेलीमेट्री सिस्टम में लिखते हैं। यहाँ `Microsoft.Extensions.Logging` का उपयोग करते हुए एक त्वरित उदाहरण है: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +अब संस्करण आपके संरचित लॉग में दिखाई देगा, जिससे बाद में `{Version}` द्वारा फ़िल्टर करना आसान हो जाता है। यह पैटर्न विशेष रूप से उपयोगी है जब आपके पास कई माइक्रो‑सर्विसेज हैं जो संभावित रूप से अलग OCR DLL को खींच रही हैं। + +--- + +## सामान्य प्रश्न और किनारे के मामलों + +### यदि `GetVersion()` खाली स्ट्रिंग लौटाता है तो क्या करें? + +यह आमतौर पर भ्रष्ट स्थापना या गायब नेटिव निर्भरता को दर्शाता है। NuGet पैकेज को पुनः‑इंस्टॉल करें और यह सत्यापित करें कि `Aspose.OCR.Native.dll` (या उपयुक्त प्लेटफ़ॉर्म‑विशिष्ट बाइनरी) आपके एक्ज़ीक्यूटेबल के साथ स्थित है। + +### क्या यह मेथड .NET Core 2.0 पर काम करता है? + +हाँ, **Aspose OCR** .NET Standard 2.0 और उससे ऊपर को सपोर्ट करता है, इसलिए कोई भी .NET Core संस्करण जो इस मानक को लागू करता है, `OcrEngine.GetVersion()` को कॉल कर सकता है। यदि आप एक स्व-निहित ऐप प्रकाशित कर रहे हैं तो सही रनटाइम आइडेंटिफ़ायर्स (`win-x64`, `linux-x64`, आदि) को संदर्भित करना सुनिश्चित करें। + +### क्या मैं लाइसेंस फ़ाइल के बिना संस्करण प्राप्त कर सकता हूँ? + +बिल्कुल। `GetVersion()` को लाइसेंस की आवश्यकता **नहीं** है; यह केवल लाइब्रेरी बिल्ड नंबर रिपोर्ट करता है। हालांकि, यदि आप वैध लाइसेंस के बिना OCR करने का प्रयास करते हैं, तो आपको एक रनटाइम अपवाद मिलेगा। इसलिए हमारे स्निपेट में `try/catch` उपयोगी है—यह संस्करण जाँच को OCR निष्पादन प्रवाह से अलग करता है। + +--- + +## पूर्ण कार्यशील उदाहरण (कॉपी‑पेस्ट तैयार) + +नीचे पूरा प्रोग्राम दिया गया है, जिसे आप नए कंसोल प्रोजेक्ट में डाल सकते हैं। इसमें वैकल्पिक लॉगिंग ब्लॉक शामिल है, जिससे आप कंसोल आउटपुट और संरचित लॉग दोनों को कार्य में देख सकते हैं। + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +`dotnet run` के साथ इसे चलाएँ और आपको संस्करण की पुष्टि करने वाली दो लाइनों के साथ, यदि आप `LogLevel.Debug` सक्षम करते हैं तो एक डिबग लाइन भी दिखेगी। + +--- + +## निष्कर्ष + +हमने C# वातावरण में **Aspose OCR संस्करण** प्राप्त करने के सभी पहलुओं को कवर किया है—**Aspose OCR लाइब्रेरी** को स्थापित करने से लेकर **ocrengine getversion** मेथड को कॉल करने, त्रुटियों को संभालने, और परिणाम को प्रोडक्शन‑ग्रेड लॉगिंग में एम्बेड करने तक। इस ज्ञान के साथ, आप अब अपने एप्लिकेशन द्वारा उपयोग किए जा रहे सटीक OCR बिल्ड को विश्वसनीय रूप से सत्यापित कर सकते हैं, संस्करण‑संबंधी बग्स से बच सकते हैं, और अनुपालन आवश्यकताओं को बिना किसी परेशानी के पूरा कर सकते हैं। + +अगला कदम? इस संस्करण जाँच को वास्तविक OCR कॉल (`OcrEngine` → `RecognizeImage`) के साथ जोड़ने और दोनों—संस्करण और पहचान परिणाम—को लॉग करने का प्रयास करें। आप अन्य Aspose उत्पादों (PDF, Slides, Cells) के लिए **retrieve aspose version** पैटर्न भी देख सकते हैं ताकि आपका पूरा सूट सिंक्रनाइज़ रहे। + +कोडिंग का आनंद लें, और आपकी OCR पाइपलाइन हमेशा तेज़ बनी रहे! + +## अब आप क्या सीख सकते हैं? + +निम्नलिखित ट्यूटोरियल्स उन निकट संबंधित विषयों को कवर करते हैं जो इस गाइड में प्रदर्शित तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API सुविधाओं में निपुण बनने और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण करने में मदद करती हैं। + +- [Aspose.OCR for .NET के साथ OCR परिणाम कैसे प्राप्त करें](/ocr/english/net/text-recognition/get-recognition-result/) +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ C# में इमेज टेक्स्ट निकालें](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR for .NET में सूची के साथ बैच OCR इमेज कैसे करें](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/hindi/net/ocr-optimization/_index.md index 741ae28e9..3a8017f94 100644 --- a/ocr/hindi/net/ocr-optimization/_index.md +++ b/ocr/hindi/net/ocr-optimization/_index.md @@ -74,6 +74,9 @@ Aspose.OCR for .NET के साथ OCR सटीकता बढ़ाएँ ### [OCR इमेज रिकग्निशन में मल्टी‑पेज परिणाम को दस्तावेज़ के रूप में सहेजें](./save-multipage-result-as-document/) Aspose.OCR for .NET की क्षमता को अनलॉक करें। इस व्यापक चरण‑दर‑चरण गाइड के साथ मल्टी‑पेज OCR परिणामों को दस्तावेज़ों के रूप में आसानी से सहेजें। +### [Aspose OCR C# उदाहरण – GPU सक्षम करें, मेमोरी सीमा सेट करें और TIF छवियों को प्रोसेस करें](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +GPU का उपयोग करके तेज़ OCR, मेमोरी सीमा निर्धारित करने और TIF फ़ॉर्मेट छवियों को प्रोसेस करने का पूरा C# कोड उदाहरण। + ## अक्सर पूछे जाने वाले प्रश्न **Q:** क्या मैं कई भाषाओं वाली छवि फ़ाइलों से पाठ निकाल सकता हूँ? diff --git a/ocr/hindi/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/hindi/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..608f82487 --- /dev/null +++ b/ocr/hindi/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# उदाहरण जो GPU मेमोरी सीमा सेट करने, OCR के लिए छवि लोड + करने और TIF फ़ाइलों से टेक्स्ट पहचानने को पूर्ण कोड और टिप्स के साथ दिखाता है। +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: hi +og_description: 'Aspose OCR C# का पूरा उदाहरण सीखें: GPU सक्षम करें, GPU मेमोरी सीमा + सेट करें, OCR के लिए एक छवि लोड करें और TIF फ़ाइलों से टेक्स्ट पहचानें। पूर्ण कोड + शामिल है।' +og_title: Aspose OCR C# उदाहरण – GPU त्वरण, मेमोरी सीमा और TIF प्रोसेसिंग +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# उदाहरण – GPU सक्षम करें, मेमोरी सीमा सेट करें और TIF छवियों को + प्रोसेस करें +url: /hi/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# उदाहरण – GPU सक्षम करें, मेमोरी सीमा सेट करें और TIF इमेज प्रोसेस करें + +क्या आपने कभी सोचा है कि **Aspose OCR C# example** कोड से जब बड़े‑पैमाने पर TIFF स्कैन के साथ काम किया जाए तो अधिकतम प्रदर्शन कैसे निकाला जाए? आप अकेले नहीं हैं। कई वास्तविक‑दुनिया प्रोजेक्ट्स—जैसे अभिलेखों को डिजिटल बनाना या हाई‑रिज़ॉल्यूशन रसीदों से डेटा निकालना—में बाधा OCR एल्गोरिद्म नहीं, बल्कि हार्डवेयर उपयोग है। + +बात यह है: Aspose OCR GPU एक्सेलेरेशन को सपोर्ट करता है, लेकिन आपको इसे ठीक‑ठीक बताना पड़ता है कि वह कितना मेमोरी उपयोग कर सकता है, सही इमेज टाइप लोड करना है, और अंत में .tif फ़ाइल से पहचाना गया टेक्स्ट निकालना है। यह ट्यूटोरियल आपको हर कदम से गुज़राएगा, SDK इंस्टॉल करने से लेकर GPU सेटिंग्स को ट्यून करने तक, ताकि आप OCR को तेज़ गति से चला सकें बिना GPU की RAM को भर दिए। + +हम कुछ “क्या होगा अगर” परिदृश्यों—जैसे मल्टी‑पेज TIFF को हैंडल करना या GPU न होने पर CPU पर फॉल बैक करना—को भी शामिल करेंगे, ताकि आपका समाधान मजबूत हो, सिर्फ एक‑बार का स्निपेट नहीं। + +## आपको क्या चाहिए + +डुबकी लगाने से पहले सुनिश्चित करें कि आपके मशीन पर नीचे दी गई चीज़ें मौजूद हों: + +| आवश्यकता | महत्व क्यों है | +|--------------|----------------| +| **.NET 6 SDK** (या बाद का) | Aspose OCR .NET Standard 2.0+ को टार्गेट करता है, इसलिए कोई भी नया .NET संस्करण काम करेगा। | +| **Aspose.OCR NuGet पैकेज** (`Install-Package Aspose.OCR`) | वह कोर लाइब्रेरी जो `OcrEngine`, `GpuSettings` आदि प्रदान करती है। | +| **CUDA 11+** (NVIDIA) **या ROCm 5+** (AMD) | GPU एक्सेलेरेशन के लिए आवश्यक; SDK रन‑टाइम पर संगत ड्राइवर की जाँच करेगा। | +| कम से कम **2 GB VRAM** वाला **GPU** (हम इसे 2048 MB पर सीमित करेंगे) | पर्याप्त मेमोरी न होने पर इंजन चुपचाप CPU पर फॉल बैक हो सकता है। | +| वह **हाई‑रिज़ॉल्यूशन TIFF** इमेज जिसे आप प्रोसेस करना चाहते हैं | Aspose OCR लगभग सभी रास्टर फ़ॉर्मेट पढ़ सकता है, लेकिन स्कैन के लिए TIF आम है। | +| Visual Studio 2022 (या आपका पसंदीदा एडिटर) | C# प्रोजेक्ट को बिल्ड और डिबग करने के लिए। | + +यदि इनमें से कोई भी चीज़ गायब है, तो कोड फिर भी कंपाइल होगा, लेकिन आप वह प्रदर्शन सुधार नहीं देख पाएंगे जिसकी हमें उम्मीद है। + +## चरण 1: Aspose OCR C# उदाहरण इंजन बनाएं + +हर **Aspose OCR C# example** में पहला काम OCR इंजन को इंस्टैंशिएट करना होता है। `OcrEngine` को एक फ़िल्म के डायरेक्टर की तरह समझें—यह इमेज लोडिंग से लेकर टेक्स्ट एक्सट्रैक्शन तक सब कुछ समन्वयित करता है। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **प्रो टिप:** यदि आप कई इमेज को क्रम में प्रोसेस करने वाले हैं, तो एक ही `OcrEngine` को जीवित रखें। प्रत्येक इमेज के लिए नया इंजन बनाना ओवरहेड जोड़ता है जो OCR समय से कहीं अधिक हो सकता है। + +## चरण 2: GPU मेमोरी सीमा सेट करें (और एक्सेलेरेशन सक्षम करें) + +अब वह हिस्सा आता है जो अक्सर लोगों को उलझा देता है: **GPU मेमोरी सीमा सेट करना**। डिफ़ॉल्ट रूप से Aspose OCR जितनी संभव हो उतनी VRAM उपयोग करने की कोशिश करता है, जो साझा वर्कस्टेशन पर अन्य एप्लिकेशन को भूखा छोड़ सकता है। `GpuSettings` ऑब्जेक्ट आपको इस अलोकेशन को सीमित करने देता है। + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### मेमोरी सीमा क्यों सेट करें? + +- **स्थिरता:** विशाल इमेज प्रोसेस करते समय आउट‑ऑफ़‑मेमोरी क्रैश से बचाता है। +- **सह-अस्तित्व:** अन्य GPU‑हैवी एप्लिकेशन (जैसे TensorFlow मॉडल) को साथ‑साथ चलाने की अनुमति देता है। +- **पूर्वानुमेयता:** प्रदर्शन परीक्षण दोहराने योग्य बनाता है क्योंकि GPU स्वैपिंग नहीं करेगा। + +यदि आप `MemoryLimitMb` को छोड़ देते हैं, तो Aspose आवश्यकतानुसार मेमोरी आवंटित करेगा, जो डेडिकेटेड इंफ़रेंस सर्वर पर ठीक है लेकिन डेवलपर लैपटॉप पर जोखिम भरा हो सकता है। + +## चरण 3: OCR के लिए इमेज लोड करें + +सही फ़ाइल फ़ॉर्मेट लोड करना अगला महत्वपूर्ण कदम है। `OcrImage.FromFile` मेथड स्वचालित रूप से इमेज टाइप का पता लगाता है, लेकिन आपको यह भी जाँचना चाहिए कि फ़ाइल मौजूद है और वह समर्थित TIFF वैरिएंट (जैसे LZW‑कम्प्रेस्ड या CCITT‑G4) है। + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### मल्टी‑पेज TIFF को हैंडल करना + +यदि आपका TIFF कई पेजों वाला है, तो Aspose OCR डिफ़ॉल्ट रूप से केवल पहला पेज पढ़ेगा। सभी पेजों को प्रोसेस करने के लिए आप `image.Pages` (नए SDK संस्करणों में उपलब्ध) पर लूप कर सकते हैं और प्रत्येक पेज को अलग‑अलग इंजन को फीड कर सकते हैं। + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +ऊपर दिया गया स्निपेट **OCR के लिए इमेज लोड** पैटर्न दर्शाता है जो सिंगल‑और मल्टी‑पेज दोनों फ़ाइलों के लिए काम करता है। + +## चरण 4: TIF (या किसी भी रास्टर) से टेक्स्ट पहचानें + +अब इमेज मेमोरी में है, हम Aspose को जादू करने के लिए कहते हैं। `Recognize` मेथड एक `OcrResult` लौटाता है जिसमें प्लेन टेक्स्ट, कॉन्फिडेंस स्कोर, और यदि जरूरत हो तो बाउंडिंग‑बॉक्स जानकारी भी होती है। + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### यह TIF के साथ क्यों अच्छा काम करता है + +- **लॉसलेस कम्प्रेशन:** TIFF अक्सर रॉ पिक्सेल डेटा रखता है, जिससे OCR इंजन को सबसे अधिक फिडेलिटी मिलती है। +- **कई कलर स्पेसेस:** Aspose ग्रेस्केल, RGB, या यहाँ तक कि CMYK TIFF को अतिरिक्त कन्वर्ज़न कोड के बिना संभाल सकता है। + +यदि आपको भाषा पैक (जैसे फ़्रेंच या जापानी) बदलने की जरूरत है, तो `ocrEngine.Settings.Language = "fr"` को `Recognize` कॉल से पहले सेट करें। + +## चरण 5: पहचाना गया टेक्स्ट प्रदर्शित करें + +अंत में, हम टेक्स्ट को कंसोल पर आउटपुट करते हैं। वास्तविक एप्लिकेशन में आप इसे डेटाबेस, JSON फ़ाइल, या डाउनस्ट्रीम NLP पाइपलाइन में फीड कर सकते हैं। + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### अपेक्षित आउटपुट + +300 dpi की साफ़ स्कैन की गई प्रिंटेड पेज पर प्रोग्राम चलाने पर आमतौर पर इस तरह का परिणाम मिलता है: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +यदि इमेज धुंधली है या GPU मेमोरी सीमा बहुत कम है, तो आपको गड़बड़ अक्षर या कटे‑हुए परिणाम मिल सकते हैं। `MemoryLimitMb` को इमेज के फुटप्रिंट (आमतौर पर ~1 GB for 6000×8000 pixel TIFF) से नीचे सेट करने से इंजन स्वचालित रूप से CPU पर फॉल बैक हो जाएगा। + +## पूर्ण कार्यशील उदाहरण + +नीचे पूरा, तैयार‑चलाने‑योग्य प्रोग्राम दिया गया है। इसे नई Console App प्रोजेक्ट में कॉपी‑पेस्ट करें, `YOUR_DIRECTORY/large_photo.tif` को अपनी TIFF फ़ाइल के पाथ से बदलें, और **F5** दबाएँ। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### त्वरित चेकलिस्ट + +- ✅ **Aspose OCR C# example** बिना त्रुटि के कंपाइल हुआ। +- ✅ **GPU सक्षम** (`Enable = true`)। +- ✅ **GPU मेमोरी सीमा** 2048 MB पर सेट। +- ✅ **इमेज** TIF फ़ाइल से लोड हुई। +- ✅ **टेक्स्ट पहचान** हुआ और प्रिंट हुआ। + +## सामान्य समस्याएँ और समाधान + +| लक्षण | संभावित कारण | समाधान | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA रनटाइम इंस्टॉल नहीं है या संस्करण मेल नहीं खाता। | अपने ड्राइवर से मेल खाने वाला CUDA 11.x (या 12.x) इंस्टॉल करें। | +| OCR खाली स्ट्रिंग लौटाता है | इमेज बहुत डार्क है या DPI < 150। | `image.AdjustContrast()` से प्री‑प्रोसेस करें या 300 dpi पर री‑सैंपल करें। | +| GPU पर आउट‑ऑफ़‑मेमोरी क्रैश | `MemoryLimitMb` इमेज के लिए बहुत कम है। | सीमा बढ़ाएँ या `image.Crop` से इमेज को टाइल्स में बाँटें। | +| `Unsupported image format` त्रुटि | TIFF में अजीब कम्प्रेशन (जैसे JPEG‑2000) है। | OCR से पहले ImageMagick से TIFF को समर्थित फ़ॉर्मेट में बदलें। | + +## डेमो का विस्तार + +अब आपके पास एक ठोस **aspose ocr c# example** है, आप आगे इन चीज़ों को एक्सप्लोर कर सकते हैं: + +- **बैच प्रोसेसिंग:** TIF फ़ोल्डर पर लूप चलाएँ, प्रत्येक परिणाम को `.txt` फ़ाइल में लिखें। +- **भाषा पैक:** `ocrEngine.Settings.Language = "es"` स्पेनिश के लिए, या कस्टम डिक्शनरी लोड करें। +- **बाउंडिंग बॉक्स:** `ocrResult.Regions` से प्रत्येक शब्द के कोऑर्डिनेट प्राप्त करें—रेडैक्शन टूल्स के लिए उपयोगी। +- **CPU फॉल बैक:** GPU ब्लॉक को try/catch में रखें; विफलता पर `ocrEngine.Settings.Gpu.Enable = false` सेट करके फिर से प्रयास करें। + +इन एक्सटेंशन से कोर पैटर्न वही रहता है, जबकि विशिष्ट उपयोग‑केस के लिए अतिरिक्त मूल्य जुड़ता है। + +## अगला क्या सीखें? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकते हैं और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोच को एक्सप्लोर कर सकते हैं। + +- [Aspose.OCR .NET का उपयोग करके इमेज से टेक्स्ट निकालें](/ocr/english/net/image-and-drawing-recognition/) +- [Aspose.OCR for .NET के साथ OCR ऑप्टिमाइज़ेशन](/ocr/english/net/ocr-optimization/) +- [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/hindi/net/skew-angle-calculation/_index.md b/ocr/hindi/net/skew-angle-calculation/_index.md index 2c9caab0f..40824caf7 100644 --- a/ocr/hindi/net/skew-angle-calculation/_index.md +++ b/ocr/hindi/net/skew-angle-calculation/_index.md @@ -18,7 +18,7 @@ url: /hi/net/skew-angle-calculation/ क्या आप अपने C# अनुप्रयोगों में त्रुटिहीन पाठ पहचान के लिए प्रयास कर रहे हैं? आगे कोई तलाश नहीं करें! .NET के लिए Aspose.OCR द्वारा संचालित हमारे स्क्यू एंगल कैलकुलेशन ट्यूटोरियल, आपको जटिल प्रक्रिया में कुशलता के साथ मार्गदर्शन करेंगे। ## तिरछा कोण गणना को समझना -तिरछा कोण ओसीआर छवि पहचान में महत्वपूर्ण भूमिका निभाता है, जिससे पाठ की सटीक व्याख्या सुनिश्चित होती है। हमारे ट्यूटोरियल में, हम गणना प्रक्रिया में चरण-दर-चरण अंतर्दृष्टि प्रदान करते हुए जटिलताओं को सुलझाते हैं। चाहे आप नौसिखिया हों या अनुभवी डेवलपर, बुनियादी बातों को सहजता से समझ लें। +तिरछा कोण ओसीआर छवि पहचान में महत्वपूर्ण भूमिका निभाता है, जिससे पाठ की सटीक व्याख्या सुनिश्चित होती है। हमारे ट्यूटोरियल में, हम गणना प्रक्रिया में चरण-दर-स्टेप अंतर्दृष्टि प्रदान करते हुए जटिलताओं को सुलझाते हैं। चाहे आप नौसिखिया हों या अनुभवी डेवलपर, बुनियादी बातों को सहजता से समझ लें। ## [ओसीआर छवि पहचान में तिरछा कोण की गणना करें](./calculate-skew-angle/) .NET के लिए Aspose.OCR का उपयोग करके OCR छवि पहचान में तिरछा कोण गणना में महारत हासिल करने की यात्रा शुरू करें। हमारा ट्यूटोरियल प्रक्रिया को सरल बनाता है, जिससे यह सभी स्तरों के डेवलपर्स के लिए सुलभ हो जाता है। आज ही अपनी पाठ पहचान सटीकता और दक्षता बढ़ाएँ! @@ -40,9 +40,11 @@ url: /hi/net/skew-angle-calculation/ .NET के लिए Aspose.OCR की शक्ति को उजागर करें, जो छवि पहचान के लिए एक मजबूत समाधान है। आसानी से तिरछे कोणों की गणना करना सीखें। ### [ओसीआर छवि पहचान में यूआरआई से तिरछा कोण की गणना करें](./calculate-skew-angle-from-uri/) OCR छवि पहचान में तिरछे कोणों की आसानी से गणना करने के लिए .NET के लिए Aspose.OCR का अन्वेषण करें। अपनी परियोजनाओं को सटीकता और दक्षता के साथ बढ़ाएं। +### [OCR घुमाए गए दस्तावेज़ ट्यूटोरियल – C# में ऑटो स्क्यू और रोटेशन फ़िक्स](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +.NET के लिए Aspose.OCR के साथ घुमाए गए दस्तावेज़ों में स्वचालित स्क्यू सुधार और रोटेशन ठीक करना सीखें। {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/hindi/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..3cddd472d --- /dev/null +++ b/ocr/hindi/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR का उपयोग करके C# में स्क्यू को स्वचालित रूप से सुधारने और + घुमाव का पता लगाने वाला OCR घुमाए हुए दस्तावेज़ ट्यूटोरियल। पूर्ण कोड के साथ चरण‑दर‑चरण + सीखें। +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: hi +og_description: OCR घुमाए गए दस्तावेज़ ट्यूटोरियल आपको स्वचालित रूप से स्क्यू को ठीक + करने और Aspose OCR का उपयोग करके C# में रोटेशन का पता लगाने का तरीका सिखाता है। + पूरी गाइड का पालन करें। +og_title: OCR घुमाए गए दस्तावेज़ ट्यूटोरियल – ऑटो स्क्यू और रोटेशन फ़िक्स C# में +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR घुमाए गए दस्तावेज़ ट्यूटोरियल – C# में ऑटो स्क्यू और रोटेशन फ़िक्स +url: /hi/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR घुमा हुआ दस्तावेज़ ट्यूटोरियल – C# डेवलपर्स के लिए पूर्ण गाइड + +क्या आप कभी **ocr rotated document tutorial** पर अटक गए हैं जब स्कैन किया गया फ़ॉर्म साइडवे या तिरछा आया हो? आप अकेले नहीं हैं। ये विकृत छवियां साफ़ टेक्स्ट एक्सट्रैक्शन को बिगाड़ सकती हैं, लेकिन अच्छी खबर यह है कि Aspose OCR आपके लिए इसे स्वचालित रूप से सीधा कर सकता है। + +इस चरण‑दर‑चरण गाइड में हम एक `OcrEngine` बनाएँगे, **ऑटोमैटिक स्क्यू करेक्शन** और **ऑटो डिटेक्ट रोटेशन** को चालू करेंगे, घुमा हुई छवि पर इंजन चलाएँगे, और साफ़ टेक्स्ट प्रिंट करेंगे। अंत तक आप समझेंगे कि प्रत्येक सेटिंग क्यों महत्वपूर्ण है, किन किन मामलों में इसे कैसे ट्यून करना है, और आपके पास एक तैयार‑चलाने‑योग्य C# प्रोग्राम होगा। + +## आप क्या सीखेंगे + +* .NET प्रोजेक्ट में **Aspose OCR** को इंस्टॉल और रेफ़रेंस करने का तरीका। +* `AutoCorrectSkew` और `AutoDetectRotation` को सक्षम करना क्यों एक भरोसेमंद **ocr rotated document tutorial** की कुंजी है। +* किसी भी इमेज (JPG, PNG, TIFF) को लोड करना और इंजन को भारी काम करने देना। +* मल्टी‑पेज PDFs, लो‑रेज़ोल्यूशन स्कैन, और कस्टम लैंग्वेज पैक्स को संभालने के टिप्स। + +> **Prerequisites:** Visual Studio 2022 (या कोई भी C# IDE), .NET 6+ रनटाइम, और एक वैध Aspose OCR लाइसेंस (या फ्री ट्रायल)। पहले से OCR का कोई अनुभव आवश्यक नहीं है। + +--- + +## Step 1 – Install Aspose OCR and Set Up the Project + +सबसे पहले। NuGet पैकेज प्राप्त करें: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** यदि आप ट्रायल लाइसेंस का उपयोग कर रहे हैं, तो `Aspose.OCR.lic` फ़ाइल को अपने executable के समान फ़ोल्डर में रखें, या प्रोग्रामेटिकली रजिस्टर करें `License license = new License(); license.SetLicense("Aspose.OCR.lic");`। + +एक नया कंसोल ऐप बनाएं: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +अब आपके पास हमारे **ocr rotated document tutorial** के लिए एक साफ़ स्लेट है। + +## Step 2 – Initialize the OCR Engine + +इंजन प्रक्रिया का दिल है। इसे टेक्स्ट एक्सट्रैक्शन के लिए एक स्विस‑आर्मी नाइफ़ समझें; आपको केवल यह बताना है कि कौन‑से ट्रिक्स सक्षम करने हैं। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**इन सेटिंग्स का कारण क्या है?** +* `AutoCorrectSkew` अक्षरों की बेसलाइन का विश्लेषण करता है और लाइनों को क्षैतिज बनाने के लिए छवि को पर्याप्त मात्रा में घुमाता है। +* `AutoDetectRotation` समग्र ओरिएंटेशन (0°, 90°, 180°, 270°) को देखता है और यदि पेज उल्टा है तो उसे फ़्लिप कर देता है। इनके बिना, इंजन “pɹᴉʍ” पढ़ेगा न कि “word”। + +## Step 3 – Load the Image You Want to Process + +Aspose OCR किसी भी सामान्य रास्टर फ़ॉर्मेट के साथ काम करता है। प्लेसहोल्डर पाथ को अपनी घुमा हुई फ़ॉर्म की वास्तविक लोकेशन से बदलें। + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** यदि आपको मल्टी‑पेज TIFF मिलता है, तो `OcrImage.FromMultiPageTiff(filePath)` का उपयोग करें और `image.Pages` पर लूप लगाएँ। + +## Step 4 – Run the Recognition + +अब इंजन जादू करता है। यह पहले छवि को सीधा करेगा (हमारे स्क्यू/रोटेशन फ़्लैग्स के धन्यवाद) और फिर अक्षरों को निकाल लेगा। + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +यदि आपको अंग्रेज़ी के अलावा अन्य भाषा समर्थन चाहिए, तो `Recognize` कॉल करने से पहले इसे सेट करें: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Step 5 – Output the Recognized Text + +अंत में, साफ़ टेक्स्ट को कंसोल में डंप करें—या फ़ाइल, डेटाबेस आदि में पाइप करें, जो भी आपके वर्कफ़्लो में फिट हो। + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Expected output** (मान लेते हैं कि सैंपल इमेज में “Invoice #1234” है): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +ध्यान दें कि टेक्स्ट सही ढंग से दिख रहा है जबकि स्रोत छवि 90° घुमा हुआ और थोड़ा स्क्यू था। + +--- + +## Handling Common Pitfalls + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Blank output** | Skew correction disabled or image too dark. | Enable `AutoCorrectSkew` (already on) and increase image contrast via `image.AdjustContrast(1.2)`. | +| **Garbage characters** | Wrong language setting. | Set `ocrEngine.Settings.Language` to match the document language. | +| **Performance lag on large PDFs** | Engine processes each page sequentially. | Use `Parallel.ForEach` on `image.Pages` to leverage multi‑core CPUs. | +| **License exception** | Trial expired. | Acquire a permanent license or stay within the trial limits (5 pages per run). | + +## Pro Tips for a Robust OCR Rotated Document Tutorial + +* **Batch processing:** पूरे फ्लो को एक मेथड में रैप करें जो फ़ोल्डर पाथ लेता है, हर इमेज पर लूप करता है, और प्रत्येक परिणाम को `.txt` फ़ाइल में लिखता है। +* **Pre‑processing:** कभी‑कभी शोरयुक्त स्कैन को `image.Denoise()` से पहले प्रोसेस करने से फायदा होता है। +* **Post‑processing:** सामान्य OCR गलतियों को साफ़ करने के लिए रेगुलर एक्सप्रेशन का उपयोग करें, उदाहरण के लिए, “0” को “O” से बदलें केवल तब जब वह अक्षरों के बीच हो। +* **Logging:** Aspose OCR `ocrEngine.Logger` प्रदान करता है – इसे फ़ाइल लॉगर से जोड़ें ताकि लो कॉन्फिडेंस स्कोर के बारे में वार्निंग्स कैप्चर हो सकें। + +## Complete, Ready‑to‑Run Code + +निम्नलिखित को अपने कंसोल प्रोजेक्ट के अंदर `Program.cs` के रूप में सेव करें। इसमें सभी चरण, कमेंट्स, और बैच प्रोसेसिंग के लिए एक छोटा हेल्पर शामिल है। + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Run it: + +```bash +dotnet run +``` + +आपको कंसोल में साफ़ किया हुआ टेक्स्ट प्रिंट होता दिखेगा, जिससे सिद्ध होगा कि हमारा **ocr rotated document tutorial** एंड‑टू‑एंड काम करता है। + +--- + +## Conclusion + +अब आपके पास एक पूर्ण **ocr rotated document tutorial** है जो स्वचालित रूप से स्क्यू को ठीक करता है, रोटेशन का पता लगाता है, और Aspose OCR का उपयोग करके C# में साफ़ टेक्स्ट निकालता है। मुख्य सीख? `AutoCorrectSkew` **और** `AutoDetectRotation` को सक्षम करने से एक पूरी तरह से टिल्टेड स्कैन भी कुछ ही लाइनों के कोड से पढ़ने योग्य आउटपुट में बदल जाता है। + +अब आप इसे बैच जॉब्स में विस्तारित कर सकते हैं, लैंग्वेज पैक्स इंटीग्रेट कर सकते हैं, या परिणामों को डाउनस्ट्रीम एनालिटिक्स पाइपलाइन में फीड कर सकते हैं। **ऑटोमैटिक स्क्यू करेक्शन** के बारे में और अधिक जानना चाहते हैं? Aspose की इमेज प्री‑प्रोसेसिंग API देखें, या शोरयुक्त स्कैन के लिए कस्टम थ्रेशहोल्ड्स के साथ प्रयोग करें। + +PDFs, मल्टी‑पेज TIFFs, या Azure Functions के साथ इंटीग्रेशन के बारे में सवाल हैं? टिप्पणी छोड़ें, और हैप्पी कोडिंग! + +## What Should You Learn Next? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन एप्रोच को एक्सप्लोर कर सकें। + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/hindi/net/text-recognition/_index.md index 0512ee10e..a8e36a665 100644 --- a/ocr/hindi/net/text-recognition/_index.md +++ b/ocr/hindi/net/text-recognition/_index.md @@ -27,7 +27,7 @@ url: /hi/net/text-recognition/ ## OCR छवि पहचान में JSON के रूप में परिणाम प्राप्त करें -आसानी से JSON प्रारूप में OCR परिणाम प्राप्त करने का तरीका सीखकर .NET के लिए Aspose.OCR की पूरी क्षमता का उपयोग करें। यह चरण-दर-चरण मार्गदर्शिका आपकी छवि पहचान क्षमताओं को बढ़ाने की दिशा में एक सहज यात्रा सुनिश्चित करती है। Aspose.OCR की मजबूत विशेषताओं और उद्योग-अग्रणी तकनीक के साथ अपने एप्लिकेशन की दक्षता बढ़ाएँ। +आसानी से JSON प्रारूप में OCR परिणाम प्राप्त करने का तरीका सीखकर .NET के लिए Aspose.OCR की पूरी क्षमता का उपयोग करें। यह चरण-दर-स्टेप मार्गदर्शिका आपकी छवि पहचान क्षमताओं को बढ़ाने की दिशा में एक सहज यात्रा सुनिश्चित करती है। Aspose.OCR की मजबूत विशेषताओं और उद्योग-अग्रणी तकनीक के साथ अपने एप्लिकेशन की दक्षता बढ़ाएँ। ## ओसीआर छवि पहचान में ओसीआर डिटेक्ट एरिया मोड @@ -44,20 +44,31 @@ Aspose.OCR के साथ .NET में OCR की क्षमता को क्या आप अपने .NET अनुप्रयोगों में क्रांति लाने के लिए तैयार हैं? हमारे टेक्स्ट रिकग्निशन ट्यूटोरियल्स में गोता लगाएँ और छवियों में सटीक और कुशल टेक्स्ट पहचान के लिए Aspose.OCR की शक्ति का उपयोग करें। अभी डाउनलोड करें और उन्नत ओसीआर क्षमताओं की यात्रा पर निकलें। ## पाठ पहचान ट्यूटोरियल ### [ओसीआर छवि पहचान में मान्यता प्राप्त पात्रों के लिए विकल्प प्राप्त करें](./get-choices-for-recognized-characters/) -सटीक चरित्र पहचान के लिए Aspose.OCR के साथ अपने .NET अनुप्रयोगों को बेहतर बनाएं। छवि पहचान में मान्यता प्राप्त पात्रों के विकल्प पुनः प्राप्त करने के लिए हमारी चरण-दर-चरण मार्गदर्शिका का पालन करें। +सटीक चरित्र पहचान के लिए Aspose.OCR के साथ अपने .NET अनुप्रयोगों को बेहतर बनाएं। छवि पहचान में मान्यता प्राप्त पात्रों के विकल्प पुनः प्राप्त करने के लिए हमारी चरण-दर-स्टेप मार्गदर्शिका का पालन करें। ### [ओसीआर छवि पहचान में मान्यता परिणाम प्राप्त करें](./get-recognition-result/) .NET के लिए Aspose.OCR का अन्वेषण करें, जो छवियों में निर्बाध पाठ पहचान के लिए एक शक्तिशाली OCR समाधान है। ### [OCR छवि पहचान में JSON के रूप में परिणाम प्राप्त करें](./get-result-as-json/) -.NET के लिए Aspose.OCR की शक्ति को उजागर करें। JSON प्रारूप में OCR परिणाम सहजता से प्राप्त करना सीखें। इस चरण-दर-चरण मार्गदर्शिका के साथ अपनी छवि पहचान बढ़ाएँ। +.NET के लिए Aspose.OCR की शक्ति को उजागर करें। JSON प्रारूप में OCR परिणाम सहजता से प्राप्त करना सीखें। इस चरण-दर-स्टेप मार्गदर्शिका के साथ अपनी छवि पहचान बढ़ाएँ। ### [ओसीआर छवि पहचान में ओसीआर डिटेक्ट एरिया मोड](./ocr-detect-areas-mode/) कुशल छवि पाठ पहचान के लिए Aspose.OCR के साथ अपने .NET अनुप्रयोगों को बेहतर बनाएं। सटीक परिणामों के लिए ओसीआर डिटेक्ट एरिया मोड का अन्वेषण करें। ### [ओसीआर छवि पहचान में पीडीएफ को पहचानें](./recognize-pdf/) Aspose.OCR के साथ .NET में OCR की क्षमता को अनलॉक करें। पीडीएफ़ से आसानी से टेक्स्ट निकालें। सहज एकीकरण अनुभव के लिए अभी डाउनलोड करें। +### [Aspose OCR के साथ PDF पर OCR करें – पूर्ण C# गाइड](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Aspose.OCR का उपयोग करके PDF फ़ाइलों से टेक्स्ट निकालें और C# में पूर्ण चरण-दर-स्टेप मार्गदर्शिका प्राप्त करें। ### [ओसीआर छवि पहचान में तालिका को पहचानें](./recognize-table/) OCR छवि पहचान में तालिकाओं को पहचानने पर हमारे व्यापक गाइड के साथ .NET के लिए Aspose.OCR की क्षमता को अनलॉक करें। +### [Aspose OCR के साथ छवि पर OCR करें – हिंदी गाइड](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Aspose OCR का उपयोग करके छवि से टेक्स्ट निकालने की प्रक्रिया को चरण-दर-स्टेप सीखें। +### [Aspose का उपयोग कैसे करें: OCR के साथ छवि को HTML में परिवर्तित करें](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Aspose.OCR का उपयोग करके छवि को HTML में बदलें और OCR परिणाम प्राप्त करें। चरण-दर-स्टेप मार्गदर्शिका। +### [छवि पर OCR करें और C# में गलत वर्तनी वाले शब्दों का पता लगाएँ](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Aspose.OCR का उपयोग करके छवि से टेक्स्ट निकालें और C# में गलत वर्तनी वाले शब्दों की पहचान करने की प्रक्रिया सीखें। +### [वीडियो सबटाइटल OCR C# में – पूर्ण गाइड](./video-subtitle-ocr-in-c-complete-guide/) +C# में वीडियो सबटाइटल OCR करने के लिए पूर्ण गाइड, Aspose.OCR का उपयोग करके सबटाइटल से टेक्स्ट निकालें। + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/hindi/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..c4d8cfd50 --- /dev/null +++ b/ocr/hindi/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-03 +description: Aspose का उपयोग करके इमेज को HTML में बदलना और C# में इमेज से टेक्स्ट + निकालना कैसे करें। इमेज से HTML जनरेट करना और OCR इमेज को जल्दी से HTML में बदलना + सीखें। +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: hi +og_description: Aspose का उपयोग करके इमेज को HTML में बदलना, इमेज से टेक्स्ट निकालना, + और OCR के साथ इमेज से HTML जेनरेट करना C# में कैसे करें। इस पूर्ण गाइड का पालन करें। +og_title: 'Aspose का उपयोग कैसे करें: OCR के साथ इमेज को HTML में बदलें' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Aspose का उपयोग कैसे करें: OCR के साथ छवि को HTML में परिवर्तित करें' +url: /hi/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose का उपयोग कैसे करें: OCR के साथ इमेज को HTML में बदलें + +क्या आप कभी **how to use Aspose** को स्कैन की हुई तस्वीर को साफ़ HTML में बदलने के लिए? शायद आपके पास कोई मैगज़ीन पेज, रसीद, या हाथ से लिखा नोट है और आपको वेब पब्लिशिंग के लिए टेक्स्ट और लेआउट को संरक्षित रखना है। अच्छी खबर यह है कि आपको कस्टम पार्सर लिखने या लो‑लेवल इमेज प्रोसेसिंग से जूझने की जरूरत नहीं है—Aspose.OCR आपके लिए यह काम कर देता है। + +इस ट्यूटोरियल में हम एक **complete, runnable example** के माध्यम से चलेंगे जो आपको दिखाता है कि Aspose OCR लाइब्रेरी को C# में उपयोग करके **convert image to HTML**, **extract text from image**, और **generate HTML from image** कैसे किया जाता है। अंत तक आपके पास एक छोटा कंसोल ऐप होगा जो मूल पेज लेआउट को बरकरार रखते हुए एक HTML फ़ाइल बनाता है, जिसे आप किसी भी वेबसाइट में आसानी से जोड़ सकते हैं। + +## आवश्यकताएँ + +- **.NET 6.0 SDK** या बाद का (कोड .NET Core और .NET Framework दोनों के साथ काम करता है)। +- **Visual Studio 2022** (या कोई भी एडिटर जो आपको पसंद हो)। +- **Aspose.OCR for .NET** – NuGet के माध्यम से इंस्टॉल करें: `dotnet add package Aspose.OCR`। +- वह इमेज फ़ाइल (JPEG/PNG) जिसे आप ट्रांसफ़ॉर्म करना चाहते हैं, जैसे `magazine_page.jpg`। + +कोई अतिरिक्त कॉन्फ़िगरेशन फ़ाइलों की आवश्यकता नहीं है; लाइब्रेरी OCR और HTML लेआउट जेनरेशन के लिए आवश्यक सभी चीज़ें साथ में देती है। + +## चरण 1: प्रोजेक्ट सेट अप करें और Aspose.OCR जोड़ें + +सबसे पहले, एक नया कंसोल प्रोजेक्ट बनाएं और Aspose OCR पैकेज को जोड़ें। + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** यदि आप Visual Studio का उपयोग कर रहे हैं, तो बस प्रोजेक्ट पर राइट‑क्लिक करें → *Manage NuGet Packages* → **Aspose.OCR** खोजें और इसे इंस्टॉल करें। यह कदम सुनिश्चित करता है कि आप **ocr image to html** बिना किसी मिसिंग रेफ़रेंस के कर सकें। + +## चरण 2: OCR इंजन को इनिशियलाइज़ करें + +प्रक्रिया का मुख्य भाग `OcrEngine` क्लास है। इसे आप उस दिमाग की तरह समझ सकते हैं जो तस्वीर को पढ़ता है और परिणाम को कैसे आउटपुट करना है, तय करता है। + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +यहाँ हम `OcrEngine` को इंस्टैंशिएट करते हैं। फ्री वर्ज़न के लिए आपको कोई क्रेडेंशियल पास करने की ज़रूरत नहीं है; लाइब्रेरी अपने बिल्ट‑इन रिकग्निशन मॉडल का उपयोग करेगी। + +## चरण 3: स्रोत इमेज लोड करें + +अब, इंजन को उस फ़ाइल की ओर इंगित करें जिसे आप प्रोसेस करना चाहते हैं। Aspose एक सुविधाजनक `OcrImage.FromFile` मेथड प्रदान करता है जो अधिकांश इमेज फ़ॉर्मेट को संभालता है। + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +`YOUR_DIRECTORY` को उस एब्सोल्यूट या रिलेटिव पाथ से बदलें जहाँ आपकी इमेज स्थित है। यदि इमेज एक्सीक्यूटेबल के समान फ़ोल्डर में है, तो आप बस `"magazine_page.jpg"` का उपयोग कर सकते हैं। + +## चरण 4: लेआउट के साथ HTML रिकग्नाइज़ और अनुरोध करें + +यह ट्यूटोरियल का मुख्य भाग है। `OutputFormat.HtmlWithLayout` पास करके हम Aspose को **generate HTML from image** करने के लिए कहते हैं, जबकि टेक्स्ट ब्लॉक्स, इमेजेज, और टेबल्स की मूल पोज़िशनिंग को बरकरार रखते हैं। + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text` प्रॉपर्टी अब एक पूर्ण HTML दस्तावेज़ रखती है। यदि आपको केवल प्लेन टेक्स्ट चाहिए होता, तो आप `OutputFormat.Text` का उपयोग कर सकते थे, लेकिन हम लेआउट फ़िडेलिटी के साथ **convert image to html** पर फोकस कर रहे हैं। + +## चरण 5: HTML फ़ाइल सहेजें + +अंत में, HTML स्ट्रिंग को डिस्क पर लिखें। इससे आपको एक तैयार‑उपयोग फ़ाइल मिलती है जिसे आप किसी भी ब्राउज़र में खोल सकते हैं। + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +प्रोग्राम चलाने पर `magazine.html` बनेगा। इसे खोलें, और आप देखेंगे कि मूल पेज का टेक्स्ट ठीक उसी तरह पोज़िशन किया गया है जैसा स्रोत इमेज में था—आर्काइविंग या वेब पब्लिशिंग के लिए परफेक्ट। + +## पूर्ण कार्यशील उदाहरण + +नीचे **complete, copy‑paste‑ready** प्रोग्राम दिया गया है। कोई भाग छोड़ा नहीं गया है, इसलिए आप सही पाथ सेट करने के बाद तुरंत इसे कंपाइल और रन कर सकते हैं। + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### अपेक्षित आउटपुट + +जब आप ब्राउज़र में `magazine.html` खोलेंगे, तो आपको कुछ इस तरह दिखना चाहिए (सरलीकृत उदाहरण के लिए): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +सटीक `style` एट्रिब्यूट्स मूल इमेज पर निर्भर करेंगे, लेकिन संरचना यह सुनिश्चित करती है कि **extract text from image** और **generate html from image** एक ही सहज चरण में हों। + +## सामान्य प्रश्न और किनारे के मामलों + +### अगर इमेज लो‑रेज़ोल्यूशन है तो क्या? + +Aspose.OCR उन इमेजेज़ के साथ सबसे अच्छा काम करता है जिनकी रेज़ोल्यूशन कम से कम **300 DPI** हो। यदि आपकी फ़ाइल धुंधली है, तो OCR इंजन को फीड करने से पहले इसे किसी इमेज‑एन्हांसमेंट लाइब्रेरी (जैसे ImageSharp) से प्री‑प्रोसेस करने की कोशिश करें। लो क्वालिटी दोनों **extract text from image** की सटीकता और जेनरेटेड HTML लेआउट की फ़िडेलिटी को प्रभावित कर सकती है। + +### क्या मैं OCR की भाषा नियंत्रित कर सकता हूँ? + +हाँ। `Recognize` कॉल करने से पहले `OcrEngine` पर `Language` प्रॉपर्टी सेट करें: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +यह गैर‑इंग्लिश कैरेक्टर्स के साथ काम करते समय रिकग्निशन को बेहतर बनाता है। + +### मैं HTML के बजाय प्लेन टेक्स्ट कैसे प्राप्त करूँ? + +यदि आपको केवल रॉ स्ट्रिंग चाहिए, तो `OutputFormat.HtmlWithLayout` को `OutputFormat.Text` से बदल दें। तब वही `recognitionResult.Text` केवल निकाले गए कैरेक्टर्स रखेगा। + +### क्या जेनरेटेड HTML में इमेजेज़ एम्बेड करने का कोई तरीका है? + +Aspose.OCR `OutputFormat.HtmlWithLayoutAndImages` उपयोग करने पर मूल इमेज को बेस‑64 डेटा URI के रूप में एम्बेड कर सकता है। यह तब उपयोगी होता है जब आप एक सिंगल HTML फ़ाइल चाहते हैं बिना बाहरी एसेट्स के। + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### बड़े बैच को कैसे हैंडल करें? + +बैच प्रोसेसिंग के लिए, लॉजिक को फ़ाइल पाथ की लिस्ट पर `foreach` लूप में रैप करें। समान `OcrEngine` इंस्टेंस को पुनः उपयोग करने से ओवरहेड कम होता है और **convert image to html** पाइपलाइन तेज़ होती है। + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## प्रोडक्शन‑रेडी कोड के लिए टिप्स + +- **Dispose resources**: दोनों `OcrEngine` और `OcrImage` `IDisposable` को इम्प्लीमेंट करते हैं। उन्हें `using` स्टेटमेंट्स में रैप करें ताकि नेटिव मेमोरी तुरंत फ्री हो सके। +- **Error handling**: फ़ाइल‑संबंधी समस्याओं के लिए `IOException` और रिकग्निशन समस्याओं के लिए `OcrException` को कैच करें। +- **Performance**: यदि आप कई इमेजेज़ प्रोसेस करते हैं, तो **parallelism** (`Parallel.ForEach`) को एनेबल करने पर विचार करें, लेकिन CPU उपयोग का ध्यान रखें—OCR CPU‑इंटेंसिव है। +- **Logging**: एक लॉगर (जैसे Serilog) इंटीग्रेट करें ताकि OCR कॉन्फिडेंस स्कोर (`recognitionResult.Confidence`) को क्वालिटी मॉनिटरिंग के लिए कैप्चर किया जा सके। + +## निष्कर्ष + +हमने अभी **how to use Aspose** को **convert image to HTML**, **extract text from image**, और **generate HTML from image** कुछ सरल चरणों में कवर किया है। पूर्ण कोड सैंपल आपको दिखाता है कि कैसे **ocr image to html** लेआउट को बरकरार रखते हुए किया जाता है, जिससे यह किसी भी डॉक्यूमेंट‑डिजिटाइज़ेशन प्रोजेक्ट के लिए एक ठोस आधार बन जाता है। + +From here you might: + +- अपनी ज़रूरतों के अनुसार विभिन्न `OutputFormat` विकल्पों के साथ प्रयोग करें। +- HTML आउटपुट को एक CSS फ्रेमवर्क के साथ मिलाकर रिस्पॉन्सिव स्टाइलिंग बनाएं। +- निकाले गए टेक्स्ट को सर्च इंडेक्स या मशीन‑लर्निंग पाइपलाइन में फीड करें। + +इसे आज़माएँ, सेटिंग्स को ट्यून करें, और देखें कि Aspose कैसे आसानी से तस्वीरों को वेब‑रेडी कंटेंट में बदलता है। अगर आपको कोई समस्या आती है, तो कमेंट छोड़ें—हैप्पी कोडिंग! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और स्टेप‑बाय‑स्टेप एक्सप्लानेशन शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर करने में मदद करेंगे। + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ इमेज टेक्स्ट निकालें (C#)](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [इमेज को टेक्स्ट में बदलें – URL से इमेज पर OCR करें](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Aspose OCR के साथ कई भाषाओं के लिए टेक्स्ट इमेज को पहचानें](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/hindi/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..207c5aad5 --- /dev/null +++ b/ocr/hindi/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR का उपयोग करके छवि पर OCR करें और छवि से पाठ निकालें। एक ही + C# डेमो में गलत वर्तनी वाले शब्दों का पता लगाना और वर्तनी सुझाव प्राप्त करना सीखें। +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: hi +og_description: छवि पर OCR करके पाठ निकालें, फिर गलत वर्तनी वाले शब्दों का पता लगाएँ + और Aspose.OCR के साथ C# में वर्तनी सुझाव प्राप्त करें। +og_title: छवि पर OCR करें और C# में गलत वर्तनी वाले शब्दों का पता लगाएँ +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: इमेज पर OCR करें और C# में गलत वर्तनी वाले शब्दों का पता लगाएँ +url: /hi/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेज पर OCR करें और C# में गलत वर्तनी वाले शब्दों का पता लगाएँ + +क्या आपने कभी सोचा है कि **इमेज फ़ाइलों पर OCR कैसे करें** बिना सिरदर्द के? आप अकेले नहीं हैं। चाहे आप पुराने पत्रों को डिजिटल बना रहे हों, रसीदें स्कैन कर रहे हों, या एक स्मार्ट डॉक्यूमेंट वर्कफ़्लो बना रहे हों, तस्वीरों से साफ़ टेक्स्ट निकालना पहला बाधा है। अच्छी खबर? Aspose.OCR के साथ आप मिनटों में एक समाधान तैयार कर सकते हैं, और बोनस यह है कि आप **गलत वर्तनी वाले शब्दों का पता लगा सकते हैं** और **स्पेलिंग सुझाव** भी उसी रन में प्राप्त कर सकते हैं। + +इस ट्यूटोरियल में हम एक पूर्ण, तैयार‑चलाने‑योग्य C# कंसोल ऐप के माध्यम से **इमेज से टेक्स्ट निकालना**, अंग्रेज़ी स्पेल‑चेकर चलाना, और प्रत्येक त्रुटि को उपयोगी सुधार विचारों के साथ प्रिंट करना सीखेंगे। अंत तक आप बिल्कुल जानेंगे **टेक्स्ट कैसे निकालें**, स्पेल‑चेक API को कैसे जोड़ें, और अपेक्षित कंसोल आउटपुट कैसा दिखेगा। + +## आप क्या बनाएँगे + +- एक बिटमैप (या PNG) लोड करेंगे जिसमें टाइपो हों। +- Aspose.OCR चलाएँगे **इमेज पर OCR करने** और कच्चा स्ट्रिंग डेटा प्राप्त करेंगे। +- बिल्ट‑इन अंग्रेज़ी स्पेल‑चेकर को इनिशियलाइज़ करेंगे। +- **गलत वर्तनी वाले शब्दों का पता लगाएँ** और प्रत्येक के लिए **स्पेलिंग सुझाव** प्राप्त करें। +- कंसोल पर एक साफ़ रिपोर्ट प्रिंट करें। + +कोई बाहरी सर्विस नहीं, कोई जटिल HTTP कॉल नहीं—सिर्फ एक NuGet पैकेज और कुछ लाइनों का कोड। + +## पूर्वापेक्षाएँ + +- .NET 6.0 SDK या बाद का (कोड .NET Framework 4.7+ पर भी काम करता है)। +- Visual Studio 2022 (या कोई भी पसंदीदा एडिटर)। +- Aspose.OCR for .NET NuGet पैकेज (`Aspose.OCR`)। +- एक इमेज फ़ाइल (`letter_with_typos.png`) जिसे आप प्रोजेक्ट से रेफ़र कर सकें। + +यदि आपने पहले Aspose का उपयोग नहीं किया है, तो चिंता न करें—पैकेज इंस्टॉल करना इतना आसान है जितना चलाना: + +```bash +dotnet add package Aspose.OCR +``` + +अब कार्यान्वयन में डुबकी लगाएँ। + +## चरण 1: प्रोजेक्ट सेट अप करें और Aspose.OCR इंस्टॉल करें + +एक नया कंसोल प्रोजेक्ट बनाएँ और OCR लाइब्रेरी को जोड़ें: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +रीस्टोर पूरा होने के बाद, `Program.cs` खोलें। हम बाद में डिफ़ॉल्ट कंटेंट को पूर्ण डेमो कोड से बदलेंगे, लेकिन पहले समझते हैं कि प्रत्येक नेमस्पेस क्यों महत्वपूर्ण है। + +- `Aspose.OCR` – कोर OCR इंजन और इमेज हैंडलिंग। +- `Aspose.OCR.SpellCheck` – लाइब्रेरी के साथ आने वाले स्पेल‑चेकिंग यूटिलिटीज़। +- `System` – स्टैंडर्ड .NET बेस क्लासेज (जैसे `Console`)। + +## चरण 2: इमेज लोड करें और इमेज पर OCR करें + +पहला वास्तविक काम इमेज को OCR इंजन को देना है। Aspose.OCR कई फ़ॉर्मैट (PNG, JPEG, TIFF) पढ़ता है। यहाँ वह स्निपेट है जो भारी काम करता है: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **यह क्यों महत्वपूर्ण है:** `OcrImage.FromFile` पिक्सेल‑लेवल विवरणों को एब्स्ट्रैक्ट करता है, जबकि `OcrEngine.Recognize` प्रशिक्षित न्यूरल मॉडल को चलाता है जो विज़ुअल ग्लिफ़ को यूनिकोड कैरेक्टर्स में बदलता है। `ocrResult.Text` प्रॉपर्टी अब कच्चा स्ट्रिंग रखती है—बिल्कुल वही जो आपको **इमेज से टेक्स्ट निकालने** के लिए चाहिए। + +> **प्रो टिप:** यदि आपकी इमेज में कई भाषाएँ हैं, तो `Recognize` कॉल करने से पहले `ocrEngine.Language = OcrLanguage.Multilingual;` सेट कर सकते हैं। + +## चरण 3: अंग्रेज़ी स्पेल‑चेकर को इनिशियलाइज़ करें + +Aspose.OCR एक बिल्ट‑इन स्पेल‑चेकिंग इंजन के साथ आता है जो डिफ़ॉल्ट रूप से अंग्रेज़ी समझता है। इसे इनिशियलाइज़ करना एक‑लाइनर है: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **यह कदम क्यों ज़रूरी है:** OCR आउटपुट में गलत पहचान वाले कैरेक्टर्स (जैसे “l” बनाम “1”) या स्रोत दस्तावेज़ की वास्तविक टाइपो हो सकते हैं। स्पेल‑चेकर स्ट्रिंग को स्कैन करेगा, संदिग्ध टोकन ढूँढेगा, और वैकल्पिक शब्द सुझाएगा। + +## चरण 4: गलत वर्तनी वाले शब्दों का पता लगाएँ और स्पेलिंग सुझाव प्राप्त करें + +अब हम OCR टेक्स्ट को चेकर में फीड करेंगे: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` एक कलेक्शन है जहाँ प्रत्येक एंट्री में त्रुटिपूर्ण शब्द और संभावित सुधारों की एरे होती है। + +## चरण 5: परिणाम आउटपुट करें + +अंत में, हम कलेक्शन पर इटररेट करेंगे और एक मानव‑पठनीय रिपोर्ट प्रिंट करेंगे: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### अपेक्षित कंसोल आउटपुट + +मान लीजिए `letter_with_typos.png` में यह वाक्य है: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +डेमो चलाने पर कुछ इस प्रकार का आउटपुट मिलेगा: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +ध्यान दें कि प्रत्येक टाइपो के साथ कुछ संभावित सुधार जुड़े होते हैं—बिल्कुल वही जो आप एक यूज़र‑फ्रेंडली करेक्शन UI बनाते समय चाहते हैं। + +## पूर्ण कार्यशील उदाहरण + +नीचे **पूरा, कॉपी‑पेस्ट‑तैयार** प्रोग्राम दिया गया है। `YOUR_DIRECTORY` को अपनी इमेज फ़ाइल के वास्तविक पाथ से बदलें। + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **विचार करने योग्य किनारे के मामले** +> - **खाली इमेज:** यदि OCR इंजन खाली स्ट्रिंग लौटाता है, तो `spellChecker.Check` बस एक खाली कलेक्शन रिटर्न करेगा—कोई क्रैश नहीं। +> - **गैर‑अंग्रेज़ी टेक्स्ट:** `OcrLanguage.English` को `OcrLanguage.French` (या कोई भी सपोर्टेड भाषा) से बदलें ताकि अन्य लोकेल में **गलत वर्तनी वाले शब्दों का पता लगाएँ**। +> - **बड़ी दस्तावेज़:** मल्टी‑पेज PDFs के लिए आप प्रत्येक पेज पर लूप करेंगे, OCR करेंगे, फिर स्पेल‑चेकिंग से पहले परिणामों को एग्रीगेट करेंगे। + +## विज़ुअल ओवरव्यू (इमेज Alt Text) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*ऊपर का डायग्राम एंड‑टू‑एंड पाइपलाइन को दर्शाता है: इमेज → OCR इंजन → कच्चा टेक्स्ट → स्पेल‑चेकर → सुझाव।* + +## सामान्य प्रश्न एवं प्रो टिप्स + +| प्रश्न | उत्तर | +|----------|--------| +| **क्या मुझे इंटरनेट कनेक्शन चाहिए?** | नहीं। Aspose.OCR पूरी तरह लोकली चलता है; ऑफ़लाइन या सुरक्षित वातावरण के लिए परफेक्ट। | +| **स्पेल‑चेकर की सटीकता कितनी है?** | यह लगभग 150k अंग्रेज़ी शब्दों की डिक्शनरी और फ़ज़ी मैचिंग का उपयोग करता है, इसलिए अधिकांश सामान्य टाइपो पकड़े जाते हैं। | +| **क्या मैं डिक्शनरी को कस्टमाइज़ कर सकता हूँ?** | हाँ। `SpellChecker.AddUserDictionary("custom.txt")` से आप डोमेन‑स्पेसिफिक टर्म्स (जैसे प्रोडक्ट नाम) लोड कर सकते हैं। | +| **अगर इमेज स्क्यू हो तो?** | OCR इंजन ऑटो‑डिटेक्ट्स ओरिएंटेशन, लेकिन आप जिद्दी केस में `ocrEngine.ImagePreprocessing.Rotate(angle)` को मैन्युअली कॉल कर सकते हैं। | +| **क्या UI में सुझावों को हाईलाइट करने का तरीका है?** | `misspellings` कलेक्शन मिलने के बाद आप प्रत्येक `entry.Word` को `ocrResult.Text` में उसकी पोज़ीशन से मैप कर सकते हैं और RichTextBox या वेब व्यू में अंडरलाइन कर सकते हैं। | + +## निष्कर्ष + +हमने अभी दिखाया **इमेज पर OCR कैसे करें**, **इमेज से टेक्स्ट निकालें**, और फिर **गलत वर्तनी वाले शब्दों का पता लगाएँ** तथा **स्पेलिंग सुझाव प्राप्त करें**—सभी एक संक्षिप्त C# कंसोल ऐप के साथ। मुख्य विचार सरल है: Aspose.OCR को कैरेक्टर पहचान का भारी काम करने दें, फिर उसके बिल्ट‑इन स्पेल‑चेकर से आउटपुट को साफ़ करें। अब आप इस डेमो को एक पूर्ण‑फ़ीचर डॉक्यूमेंट प्रोसेसिंग सर्विस में बदल सकते हैं, वेब API के साथ इंटीग्रेट कर सकते हैं, या डेस्कटॉप एडिटर में प्लग‑इन बना सकते हैं। + +अगला कदम उठाने के लिए तैयार हैं? भाषा को स्पेनिश में बदलें, मल्टी‑पेज PDF फ़ीड करें, या एक छोटा WPF फ्रंट‑एंड बनाएं जो यूज़र को शब्द पर क्लिक करके सुझाव स्वीकार करने की सुविधा दे। बिल्डिंग ब्लॉक्स पहले से ही मौजूद हैं—बस प्रयोग करते रहें। + +यदि आपको कोई समस्या आती है या एक्सटेंशन के लिए आइडिया है, तो नीचे कमेंट करें। हैप्पी कोडिंग! + +## आगे आप क्या सीखें? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/hindi/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..2a23cae76 --- /dev/null +++ b/ocr/hindi/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: C# में Aspose OCR का उपयोग करके छवि पर OCR करें। जानें कि OCR के लिए + छवि कैसे लोड करें और चरण‑दर‑चरण कोड के साथ ऑफ़लाइन हिंदी टेक्स्ट निकालें। +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: hi +og_description: C# में Aspose OCR के साथ छवि पर OCR करें। यह ट्यूटोरियल दिखाता है + कि OCR के लिए छवि कैसे लोड करें और ऑफ़लाइन हिंदी टेक्स्ट निकालें, पूरी तरह चलाने + योग्य कोड के साथ। +og_title: छवि पर OCR करें – Aspose OCR हिंदी गाइड +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Aspose OCR के साथ छवि पर OCR करें – हिंदी गाइड +url: /hi/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR के साथ इमेज पर OCR करें – हिंदी गाइड + +क्या आपको कभी **इमेज पर OCR करना** पड़ा है लेकिन हिंदी अक्षर निकालने में अटक गए थे? आप अकेले नहीं हैं—कई डेवलपर्स को पहली बार गैर‑लैटिन स्क्रिप्ट पढ़ते समय यही समस्या आती है। अच्छी बात यह है कि Aspose OCR इसे काफी आसान बनाता है, और आप इसे पूरी तरह ऑफ़लाइन भी कर सकते हैं। + +इस गाइड में हम **OCR के लिए इमेज लोड करेंगे**, इंजन को आपके ऑफ़लाइन भाषा पैक्स की ओर इंगित करेंगे, और अंत में **हिंदी टेक्स्ट इमेज** डेटा निकालेंगे बिना इंटरनेट के उपयोग के। अंत तक आपके पास एक तैयार‑चलाने योग्य C# कंसोल एप्लिकेशन होगा जो हिंदी रसीद पढ़ेगा और टेक्स्ट को कंसोल में प्रिंट करेगा। + +## आप को क्या चाहिए + +- **.NET 6.0** या बाद का संस्करण (कोड .NET Framework 4.7+ पर भी काम करता है) +- **Aspose.OCR for .NET** NuGet पैकेज + `dotnet add package Aspose.OCR` +- एक फ़ोल्डर जिसमें **ऑफ़लाइन हिंदी भाषा संसाधन** हों (Aspose पोर्टल से डाउनलोड करें) +- हिंदी टेक्स्ट वाली इमेज फ़ाइल, उदाहरण के लिए `receipt_hindi.png` + +बस इतना ही—कोई बाहरी सेवा नहीं, कोई API कुंजी नहीं, सिर्फ सीधा‑सरल कोड। + +## इमेज पर OCR करें – चरण‑दर‑चरण कार्यान्वयन + +नीचे हम प्रक्रिया को सात स्पष्ट चरणों में विभाजित करेंगे। प्रत्येक चरण को **क्यों** महत्वपूर्ण है, यह समझाते हुए बताया गया है, न कि केवल **क्या** टाइप करना है। + +### चरण 1: OCR इंजन इंस्टेंस बनाएं + +इंजन Aspose OCR का हृदय है। इसे इंस्टैंसिएट करने से आपको सभी सेटिंग्स तक पहुँच मिलती है जिन्हें आप बाद में समायोजित करेंगे। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **क्यों?** +> बिना `OcrEngine` के आपके पास `Recognize` कॉल करने के लिए कोई ऑब्जेक्ट नहीं होगा। इसे उस “कैमरा” की तरह समझें जो बाद में आपकी तस्वीर स्कैन करेगा। + +### चरण 2: इंजन को ऑफ़लाइन संसाधनों की ओर इंगित करें + +Aspose भाषा पैक्स प्रदान करता है जिन्हें आप स्थानीय रूप से संग्रहीत कर सकते हैं। `ResourcesFolder` सेट करने से इंजन को पता चलता है कि कहां देखना है। + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **टिप:** +> विकास के दौरान एक पूर्ण पथ (absolute path) उपयोग करें, फिर उत्पादन के लिए सापेक्ष पथ (relative path) या कॉन्फ़िगरेशन सेटिंग में बदलें। + +### चरण 3: ऑफ़लाइन मोड को मजबूर करें + +आप सोच सकते हैं, “क्या मुझे ऑनलाइन लुकअप को निष्क्रिय करना वास्तव में जरूरी है?” +यदि आप फ़ायरवॉल के पीछे काम कर रहे हैं या केवल निश्चित परिणाम चाहते हैं, तो `UseOfflineResources` को `true` सेट करें। + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **प्रो टिप:** +> इस फ़्लैग को `false` रहने देने से इंजन अतिरिक्त डेटा डाउनलोड कर सकता है, जिससे लेटेंसी बढ़ती है और सुरक्षा नीतियों का उल्लंघन हो सकता है। + +### चरण 4: पहचान भाषा के रूप में हिंदी चुनें + +यहाँ हम इंजन को बताकर **हिंदी टेक्स्ट इमेज** निकालते हैं कि कौन सी भाषा की अपेक्षा करनी है। इससे सटीकता में काफी सुधार होता है। + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **क्यों मदद करता है:** +> OCR इंजन भाषा‑विशिष्ट कैरेक्टर मॉडल का उपयोग करते हैं। हिंदी को लॉक करके, आप इंजन को दर्जनों स्क्रिप्ट्स में अनुमान लगाने से बचाते हैं। + +### चरण 5: OCR के लिए इमेज लोड करें + +अब हम वास्तव में **OCR के लिए इमेज लोड** करते हैं। `OcrImage.FromFile` मेथड बिटमैप को ऐसे फॉर्मेट में पढ़ता है जिसे इंजन समझता है। + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **सामान्य गलती:** +> विंडोज़ पर फॉरवर्ड स्लैश वाले पाथ का उपयोग काम करता है, लेकिन `Path.Combine` उपयोग करने से आपका कोड प्लेटफ़ॉर्म‑अज्ञेय बन जाता है। + +### चरण 6: पहचान चलाएँ + +सब कुछ सेट होने के बाद, हम अंत में `Recognize` कॉल करके **इमेज पर OCR करें**। + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **क्या हो रहा है?** +> इंजन प्रत्येक पिक्सेल को स्कैन करता है, पैटर्न को हिंदी ग्लिफ़ डेटाबेस से मिलाता है, और यूनिकोड कैरेक्टर्स की स्ट्रिंग बनाता है। + +### चरण 7: पहचाने गए टेक्स्ट को आउटपुट करें + +परिणाम ऑब्जेक्ट में `Text` प्रॉपर्टी होती है जो निकाली गई स्ट्रिंग रखती है। हम इसे सरलता से कंसोल में लिखते हैं। + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **अपेक्षित आउटपुट:** +> यदि `receipt_hindi.png` में “भुगतान सफल” है, तो कंसोल ठीक वही लाइन प्रिंट करेगा, डायाक्रिटिक को संरक्षित रखते हुए। + +## OCR के लिए इमेज लोड करें – संसाधन तैयार करना + +यदि आप सोच रहे हैं कि क्या आप इंजन को फ़ाइल की बजाय स्ट्रीम दे सकते हैं, तो उत्तर हाँ है। `OcrImage.FromFile` को इस प्रकार बदलें: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **स्ट्रीम क्यों उपयोग करें?** +> स्ट्रीम आपको डेटाबेस, क्लाउड ब्लॉब्स, या एम्बेडेड रिसोर्सेज़ में संग्रहीत इमेज के साथ काम करने देती है—स्केलेबल सर्विसेज़ के लिए उत्तम। + +## हिंदी टेक्स्ट इमेज निकालें – किनारे के मामलों को संभालना + +1. **भाषा पैक अनुपलब्ध** – यदि हिंदी पैक नहीं मिला, तो `Recognize` एक अपवाद (exception) फेंकेगा। कॉल को try/catch में रखें और एक मित्रवत संदेश लॉग करें। +2. **कम‑रिज़ॉल्यूशन इमेज** – OCR की सटीकता 300 dpi से नीचे गिर जाती है। लोड करने से पहले इमेज को प्री‑प्रोसेस करें (रिसाइज़, शार्पन)। +3. **मिश्रित‑भाषा दस्तावेज़** – आप कई भाषाएँ सक्षम कर सकते हैं: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +ये समायोजन सुनिश्चित करते हैं कि आपका **इमेज पर OCR करें** रूटीन उत्पादन में मजबूत बना रहे। + +## पूरा उदाहरण चलाना + +निम्नलिखित फ़ाइल को `Program.cs` के रूप में सहेजें, प्लेसहोल्डर पाथ बदलें, और चलाएँ: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +जब आप `dotnet run` चलाएँगे, तो आपको कुछ इस तरह दिखना चाहिए: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +यदि आपको खाली स्ट्रिंग मिलती है, तो दोबारा जांचें कि **ResourcesFolder** `Hindi.traineddata` वाले फ़ोल्डर की ओर इशारा कर रहा है और इमेज पर्याप्त स्पष्ट है। + +## निष्कर्ष + +हमने Aspose OCR के साथ **इमेज पर OCR करना** फ़ाइलों को कैसे किया जाए, इस पर चरण‑दर‑चरण बताया, जिसमें **OCR के लिए इमेज लोड** से लेकर **हिंदी टेक्स्ट इमेज निकालना** तक सब कुछ शामिल है, और यह पूरी तरह ऑफ़लाइन परिदृश्य में है। ऊपर दिया गया पूर्ण, चलाने योग्य कोड आपको एक ठोस आधार देता है, और स्ट्रीम, त्रुटि संभालना, तथा बहु‑भाषा समर्थन पर टिप्स आपको समाधान को वास्तविक प्रोजेक्ट्स में अनुकूलित करने में मदद करेंगे। + +अगले चरण के लिए तैयार हैं? भाषा को **OcrLanguage.Tamil** में बदलने या Azure Blob स्टोरेज से इमेज फीड करने की कोशिश करें। आप `ImagePreprocessing` सेटिंग्स के साथ प्रयोग करके शोरयुक्त रसीदों पर सटीकता बढ़ा सकते हैं। + +कोई प्रश्न हैं या समस्या आई? टिप्पणी छोड़ें—हैप्पी कोडिंग! + +![Perform OCR on image example + +## आपको अगला क्या सीखना चाहिए? + +निम्नलिखित ट्यूटोरियल्स उन संबंधित विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जो आपको अतिरिक्त API फीचर्स में महारत हासिल करने और अपने प्रोजेक्ट्स में वैकल्पिक कार्यान्वयन दृष्टिकोणों का अन्वेषण करने में मदद करेंगे। + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ इमेज टेक्स्ट निकालें C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [एकाधिक भाषाओं के लिए Aspose OCR के साथ इमेज टेक्स्ट पहचानें](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [इमेज से टेक्स्ट निकालें – 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/hindi/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/hindi/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..ff92ca37c --- /dev/null +++ b/ocr/hindi/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR का उपयोग करके PDF पर OCR करें और स्कैन किए गए PDF को सर्चेबल + PDF में बदलें। जानें कि PDF से टेक्स्ट कैसे पहचानें और मिनटों में सर्चेबल PDF बनाएं। +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: hi +og_description: PDF पर OCR करें और तुरंत एक खोज योग्य PDF बनाएं। यह ट्यूटोरियल चरण‑दर‑चरण + दिखाता है कि Aspose.OCR का उपयोग करके PDF से टेक्स्ट कैसे पहचाना जाए। +og_title: PDF पर OCR करें – पूर्ण C# गाइड +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Aspose.OCR के साथ PDF पर OCR करें – पूर्ण C# गाइड +url: /hi/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Perform OCR on PDF with Aspose.OCR – Complete C# Guide + +क्या आपने कभी **PDF पर OCR करने** के बारे में सोचा है बिना दर्जनों कमांड‑लाइन टूल्स के साथ झंझट किए? आप अकेले नहीं हैं। चाहे आप इनवॉइस को डिजिटल बना रहे हों, पुराने रिपोर्ट्स को आर्काइव कर रहे हों, या सिर्फ़ स्कैन किए गए कॉन्ट्रैक्ट का सर्चेबल संस्करण चाहिए, स्थिर PDF को सर्चेबल बनाना एक गेम‑चेंजर है। + +इस गाइड में हम **स्कैन किए गए PDF (और यहाँ तक कि साधारण इमेज)** से Aspose.OCR for .NET का उपयोग करके सर्चेबल PDF फ़ाइलें बनाने की प्रक्रिया को चरण‑दर‑चरण देखेंगे। अंत तक आप कुछ ही C# लाइनों से **PDF से टेक्स्ट पहचान** सकेंगे, और प्रत्येक कदम के पीछे का कारण समझेंगे ताकि आप इसे अपने प्रोजेक्ट्स में अनुकूलित कर सकें। + +> **Quick takeaway:** पूरी प्रक्रिया तीन चीज़ों में संक्षिप्त है—OCR इंजन को इनिशियलाइज़ करना, स्रोत (PDF या इमेज) को फीड करना, और सर्चेबल PDF आउटपुट को सेव करना। चलिए शुरू करते हैं। + +--- + +## What You’ll Need + +शुरू करने से पहले सुनिश्चित करें कि आपके पास ये हैं: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.OCR आधुनिक रनटाइम्स को टारगेट करता है; पुराने संस्करणों में API अपडेट नहीं हो सकते। | +| **Aspose.OCR for .NET** NuGet package | `OcrEngine` क्लास और PDF हैंडलिंग यूटिलिटीज़ प्रदान करता है। | +| **A valid Aspose license** (or use the free evaluation) | लाइसेंस के बिना आप 30‑दिन की इवैल्यूएशन लिमिट और वाटरमार्क का सामना करेंगे। | +| **A scanned PDF** (or an image file) you want to make searchable | यह OCR के लिए स्रोत दस्तावेज़ है। | +| **Visual Studio 2022** (or any C# editor) | डिबगिंग आसान बनाता है, लेकिन कोई भी IDE चलेगा। | + +आप लाइब्रेरी को निम्न NuGet कमांड से इंस्टॉल कर सकते हैं: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** यदि आप CI पाइपलाइन पर काम कर रहे हैं, तो लाइसेंस फ़ाइल को बिल्ड आर्टिफैक्ट्स में जोड़ें और रनटाइम पर लोड करें ताकि पाथ हार्ड‑कोडिंग से बचा जा सके। + +--- + +## Perform OCR on PDF – Setting Up Aspose.OCR + +सबसे पहले हमें एक नया `OcrEngine` इंस्टेंस चाहिए। इसे उस दिमाग़ की तरह समझें जो आपका दस्तावेज़ पढ़ेगा। + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +हर बार नया इंस्टेंस क्यों? इंजन में कॉन्फ़िगरेशन (जैसे भाषा सेटिंग्स) रहती है जो दस्तावेज़‑दर‑दस्तावेज़ अलग हो सकती है। प्रत्येक रन पर नया बनाना क्लीन स्लेट सुनिश्चित करता है और जॉब्स के बीच क्रॉस‑टॉक से बचाता है। + +--- + +## How to Create Searchable PDF – Configuring Passwords (Optional) + +यदि आपका PDF प्रोटेक्टेड है, तो इंजन को पासवर्ड बताना होगा इससे पहले कि वह पेज पढ़ सके: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +प्रोटेक्टेड फ़ाइल पर इस स्टेप को स्किप करने से `PdfPasswordException` आएगा। यदि आप प्रोटेक्शन स्टेटस के बारे में अनिश्चित हैं तो हमेशा इसे try‑catch में रैप करें। + +--- + +## Convert Scanned PDF to Searchable PDF – Loading the Source + +Aspose.OCR `OcrImage` एब्स्ट्रैक्शन के साथ काम करता है, जो PDFs, TIFFs, JPEGs आदि को रैप कर सकता है। यहाँ बताया गया है कि स्कैन किए गए PDF को मेमोरी में कैसे लोड करें: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +पर्दे के पीछे, `FromFile` प्रत्येक पेज को रास्टर इमेज में पार्स करता है जिसे OCR इंजन प्रोसेस कर सकता है। यदि आपके पास मल्टी‑पेज PDF है, तो इंजन स्वचालित रूप से हर पेज पर इटररेट करेगा। + +--- + +## Recognize Text from PDF – Performing the OCR + +अब ट्यूटोरियल का मुख्य भाग: इंजन को टेक्स्ट पहचानने और सर्चेबल PDF आउटपुट देने को कहें। + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` इंजन को मूल स्कैन की इमेज के ऊपर एक इनविज़िबल टेक्स्ट लेयर एम्बेड करने को बताता है। परिणामस्वरूप PDF स्कैन की विज़ुअल फ़िडेलिटी को बरकरार रखता है जबकि पूरी तरह सर्चेबल बन जाता है—जो compliance audits के लिए बिल्कुल सही है। + +--- + +## Convert Image to Searchable PDF – Saving the Result + +अंत में बाइनरी डेटा को डिस्क पर लिखें: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary` प्रॉपर्टी में कच्चे PDF बाइट्स होते हैं। आप इन्हें सीधे वेब रिस्पॉन्स में स्ट्रीम भी कर सकते हैं यदि आप API बना रहे हों। + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") +*Image alt text: Perform OCR on PDF flow diagram illustrating how a scanned PDF is turned into a searchable PDF.* + +--- + +## Edge Cases & Practical Tips + +### 1. Large Files & Memory Management +यदि आप 100 MB से बड़े PDFs प्रोसेस कर रहे हैं, तो `OcrEngineSettings.MemoryLimit` का उपयोग करके मेमोरी उपयोग को सीमित करें। अतिरिक्त रूप से, `OutOfMemoryException` से बचने के लिए पेजेज़ को बैच में प्रोसेस करें। + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Language Support +डिफ़ॉल्ट रूप से Aspose.OCR अंग्रेज़ी मानता है। अन्य भाषाओं को पहचानने के लिए `Language` प्रॉपर्टी सेट करें: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Multi‑Threaded Scenarios +`OcrEngine` **थ्रेड‑सेफ़** नहीं है। यदि आपको पैरलल प्रोसेसिंग चाहिए, तो प्रत्येक थ्रेड के लिए अलग इंजन बनाएं। + +### 4. Debugging OCR Accuracy +डिबगिंग के लिए आप `ocrResult` से प्लेन टेक्स्ट निकाल सकते हैं: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +यदि आउटपुट गड़बड़ दिखे, तो `PreprocessSettings` (जैसे deskew, despeckle) के साथ प्रयोग करें ताकि क्वालिटी सुधरे। + +### 5. Licensing Gotchas +जब आप इवैल्यूएशन वर्ज़न चलाते हैं, तो Aspose आउटपुट PDF में वाटरमार्क जोड़ता है। लाइसेंस को एप्लिकेशन की शुरुआत में रजिस्टर करें: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Full Working Example – From Start to Finish + +नीचे पूरा, रन‑टू‑रन प्रोग्राम दिया गया है जिसमें ऊपर बताए सभी टिप्स शामिल हैं। इसे एक नए कंसोल प्रोजेक्ट में कॉपी‑पेस्ट कर सकते हैं। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Expected output:** रन करने के बाद, आपको कंसोल में फ़ाइल लोकेशन की पुष्टि दिखेगी। `output.pdf` को किसी भी PDF व्यूअर में खोलें; मूल स्कैन में मौजूद कोई शब्द टाइप करके देखें। यदि टेक्स्ट हाईलाइट होता है, तो आपने सफलतापूर्वक **PDF पर OCR किया** और सर्चेबल डॉक्यूमेंट बना लिया है। + +--- + +## Frequently Asked Questions + +**Q: क्या मैं इसे एक सिंगल इमेज (PNG/JPEG) को सर्चेबल PDF में बदलने के लिए उपयोग कर सकता हूँ?** +A: बिल्कुल। `OcrImage.FromFile("input.pdf")` को अपनी इमेज फ़ाइल के पाथ से बदल दें। इंजन इमेज को रास्टराइज़ करेगा और OCR लेयर को उसी तरह एम्बेड करेगा। + +**Q: यदि मेरे PDF में स्कैन किए हुए पेजेज़ और नेटिव टेक्स्ट दोनों हैं तो क्या होगा?** +A: इंजन मौजूदा कंटेंट के ऊपर OCR टेक्स्ट ओवरले करेगा, इसलिए नेटिव टेक्स्ट सेलेक्टेबल रहेगा और स्कैन किए हुए पेजेज़ सर्चेबल बन जाएंगे। + +**Q: OCR की सटीकता कितनी है?** +A: सटीकता स्रोत की क्वालिटी पर निर्भर करती है। साफ़, हाई‑रेज़ोल्यूशन स्कैन (>300 dpi) >95 % सटीकता दे सकते हैं। शोरयुक्त दस्तावेज़ों के लिए `PreprocessSettings` (deskew, despeckle) को सक्षम करके बेहतर परिणाम मिल सकते हैं। + +--- + +## Next Steps – Extending Your OCR Toolkit + +अब जब आप **PDF से टेक्स्ट पहचान** और **स्कैन किए हुए PDF को सर्चेबल PDF में बदलना** कर सकते हैं, तो इन फॉलो‑अप टॉपिक्स पर विचार करें: + +- **Batch processing**: फ़ोल्डर में मौजूद कई PDFs को लूप करके स्वचालित रूप से सर्चेबल वर्ज़न जेनरेट करें। +- **Text extraction**: `ocrResult.Text` का उपयोग करके सर्च इंडेक्स (जैसे Elasticsearch) में फ़ीड करें। +- **Custom language packs**: Aspose से अतिरिक्त भाषा डेटा डाउनलोड करके एशियन स्क्रिप्ट्स को सपोर्ट करें। +- **PDF/A compliance**: OCR आउटपुट को Aspose.PDF के साथ मिलाकर आर्काइव‑रेडी PDFs बनाएं। + +इनमें से प्रत्येक कोर स्टेप्स पर आधारित है, इसलिए आप अपने समाधान को आसानी से विस्तारित कर सकते हैं। + +--- + +## Wrap‑Up + +हमने आपको **PDF पर OCR करने** का तरीका Aspose.OCR के साथ दिखाया, स्कैन किए हुए PDFs को पूरी तरह सर्चेबल PDFs में बदला, और साधारण इमेज को भी सर्चेबल PDFs में बदलने का तरीका बताया। नीचे दिया गया कोड + +## What Should You Learn Next? + +नीचे दिए गए ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक रिसोर्स में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/hindi/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..cf1536405 --- /dev/null +++ b/ocr/hindi/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: वीडियो सबटाइटल OCR ट्यूटोरियल जो दिखाता है कि वीडियो से फ्रेम कैसे निकालें + और Aspose.OCR का उपयोग करके MP4 जैसे वीडियो फ़ाइलों से टेक्स्ट कैसे पढ़ें। +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: hi +og_description: Aspose.OCR के साथ वीडियो सबटाइटल OCR सीखें। वीडियो से फ्रेम निकालें, + वीडियो से टेक्स्ट पढ़ें, और कुछ ही मिनटों में MP4 से टेक्स्ट निकालें। +og_title: C# में वीडियो सबटाइटल OCR – चरण‑दर‑चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: C# में वीडियो सबटाइटल OCR – पूर्ण मार्गदर्शिका +url: /hi/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# वीडियो सबटाइटल OCR इन C# – पूर्ण गाइड + +क्या आपको **video subtitle ocr** की ज़रूरत थी लेकिन नहीं पता था कहाँ से शुरू करें? आप अकेले नहीं हैं। चाहे आप लेक्चर रिकॉर्डिंग को डिजिटल बना रहे हों, ट्रेनिंग वीडियो से कैप्शन निकाल रहे हों, या सिर्फ वीडियो से टेक्स्ट पढ़ने में जिज्ञासु हों, यह ट्यूटोरियल आपको C# और Aspose.OCR के साथ ठीक‑ठीक कैसे करना है दिखाता है। + +अगले कुछ मिनटों में हम वीडियो से फ्रेम निकालेंगे, उन फ्रेम्स पर OCR चलाएंगे, और अंत में सबटाइटल टेक्स्ट को फ्रेम‑बाय‑फ़्रेम दिखाएंगे। अंत तक आप **read text from video** फ़ाइलें—MP4 सहित—को थर्ड‑पार्टी टूल्स की तलाश किए बिना पढ़ पाएँगे। + +## What You’ll Build + +हम एक छोटा कंसोल ऐप बनाएँगे जो: + +1. MP4 (या किसी भी सपोर्टेड फ़ॉर्मेट) को व्यक्तिगत `Bitmap` फ्रेम्स में डिकोड करता है। +2. OCR क्षेत्र को सबटाइटल बैंड तक सीमित करता है ताकि इंजन पूरी तस्वीर से विचलित न हो। +3. प्रत्येक फ्रेम को Aspose के `VideoOcrProcessor` के साथ प्रोसेस करता है। +4. पहचाने गए सबटाइटल टेक्स्ट को कंसोल पर प्रिंट करता है। + +कोई फालतू नहीं, सिर्फ एक कार्यशील एंड‑टू‑एंड उदाहरण जिसे आप वास्तविक प्रोजेक्ट में डाल सकते हैं। + +## Prerequisites + +- **.NET 6.0** या बाद का (कोड .NET Framework 4.7+ पर भी काम करता है)। +- **Aspose.OCR for .NET** – NuGet से इंस्टॉल करें: `Install-Package Aspose.OCR`। +- एक वीडियो फ़ाइल (MP4 बहुत अच्छा काम करता है)। +- वीडियो फ्रेम्स को डिकोड करने का तरीका – डेमो एक प्लेसहोल्डर मेथड इस्तेमाल करता है, लेकिन आप FFmpeg, OpenCV, या कोई भी लाइब्रेरी जो `Bitmap` ऑब्जेक्ट्स रिटर्न करे, प्लग इन कर सकते हैं। + +> Pro tip: यदि आप Windows पर हैं, तो `System.Drawing.Common` पैकेज `Bitmap` के लिए ठीक काम करता है। Linux/macOS पर आपको नेेटिव `libgdiplus` डिपेंडेंसी की ज़रूरत पड़ेगी। + +## Step 1 – Extract Frames from Video + +पहला बाधा है मूविंग पिक्चर को स्थिर इमेजेज़ में बदलना। नीचे दिया गया मेथड `GetVideoFrames` जानबूझकर खाली छोड़ा गया है; इसे अपने पसंदीदा डिकोडर से बदलें। यहाँ FFmpeg‑Core का एक त्वरित स्केच दिया गया है (सिर्फ डेटा की संरचना दिखाने के लिए): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Why this matters:** फ्रेम निकालने से OCR इंजन को एक स्थिर इमेज मिलती है, जिससे वीडियो स्ट्रीम से सीधे पढ़ने की तुलना में सटीकता में काफी सुधार होता है। + +## Step 2 – Set Up the VideoOcrProcessor + +अब जब हमारे पास `Bitmap` ऑब्जेक्ट्स की एक श्रृंखला है, हम उन्हें Aspose.OCR को दे सकते हैं। `VideoOcrProcessor` हमें **Region of Interest (ROI)** निर्धारित करने की सुविधा देता है – सबटाइटल्स के लिए जो आमतौर पर फ्रेम के ऊपर या नीचे होते हैं, यह बिल्कुल उपयुक्त है। + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Why limit the ROI?** चित्र के बाकी हिस्से को नजरअंदाज करके हम शोर कम करते हैं, प्रोसेसिंग टाइम घटाते हैं, और बैकग्राउंड ग्राफिक्स से फॉल्स पॉज़िटिव्स से बचते हैं। + +## Step 3 – Run OCR on the Frame Sequence + +प्रोसेसर तैयार होने के बाद, फ्रेम्स को फीड करना एक‑लाइनर है। `Process` मेथड `OcrResult` ऑब्जेक्ट्स की एक enumerable रिटर्न करता है, जिसमें प्रत्येक फ्रेम के लिए पहचाना गया टेक्स्ट होता है। + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **What’s happening under the hood?** Aspose.OCR आंतरिक रूप से प्रत्येक bitmap को नॉर्मलाइज़ करता है, न्यूरल‑नेटवर्क‑आधारित रेकग्नाइज़र चलाता है, और फिर आउटपुट को बेहतर पंक्चुएशन और लाइन ब्रेक्स के लिए पोस्ट‑प्रोसेस करता है। + +## Step 4 – Display the Extracted Text + +अंत में, हम परिणामों पर इटररेट करते हैं और प्रत्येक सबटाइटल लाइन को प्रिंट करते हैं। आप इन्हें SRT फ़ाइल, डेटाबेस, या किसी ट्रांसलेशन सर्विस में भी लिख सकते हैं। + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Full Working Example + +सब कुछ एक साथ मिलाकर एक स्व-निहित कंसोल प्रोग्राम बनता है: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Expected output (sample)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +यदि OCR किसी विशेष फ्रेम के साथ संघर्ष करता है, तो आपको एक खाली स्ट्रिंग दिखेगी – यह ROI को समायोजित करने या फ्रेम एक्सट्रैक्शन रेट बढ़ाने का संकेत है। + +## Common Pitfalls & How to Fix Them + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Garbage characters** | Low‑resolution frames or heavy compression | Extract frames at a higher bitrate, or upscale the bitmap before OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI doesn’t actually cover the subtitle band | Verify the rectangle coordinates (use a screenshot tool to measure). | +| **Performance bottleneck** | Processing every frame at 30 fps is overkill | Down‑sample to 1‑2 fps for most subtitle streams; you can still capture every subtitle change. | +| **FFmpeg not found** | `ffmpeg.exe` isn’t on the `PATH` | Provide the full path in `ProcessStartInfo.FileName` or install FFmpeg globally. | + +## Extending the Solution + +- **Export to SRT** – timestamps को OCR टेक्स्ट के साथ जोड़ें और SubRip फ़ाइल लिखें। +- **Multi‑language support** – `ocrProcessor.Language = OcrLanguage.Spanish` (या कोई भी सपोर्टेड भाषा) सेट करें। +- **Real‑time processing** – फ्रेम्स को सीधे लाइव स्ट्रीम से पाइप करें, डिस्क से पढ़ने की बजाय। + +इन सभी वैरिएशन्स का मूल विचार वही रहता है: **extract frames from video**, **read text from video**, और **extract text from mp4**। + +## Conclusion + +हमने अभी C# में एक पूर्ण **video subtitle ocr** वर्कफ़्लो को चरण‑दर‑चरण देखा। फ्रेम्स को वीडियो से निकालकर, OCR को सबटाइटल बैंड पर फोकस करके, और परिणामों को इटररेट करके, आप MP4 जैसी फ़ाइलों से भरोसेमंद रूप से **read text from video** कर सकते हैं। कोड कॉपी‑पेस्ट के लिए तैयार है, और मॉड्यूलर डिज़ाइन आपको किसी भी फ्रेम‑डिकोडर को आसानी से बदलने देता है। + +अगले कदम? परिणामों को SRT फ़ाइल में एक्सपोर्ट करें, विभिन्न ROI आकारों के साथ प्रयोग करें, या मल्टी‑लैंग्वेज़ कैप्शन के लिए सबटाइटल्स को ट्रांसलेशन API में फीड करें। टेक्स्ट को वीडियो से निकालने की बुनियादें समझने के बाद संभावनाएँ अनंत हैं। + +कोडिंग का आनंद लें, और आपके सबटाइटल हमेशा क्रिस्टल‑क्लियर रहें! + +## What Should You Learn Next? + +निम्नलिखित ट्यूटोरियल्स उन विषयों को कवर करते हैं जो इस गाइड में दिखाए गए तकनीकों पर आधारित हैं। प्रत्येक संसाधन में पूर्ण कार्यशील कोड उदाहरण और चरण‑दर‑चरण व्याख्याएँ शामिल हैं, जिससे आप अतिरिक्त API फीचर्स में महारत हासिल कर सकें और अपने प्रोजेक्ट्स में वैकल्पिक इम्प्लीमेंटेशन अप्रोचेज़ को एक्सप्लोर कर सकें। + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/ocr-configuration/_index.md b/ocr/hongkong/net/ocr-configuration/_index.md index 0fd2ef8d0..5d8f4b95b 100644 --- a/ocr/hongkong/net/ocr-configuration/_index.md +++ b/ocr/hongkong/net/ocr-configuration/_index.md @@ -60,6 +60,8 @@ Extracting OCR 意味著將影像(或影像集合)傳遞給 Aspose.OCR,該 使用 Aspose.OCR for .NET 釋放強大的 OCR 功能。將文字無縫地從圖像中提取。 ### [OCR 影像辨識中對清單檔案的 OCR 操作](./ocr-operation-with-list/) 釋放 Aspose.OCR for .NET 的潛能。輕鬆實現清單的 OCR 影像辨識。提升應用程式的效率和資料提取速度。 +### [在 C# 中取得 Aspose OCR 版本 – 完整指南](./get-aspose-ocr-version-in-c-complete-guide/) +了解如何在 C# 程式中檢索 Aspose OCR 函式庫的版本資訊,並確保相容性與升級。 ### 常見用例 - **Extract text images** 從掃描發票中擷取文字,以實現自動化會計。 @@ -93,4 +95,4 @@ Extracting OCR 意味著將影像(或影像集合)傳遞給 Aspose.OCR,該 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/hongkong/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..97255e843 --- /dev/null +++ b/ocr/hongkong/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: 使用簡單程式碼片段在 C# 中取得 Aspose OCR 版本。了解如何透過 OcrEngine GetVersion 取得 Aspose + OCR 函式庫版本。 +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: zh-hant +og_description: 快速在 C# 中取得 Aspose OCR 版本。本教學精確示範如何使用 OcrEngine.GetVersion 取得 Aspose + OCR 函式庫的版本。 +og_title: 取得 Aspose OCR 版本於 C# – 完整指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: 取得 Aspose OCR 版本於 C# – 完整指南 +url: /zh-hant/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 取得 Aspose OCR 版本(C#) – 完整指南 + +有沒有想過如何在 .NET 專案中 **取得 Aspose OCR 版本**?也許你在排除版本不符的問題,或只是想記錄在生產環境中執行的確切函式庫版本。無論原因為何,你已經來到正確的地方。 + +在本教學中,我們將逐步說明一個簡單、獨立的 C# 程式,呼叫 `OcrEngine.GetVersion()` 並印出結果。完成後,你不僅會知道 *如何* 取得版本,還會了解 *為何* 在升級 **Aspose OCR library** 時檢查版本能避免許多麻煩。 + +## 你將學會 + +- 將 Aspose.OCR NuGet 套件加入 C# 專案 +- 使用 `OcrEngine.GetVersion()` 方法(**ocrengine getversion** 入口點) +- 處理可能的例外並驗證輸出 +- 擴充程式碼以應對實務情境,例如記錄或條件功能切換 + +不需要任何 OCR 先前經驗——只要具備基本的 C# 與 Visual Studio(或你喜愛的 IDE)知識即可。讓我們開始吧。 + +--- + +## 步驟 1:設定專案並取得 Aspose OCR 函式庫 + +在呼叫任何 OCR 相關 API 之前,你必須在專案中參考 **Aspose OCR library**。 + +1. 在 Visual Studio 中開啟終端機或套件管理員主控台。 +2. 執行以下指令以安裝最新的穩定版: + +```bash +dotnet add package Aspose.OCR +``` + +> **專業提示:** 若你的目標是 .NET Framework 而非 .NET Core,請使用 NuGet 套件管理員 UI,並選取與執行環境相符的版本。此套件包含我們稍後會使用的 `OcrEngine` 類別。 + +### 為何這很重要 + +安裝套件後,磁碟上的組件版本可能與執行時函式庫回報的版本不同。透過程式碼查詢版本可確保讀取到 CLR 載入的確切組建,這對除錯與合規稽核皆相當關鍵。 + +--- + +## 步驟 2:撰寫最小程式碼以 **取得 Aspose OCR 版本** + +建立一個新的主控台應用程式(`dotnet new console -n OcrVersionDemo`),並將預設的 `Program.cs` 替換為下列程式碼: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**各部分說明** + +- `using Aspose.OCR;` 會將 OCR 命名空間匯入,使我們能呼叫 `OcrEngine`。 +- `OcrEngine.GetVersion()` 是 **ocrengine getversion** 的靜態方法,會回傳類似 `"24.5.7"` 的字串。 +- 將呼叫包在 `try/catch` 區塊中,可防止執行時的意外情況——例如目標機器找不到原生二進位檔案。 +- 插值字串 `$"Aspose OCR version: {version}"` 會印出清晰、易讀的訊息。 + +### 預期輸出 + +在專案資料夾內執行 `dotnet run` 後,你應該會看到類似以下的輸出: + +``` +Aspose OCR version: 24.5.7 +``` + +若無法載入函式庫,錯誤分支會輸出簡潔的訊息,協助你快速定位問題。 + +--- + +## 步驟 3:驗證版本是否與 NuGet 套件相符 + +很容易認為已安裝的 NuGet 版本就是執行時使用的版本,但環境差異可能會介入。為了再次確認: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +執行此額外程式碼會印出類似以下的結果: + +``` +Assembly file version: 24.5.7.0 +``` + +若兩個值不相同,可能是從全域組件快取 (GAC) 或先前的建置資料夾載入了較舊的 DLL。此時,請執行 `dotnet clean` 清理方案,然後重新建置。 + +--- + +## 步驟 4:將版本檢查寫入正式環境日誌 + +大多數實務應用程式不只會印到主控台,還會寫入日誌檔或遙測系統。以下是一個使用 `Microsoft.Extensions.Logging` 的簡易範例: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +現在版本會出現在結構化日誌中,之後可輕鬆依 `{Version}` 進行過濾。當你有多個微服務,各自載入可能不同的 OCR DLL 時,這個模式特別實用。 + +--- + +## 常見問題與邊緣情況 + +### 如果 `GetVersion()` 回傳空字串會怎樣? + +通常表示安裝損毀或缺少原生相依性。請重新安裝 NuGet 套件,並確認 `Aspose.OCR.Native.dll`(或相對應平台的二進位檔)與可執行檔位於同一目錄。 + +### 此方法在 .NET Core 2.0 上能運作嗎? + +可以,**Aspose OCR** 支援 .NET Standard 2.0 及以上版本,因此任何實作該標準的 .NET Core 版本皆可呼叫 `OcrEngine.GetVersion()`。若發佈自包含應用程式,請確保參考正確的執行時識別碼(`win‑x64`、`linux‑x64` 等)。 + +### 可以在沒有授權檔的情況下取得版本嗎? + +絕對可以。`GetVersion()` **不需要** 授權檔,只會回報函式庫的建置編號。然而,若在未持有有效授權的情況下執行 OCR,會拋出執行時例外。因此,我們程式碼中的 `try/catch` 很有價值——它將版本檢查與 OCR 執行流程分離。 + +--- + +## 完整可執行範例(直接複製貼上) + +以下是完整程式碼,可直接放入新的主控台專案。它包含可選的日誌區塊,讓你同時看到主控台輸出與結構化日誌。 + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +使用 `dotnet run` 執行,它會顯示兩行確認版本的訊息,若啟用 `LogLevel.Debug`,還會多一行除錯訊息。 + +--- + +## 結論 + +我們已說明在 C# 環境中 **取得 Aspose OCR 版本** 所需的全部步驟——從安裝 **Aspose OCR library**、呼叫 **ocrengine getversion** 方法、處理例外,到將結果寫入正式等級的日誌。掌握這些知識後,你即可可靠地驗證應用程式使用的 OCR 建置版本,避免因版本問題造成的錯誤,並在不費吹灰之力的情況下滿足合規需求。 + +下一步?試著將此版本檢查與實際的 OCR 呼叫(`OcrEngine` → `RecognizeImage`)結合,並同時記錄版本與辨識結果。你也可以探索其他 Aspose 產品(PDF、Slides、Cells)的 **retrieve aspose version** 模式,讓整個套件保持同步。 + +祝開發順利,願你的 OCR 流程保持銳利! + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立在本篇示範的技巧之上。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [如何使用 Aspose.OCR for .NET 取得 OCR 結果](/ocr/english/net/text-recognition/get-recognition-result/) +- [使用 Aspose.OCR 以語言選擇擷取影像文字(C#)](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [如何在 Aspose.OCR for .NET 中使用 List 批次 OCR 影像](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/hongkong/net/ocr-optimization/_index.md index c078585c2..9afbabb46 100644 --- a/ocr/hongkong/net/ocr-optimization/_index.md +++ b/ocr/hongkong/net/ocr-optimization/_index.md @@ -72,6 +72,8 @@ weight: 25 使用 Aspose.OCR for .NET 增強 OCR 精度,校正拼寫、客製化字典,輕鬆實現無誤的文字辨識。 ### [在 OCR 圖像辨識中將多頁結果儲存為文件](./save-multipage-result-as-document/) 解鎖 Aspose.OCR for .NET 的潛能,透過本完整步驟教學,輕鬆將多頁 OCR 結果儲存為文件。 +### [Aspose OCR C# 範例 – 啟用 GPU、設定記憶體限制與處理 TIF 圖像](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +示範如何在 C# 中啟用 GPU 加速、設定記憶體上限,並處理 TIF 圖像以提升 OCR 效能。 ## 常見問題 diff --git a/ocr/hongkong/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/hongkong/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..c54873970 --- /dev/null +++ b/ocr/hongkong/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# 示例,展示如何設定 GPU 記憶體限制、載入影像進行 OCR,並從 TIF 檔案辨識文字,附完整程式碼與技巧。 +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: zh-hant +og_description: 學習完整的 Aspose OCR C# 範例:啟用 GPU、設定 GPU 記憶體上限、載入影像進行 OCR,並從 TIF 檔案辨識文字。完整程式碼已提供。 +og_title: Aspose OCR C# 範例 – GPU 加速、記憶體限制與 TIF 處理 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# 示例 – 啟用 GPU、設定記憶體上限與處理 TIF 圖像 +url: /zh-hant/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# 範例 – 啟用 GPU、設定記憶體上限與處理 TIF 圖像 + +有沒有想過在處理巨量 TIFF 掃描檔時,如何從 **Aspose OCR C# example** 程式碼中擠出最高效能?你並不孤單。在許多實務專案——例如數位化檔案或從高解析度收據中擷取資料——瓶頸往往不是 OCR 演算法本身,而是硬體使用率。 + +事實上:Aspose OCR 支援 GPU 加速,但你必須明確告訴它可使用多少記憶體、載入正確的影像類型,最後再從 .tif 檔中取出辨識文字。本教學會一步步帶你完成,從安裝 SDK 到微調 GPU 設定,讓你在不耗盡 GPU 記憶體的前提下,以極速執行 OCR。 + +我們也會加入幾個「如果…」情境,例如處理多頁 TIFF 或在沒有 GPU 時回退至 CPU,讓你得到的是完整且穩健的解決方案,而非一次性的程式碼片段。 + +## 需要的前置條件 + +在開始之前,請確保你的機器具備以下項目: + +| 前置條件 | 為什麼重要 | +|--------------|----------------| +| **.NET 6 SDK**(或更新版本) | Aspose OCR 目標為 .NET Standard 2.0+,任何較新的 .NET 版本皆可相容。 | +| **Aspose.OCR NuGet 套件** (`Install-Package Aspose.OCR`) | 提供 `OcrEngine`、`GpuSettings` 等核心類別的程式庫。 | +| **CUDA 11+**(NVIDIA)**或 ROCm 5+**(AMD) | GPU 加速的必要條件;SDK 會在執行時檢查相容的驅動程式。 | +| 具備 **至少 2 GB VRAM** 的 **GPU**(本教學以 2048 MB 為上限) | 記憶體不足時,引擎會自動靜默回退至 CPU。 | +| 想要處理的 **高解析度 TIFF** 影像 | Aspose OCR 幾乎支援所有點陣圖格式,TIF 是掃描檔的常見格式。 | +| Visual Studio 2022(或任意你喜歡的編輯器) | 用於建置與除錯 C# 專案。 | + +若缺少上述任一項目,程式仍能編譯,但將無法體驗我們所追求的效能提升。 + +## 步驟 1:建立 Aspose OCR C# Example Engine + +每個 **Aspose OCR C# example** 的第一步都是實例化 OCR 引擎。把 `OcrEngine` 想成電影導演——它負責協調從影像載入到文字抽取的所有工作。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **小技巧:** 若要連續處理多張影像,請保持同一個 `OcrEngine` 實例存活。每張影像重新建立引擎會產生額外開銷,往往會超過 OCR 本身的執行時間。 + +## 步驟 2:設定 GPU 記憶體上限(並啟用加速) + +接下來是常讓人卡住的部份:**設定 GPU 記憶體上限**。預設情況下 Aspose OCR 會盡可能使用所有可用的 VRAM,這在共用工作站上可能會導致其他程式資源不足。`GpuSettings` 物件讓你可以限制分配量。 + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### 為什麼要設定記憶體上限? + +- **穩定性:** 防止在處理超大型影像時因記憶體不足而當機。 +- **共存性:** 讓其他需要大量 GPU 的應用程式(例如 TensorFlow 模型)能同時執行。 +- **可預測性:** 測試時表現更一致,因為 GPU 不會因為突發的記憶體交換而變慢。 + +如果省略 `MemoryLimitMb`,Aspose 會自行分配所需的記憶體,這在專用推論伺服器上或許沒問題,但在開發者筆記型電腦上就相當危險。 + +## 步驟 3:載入影像以供 OCR + +正確的檔案格式是下一個關鍵環節。`OcrImage.FromFile` 會自動偵測影像類型,但仍建議先確認檔案是否存在,以及它是否屬於支援的 TIFF 變體(例如 LZW 壓縮或 CCITT‑G4)。 + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### 處理多頁 TIFF + +若你的 TIFF 包含多頁,Aspose OCR 預設只會讀取第一頁。若要處理全部頁面,可遍歷 `image.Pages`(較新 SDK 版本提供)並將每頁分別送入引擎。 + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +上述程式碼示範了 **載入影像供 OCR** 的通用模式,適用於單頁與多頁檔案。 + +## 步驟 4:從 TIF(或任何點陣圖)辨識文字 + +影像已載入記憶體後,我們請 Aspose 執行辨識。`Recognize` 方法會回傳 `OcrResult`,其中包含純文字、信心分數,甚至如果需要的話,還有文字框的座標資訊。 + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### 為什麼 TIF 特別適合 + +- **無損壓縮:** TIFF 常保存原始像素資料,提供 OCR 引擎最高的細節還原度。 +- **多種色彩空間:** Aspose 能直接處理灰階、RGB,甚至 CMYK 的 TIFF,無需額外轉換程式碼。 + +若要切換語言套件(例如法文或日文),請在呼叫 `Recognize` 前設定 `ocrEngine.Settings.Language = "fr"`。 + +## 步驟 5:顯示辨識結果 + +最後,我們把文字輸出到主控台。實際應用中,你可能會寫入資料庫、JSON 檔,或將字串傳給下游的 NLP 流程。 + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### 預期輸出 + +在 300 dpi、清晰的列印頁面掃描上執行程式,通常會得到類似以下的結果: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +若影像模糊或 GPU 記憶體上限設定過低,可能會出現亂碼或結果被截斷。將 `MemoryLimitMb` 設得低於影像實際佔用的記憶體(6000×8000 像素的 TIFF 大約需要 1 GB)時,引擎會自動回退至 CPU。 + +## 完整範例程式 + +以下是可直接執行的完整程式碼。將它貼到新的 Console App 專案中,將 `YOUR_DIRECTORY/large_photo.tif` 替換成你的 TIFF 路徑,然後按 **F5** 執行。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### 快速檢查清單 + +- ✅ **Aspose OCR C# example** 已成功編譯。 +- ✅ **GPU 已啟用**(`Enable = true`)。 +- ✅ **GPU 記憶體上限** 設為 2048 MB。 +- ✅ **影像已從 TIF 檔載入**。 +- ✅ **文字已辨識並列印**。 + +## 常見問題與避免方式 + +| 症狀 | 可能原因 | 解決方法 | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | 未安裝 CUDA 執行時或版本不符。 | 安裝與驅動相容的 CUDA 11.x(或 12.x)。 | +| OCR 回傳空字串 | 影像過暗或 DPI 低於 150。 | 使用 `image.AdjustContrast()` 前處理,或將解析度重採樣至 300 dpi。 | +| GPU 記憶體不足當機 | `MemoryLimitMb` 設定過低。 | 提高上限或使用 `image.Crop` 將影像切割成多塊。 | +| `Unsupported image format` 錯誤 | TIFF 使用了罕見壓縮(例如 JPEG‑2000)。 | 先用 ImageMagick 轉換成支援的格式再進行 OCR。 | + +## 延伸示範 + +既然已掌握 **aspose ocr c# example** 的核心流程,你可以進一步探索: + +- **批次處理:** 迴圈讀取資料夾內所有 TIF,將每個結果寫入 `.txt` 檔。 +- **語言套件:** `ocrEngine.Settings.Language = "es"` 以支援西班牙文,或載入自訂字典。 +- **文字框座標:** 使用 `ocrResult.Regions` 取得每個單字的座標,適合做遮蔽工具。 +- **CPU 回退機制:** 將 GPU 區塊包在 try/catch 中;若失敗,設定 `ocrEngine.Settings.Gpu.Enable = false` 後重新嘗試。 + +這些延伸保持了核心模式不變,同時為特定需求提供更多價值。 + +## 接下來該學什麼? + +以下教學與本篇內容密切相關,能進一步擴充你的技巧與 API 應用範圍,每篇皆附完整可執行的程式碼與步驟說明。 + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/hongkong/net/skew-angle-calculation/_index.md index ad80ec37e..3b96e5d03 100644 --- a/ocr/hongkong/net/skew-angle-calculation/_index.md +++ b/ocr/hongkong/net/skew-angle-calculation/_index.md @@ -40,9 +40,12 @@ url: /zh-hant/net/skew-angle-calculation/ 釋放 Aspose.OCR for .NET 的強大功能,這是一個強大的影像辨識解決方案。了解如何輕鬆計算傾斜角度。 ### [OCR 影像辨識中根據 URI 計算傾斜角度](./calculate-skew-angle-from-uri/) 探索 Aspose.OCR for .NET,輕鬆計算 OCR 影像辨識中的傾斜角度。精準有效率地增強您的專案。 +### [OCR 旋轉文件教程 – 自動校正傾斜與旋轉修正(C#)](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +深入了解如何使用 Aspose.OCR for .NET 自動校正旋轉文件的傾斜與旋轉,提升 C# 應用的文字辨識精度。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/hongkong/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..a24f3d3bf --- /dev/null +++ b/ocr/hongkong/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose OCR 於 C# 的 OCR 旋轉文件教學,示範如何自動校正傾斜並偵測旋轉。逐步學習,提供完整程式碼。 +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: zh-hant +og_description: OCR 旋轉文件教學教你如何使用 Aspose OCR 於 C# 中自動校正傾斜並偵測旋轉。請參考完整指南。 +og_title: OCR 旋轉文件教學 – C# 自動去斜與旋轉修正 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR 旋轉文件教學 – C# 自動去斜與旋轉校正 +url: /zh-hant/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 旋轉文件教學 – C# 開發者完整指南 + +有沒有遇過 **ocr rotated document tutorial**,當掃描的表單是橫向或斜放時?你並不孤單。這類變形的影像會破壞文字擷取的品質,好消息是 Aspose OCR 能自動幫你校正。 + +在本步驟說明中,我們會建立 `OcrEngine`、開啟 **automatic skew correction** 與 **auto detect rotation**,對旋轉過的影像執行辨識,並輸出乾淨的文字。完成後,你將清楚每個設定的作用、如何針對特殊情況微調,以及一個可直接執行的 C# 範例程式。 + +## 你將學會 + +* 如何在 .NET 專案中安裝與引用 **Aspose OCR**。 +* 為何啟用 `AutoCorrectSkew` 與 `AutoDetectRotation` 是可靠的 **ocr rotated document tutorial** 核心。 +* 如何載入任意影像(JPG、PNG、TIFF)並讓引擎自行處理。 +* 處理多頁 PDF、低解析度掃描與自訂語言套件的技巧。 + +> **先備條件:** Visual Studio 2022(或任何 C# IDE)、.NET 6+ 執行環境,以及有效的 Aspose OCR 授權(或免費試用版)。不需要先前的 OCR 經驗。 + +--- + +## 步驟 1 – 安裝 Aspose OCR 並建立專案 + +首先,取得 NuGet 套件: + +```bash +dotnet add package Aspose.OCR +``` + +> **小技巧:** 若使用試用授權,請將 `Aspose.OCR.lic` 檔案放在可執行檔同一資料夾,或以程式碼註冊:`License license = new License(); license.SetLicense("Aspose.OCR.lic");`。 + +建立新的 Console 應用程式: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +現在,你已擁有一個乾淨的起點,來完成 **ocr rotated document tutorial**。 + +## 步驟 2 – 初始化 OCR 引擎 + +引擎是整個流程的核心。把它想像成文字擷取的瑞士軍刀,只要告訴它要啟用哪些功能即可。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**為什麼要這樣設定?** +* `AutoCorrectSkew` 會分析字元基線,將影像旋轉至行列水平。 +* `AutoDetectRotation` 會檢測整體方向(0°、90°、180°、270°),若影像倒置則自動翻轉。若未啟用,引擎可能會讀出 “pɹᴉʍ” 而非 “word”。 + +## 步驟 3 – 載入要處理的影像 + +Aspose OCR 支援所有常見的點陣圖格式。將佔位路徑替換成實際的旋轉表單位置。 + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **特殊情況:** 若收到多頁 TIFF,請使用 `OcrImage.FromMultiPageTiff(filePath)`,並在 `image.Pages` 上迴圈處理。 + +## 步驟 4 – 執行辨識 + +現在引擎會開始發威。它會先根據我們的斜率/旋轉旗標校正影像,然後擷取文字。 + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +若需要除英文外的語言支援,請在呼叫 `Recognize` 前設定: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## 步驟 5 – 輸出辨識結果 + +最後,將乾淨的文字輸出到主控台,或導向檔案、資料庫,依你的工作流程自行決定。 + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**預期輸出**(假設範例影像內含 “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +即使原始影像旋轉了 90° 且略有斜度,文字仍能正確顯示。 + +--- + +## 處理常見問題 + +| 問題 | 為何會發生 | 解決方式 | +|------|------------|----------| +| **輸出空白** | 斜率校正未開啟或影像過暗。 | 開啟 `AutoCorrectSkew`(已預設開啟)並使用 `image.AdjustContrast(1.2)` 提升對比度。 | +| **出現雜訊字元** | 語言設定錯誤。 | 將 `ocrEngine.Settings.Language` 設為文件實際語言。 | +| **大型 PDF 效能下降** | 引擎逐頁順序處理。 | 使用 `Parallel.ForEach` 於 `image.Pages` 以利用多核心 CPU。 | +| **授權例外** | 試用期已過。 | 取得正式授權或遵守試用限制(每次最多 5 頁)。 | + +--- + +## 強化 OCR 旋轉文件教學的專業技巧 + +* **批次處理:** 將整個流程封裝成接受資料夾路徑的 method,遍歷每張影像,並將結果寫入 `.txt` 檔。 +* **前置處理:** 噪點較多的掃描可先呼叫 `image.Denoise()`。 +* **後置處理:** 使用正規表達式清理常見 OCR 錯誤,例如僅在字母環繞時將 “0” 替換成 “O”。 +* **記錄日志:** Aspose OCR 提供 `ocrEngine.Logger`,可接到檔案 logger,記錄低信心分數的警告。 + +--- + +## 完整、可直接執行的程式碼 + +將以下程式碼存為 `Program.cs` 放入你的 Console 專案。內含所有步驟、註解,以及簡易的批次處理輔助函式。 + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +執行方式: + +```bash +dotnet run +``` + +執行後,你應該會在主控台看到已校正的文字,證明我們的 **ocr rotated document tutorial** 能端對端運作。 + +--- + +## 結論 + +現在你已掌握一套完整的 **ocr rotated document tutorial**,能自動校正斜率、偵測旋轉,並使用 Aspose OCR 在 C# 中擷取乾淨文字。關鍵在於同時啟用 `AutoCorrectSkew` **與** `AutoDetectRotation`,只要幾行程式碼就能把嚴重傾斜的掃描稿變成可讀的輸出。 + +接下來,你可以擴展為批次作業、整合語言套件,或將結果送入後續分析管線。想進一步探索 **automatic skew correction**?可參考 Aspose 的影像前置處理 API,或自行調整雜訊掃描的閾值。 + +對 PDF、多頁 TIFF、或與 Azure Functions 整合有疑問嗎?歡迎留言討論,祝開發順利! + +## 接下來該學什麼? + +以下教學與本篇內容密切相關,能進一步延伸本指南所示的技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能或探索替代實作方式。 + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/hongkong/net/text-recognition/_index.md index 948767d8e..b1c8bfe29 100644 --- a/ocr/hongkong/net/text-recognition/_index.md +++ b/ocr/hongkong/net/text-recognition/_index.md @@ -55,9 +55,19 @@ url: /zh-hant/net/text-recognition/ 使用 Aspose.OCR 釋放 .NET 中 OCR 的潛力。輕鬆從 PDF 中提取文字。立即下載以獲得無縫整合體驗。 ### [OCR影像辨識中的辨識表](./recognize-table/) 透過我們關於 OCR 影像辨識中表格辨識的綜合指南,釋放 Aspose.OCR for .NET 的潛力。 +### [使用 Aspose OCR 在影像上執行 OCR – 印度語指南](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +學習如何使用 Aspose OCR 於影像上執行 OCR,並支援印度語文字的辨識。 +### [使用 Aspose OCR 在 PDF 上執行 OCR – 完整 C# 指南](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +學習如何使用 Aspose OCR 在 PDF 文件上執行 OCR,提供完整的 C# 實作步驟與範例。 +### [如何使用 Aspose:將影像轉換為 HTML 並使用 OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +### [在影像上執行 OCR 並偵測拼寫錯誤的單詞(C#)](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +學習如何使用 Aspose.OCR 在影像上執行 OCR,並利用內建功能偵測拼寫錯誤的單詞,示範 C# 實作步驟。 +### [在 C# 中執行影片字幕 OCR – 完整指南](./video-subtitle-ocr-in-c-complete-guide/) +學習如何使用 Aspose.OCR 在 C# 中辨識影片字幕,提供完整步驟與範例,提升多媒體文字處理能力。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/hongkong/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..0bf91a3b2 --- /dev/null +++ b/ocr/hongkong/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-03 +description: 如何在 C# 中使用 Aspose 將圖片轉換為 HTML 並從圖片中提取文字。快速學習如何從圖片產生 HTML 以及將圖片 OCR 為 + HTML。 +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: zh-hant +og_description: 如何使用 Aspose 在 C# 中將圖片轉換為 HTML、從圖片提取文字,並使用 OCR 從圖片生成 HTML。請參考完整指南。 +og_title: 如何使用 Aspose:使用 OCR 將圖像轉換為 HTML +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 如何使用 Aspose:將圖片轉換為帶 OCR 的 HTML +url: /zh-hant/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何使用 Aspose:將影像轉換為帶 OCR 的 HTML + +有沒有想過 **如何使用 Aspose** 把掃描過的圖片變成整齊的 HTML?也許你手上有雜誌頁面、收據,或是手寫筆記,且需要保留文字與版面配置以供網站發佈。好消息是,你不必自行撰寫解析器或與低階影像處理糾纏——Aspose.OCR 會為你完成繁重的工作。 + +在本教學中,我們將示範一個 **完整、可執行的範例**,說明如何 **將影像轉換為 HTML**、**從影像中擷取文字**,以及 **從影像產生 HTML**,使用 Aspose OCR 函式庫於 C#。完成後,你將擁有一個小型主控台應用程式,能產生保留原始頁面版面的 HTML 檔,隨時可嵌入任何網站。 + +## 前置需求 + +在開始之前,請確保你的機器上已安裝以下項目: + +- **.NET 6.0 SDK** 或更新版本(此程式碼同時支援 .NET Core 與 .NET Framework)。 +- **Visual Studio 2022**(或任何你慣用的編輯器)。 +- **Aspose.OCR for .NET** – 透過 NuGet 安裝:`dotnet add package Aspose.OCR`。 +- 一張欲轉換的影像檔(JPEG/PNG),例如 `magazine_page.jpg`。 + +不需要額外的設定檔;函式庫已內建所有 OCR 與 HTML 版面產生所需的資源。 + +## 步驟 1:建立專案並加入 Aspose.OCR + +首先,建立一個新的主控台專案,並將 Aspose OCR 套件加入專案中。 + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **小技巧:** 若使用 Visual Studio,只要在專案上點右鍵 → *Manage NuGet Packages* → 搜尋 **Aspose.OCR** 並安裝。此步驟可確保你能 **ocr image to html** 而不會缺少參考。 + +## 步驟 2:初始化 OCR 引擎 + +此流程的核心是 `OcrEngine` 類別。它就像是閱讀圖片並決定輸出結果的大腦。 + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +在此我們建立 `OcrEngine` 的實例。免費版不需要提供任何憑證,函式庫會使用內建的辨識模型。 + +## 步驟 3:載入來源影像 + +接著,將引擎指向你要處理的檔案。Aspose 提供便利的 `OcrImage.FromFile` 方法,可處理大多數影像格式。 + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +將 `YOUR_DIRECTORY` 替換為影像所在的絕對或相對路徑。若影像與執行檔位於同一資料夾,只需使用 `"magazine_page.jpg"` 即可。 + +## 步驟 4:辨識並要求產生具版面配置的 HTML + +這是本教學的重點。傳入 `OutputFormat.HtmlWithLayout` 後,Aspose 會 **generate HTML from image**,同時保留文字區塊、圖片與表格的原始位置。 + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text` 屬性現在包含完整的 HTML 文件。若只需要純文字,可改用 `OutputFormat.Text`,但此處我們聚焦於 **convert image to html** 並保持版面忠實度。 + +## 步驟 5:儲存 HTML 檔案 + +最後,將 HTML 字串寫入磁碟。如此即可得到一個隨時可在瀏覽器開啟的檔案。 + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +執行程式後會產生 `magazine.html`。開啟它,你會看到原始頁面的文字恰如其分地排列——非常適合保存或網站發佈。 + +## 完整範例程式 + +以下是 **完整、可直接複製貼上的** 程式碼。未遺漏任何部份,設定好路徑後即可編譯執行。 + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### 預期輸出 + +在瀏覽器開啟 `magazine.html` 時,應會看到類似下列(為說明簡化)的畫面: + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +實際的 `style` 屬性會依原始影像而異,但結構保證 **extract text from image** 與 **generate html from image** 於同一步驟完成,流程順暢。 + +## 常見問題與特殊情況 + +### 若影像解析度太低怎麼辦? + +Aspose.OCR 最佳效果需至少 **300 DPI** 的影像。若檔案模糊,可先使用影像增強函式庫(例如 ImageSharp)進行前處理,再交給 OCR 引擎。低品質會影響 **extract text from image** 的準確度與產生 HTML 版面的忠實度。 + +### 能否控制 OCR 的語言? + +可以。於呼叫 `Recognize` 前設定 `OcrEngine` 的 `Language` 屬性: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +這可提升非英文字符的辨識率。 + +### 如何取得純文字而非 HTML? + +若只需要原始字串,將 `OutputFormat.HtmlWithLayout` 改為 `OutputFormat.Text`。此時 `recognitionResult.Text` 只會包含擷取出的文字。 + +### 能否將影像嵌入產生的 HTML 中? + +使用 `OutputFormat.HtmlWithLayoutAndImages` 時,Aspose.OCR 會將原始影像以 base‑64 data URI 形式嵌入 HTML。這在需要單一 HTML 檔且不想額外管理資源時相當方便。 + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### 大量批次處理該怎麼做? + +對於批次作業,可將邏輯包在 `foreach` 迴圈中,遍歷多個檔案路徑。重複使用同一個 `OcrEngine` 實例可減少開銷,提升 **convert image to html** 的效能。 + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## 產線級程式撰寫建議 + +- **釋放資源**:`OcrEngine` 與 `OcrImage` 皆實作 `IDisposable`,請以 `using` 包裹以即時釋放原生記憶體。 +- **錯誤處理**:捕捉 `IOException` 處理檔案相關問題,捕捉 `OcrException` 處理辨識錯誤。 +- **效能**:若需處理大量影像,可考慮使用 **平行處理**(`Parallel.ForEach`),但要留意 CPU 使用率——OCR 本身相當耗 CPU。 +- **日誌**:整合日誌框架(如 Serilog)以記錄 OCR 信心分數(`recognitionResult.Confidence`),便於品質監控。 + +## 結論 + +我們已說明 **如何使用 Aspose** 於 C# 中 **convert image to HTML**、**extract text from image**,以及 **generate HTML from image**,只需幾個簡單步驟。完整程式碼展示了如何 **ocr image to html** 同時保留版面,為任何文件數位化專案奠定堅實基礎。 + +接下來,你可以: + +- 嘗試不同的 `OutputFormat` 以符合需求。 +- 結合產生的 HTML 與 CSS 框架,打造響應式樣式。 +- 將擷取的文字導入搜尋索引或機器學習管線。 + +快去試試看,調整設定,體驗 Aspose 如何輕鬆將圖片變成可上網的內容。如有任何問題,歡迎留言——祝開發順利! + +![顯示從影像到 HTML 版面之 OCR 流程圖 – 如何使用 Aspose](/images/ocr-pipeline.png "如何使用 Aspose") + +--- + +## 接下來該學什麼? + +以下教學與本指南緊密相關,提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能,並在專案中探索其他實作方式。 + +- [使用 Aspose.OCR 於 C# 進行語言選擇的影像文字擷取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [將影像轉換為文字 – 從 URL 執行 OCR](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [使用 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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/hongkong/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..17e11702e --- /dev/null +++ b/ocr/hongkong/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose.OCR 對圖片執行文字辨識並擷取文字。於單一 C# 示範中學習如何偵測拼寫錯誤並取得拼寫建議。 +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: zh-hant +og_description: 對圖像執行 OCR 以提取文字,然後偵測拼字錯誤並取得拼字建議,使用 Aspose.OCR 於 C#。 +og_title: 在影像上執行 OCR 並偵測錯別字(C#) +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: 在 C# 中對圖像執行 OCR 並偵測拼寫錯誤的字詞 +url: /zh-hant/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中對圖像執行 OCR 並偵測拼寫錯誤 + +有沒有想過如何 **perform OCR on image** 而不至於抓狂?你並不是唯一的疑問者。無論是數位化舊信件、掃描收據,或是構建智慧文件工作流程,從圖片中提取乾淨文字都是第一道關卡。好消息是,只要使用 Aspose.OCR,你可以在幾分鐘內完成解決方案,且同時 **detect misspelled words** 並 **get spelling suggestions**。 + +在本教學中,我們將逐步說明一個完整、可直接執行的 C# 主控台應用程式,**extract text from image**、執行英文拼寫檢查,並將每個錯誤與修正建議印出。完成後,你將清楚知道 **how to extract text**、如何呼叫拼寫檢查 API,以及預期的主控台輸出長什麼樣子。 + +## 你將會建立的功能 + +- 載入包含錯別字的 bitmap(或 PNG)。 +- 使用 Aspose.OCR **perform OCR on image** 並取得原始字串資料。 +- 初始化內建的英文拼寫檢查器。 +- **Detect misspelled words** 並 **get spelling suggestions**。 +- 在主控台印出整齊的報告。 + +不需要外部服務,也不需要繁雜的 HTTP 呼叫——只要一個 NuGet 套件與少量程式碼。 + +## 前置條件 + +- .NET 6.0 SDK 或更新版本(此程式碼亦可在 .NET Framework 4.7+ 上執行)。 +- Visual Studio 2022(或任何你喜歡的編輯器)。 +- Aspose.OCR for .NET NuGet 套件(`Aspose.OCR`)。 +- 一個圖像檔案(`letter_with_typos.png`),放在專案可參照的路徑下。 + +如果你從未使用過 Aspose,也別擔心——安裝套件只要執行以下指令: + +```bash +dotnet add package Aspose.OCR +``` + +現在讓我們深入實作。 + +## 步驟 1:建立專案並安裝 Aspose.OCR + +建立一個新的主控台專案,並將 OCR 函式庫加入: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +還原完成後,開啟 `Program.cs`。稍後我們會把預設內容換成完整示範程式碼,先說明每個命名空間的用途。 + +- `Aspose.OCR` – 核心 OCR 引擎與圖像處理。 +- `Aspose.OCR.SpellCheck` – 隨函式庫提供的拼寫檢查工具。 +- `System` – 標準 .NET 基礎類別(例如 `Console`)。 + +## 步驟 2:載入圖像並 **perform OCR on image** + +真正的工作是把圖像送入 OCR 引擎。Aspose.OCR 支援多種格式(PNG、JPEG、TIFF)。以下程式碼負責完成這項重任: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **為什麼重要:** `OcrImage.FromFile` 會抽象化像素層面的細節,而 `OcrEngine.Recognize` 會執行訓練好的神經模型,將視覺字形轉換成 Unicode 字元。`ocrResult.Text` 屬性現在就保存了原始字串——正是 **extract text from image** 所需要的資料。 +> +> > **小技巧:** 若圖像包含多種語言,可在呼叫 `Recognize` 前設定 `ocrEngine.Language = OcrLanguage.Multilingual;`。 + +## 步驟 3:初始化英文拼寫檢查器 + +Aspose.OCR 內建的拼寫檢查引擎預設支援英文,只要一行程式即可完成初始化: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **為什麼這一步關鍵:** OCR 輸出可能包含辨識錯誤(例如 “l” 與 “1” 混淆)或原始文件本身的錯別字。拼寫檢查器會掃描字串、找出可疑的 token,並提供替代方案。 + +## 步驟 4:**Detect Misspelled Words** 並 **Get Spelling Suggestions** + +將 OCR 取得的文字交給檢查器: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` 為一個集合,每筆條目包含錯誤單字以及可能的修正字串陣列。 + +## 步驟 5:輸出結果 + +最後,我們遍歷集合並印出易讀的報告: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### 預期的主控台輸出 + +假設 `letter_with_typos.png` 內的句子為: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +執行示範程式後會產生類似以下的結果: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +可以看到每個錯字都配上一組合理的修正建議——這正是建構使用者友好校正 UI 時所需要的。 + +## 完整可執行範例 + +以下是 **完整、可直接複製貼上的** 程式。請將 `YOUR_DIRECTORY` 替換成實際的圖像檔案路徑。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **需留意的邊緣情況** +> - **空白圖像:** 若 OCR 引擎回傳空字串,`spellChecker.Check` 只會回傳空集合——不會當機。 +> - **非英文文字:** 將 `OcrLanguage.English` 換成 `OcrLanguage.French`(或其他支援語言)即可 **detect misspelled words** 於其他語系。 +> - **大型文件:** 若處理多頁 PDF,請對每頁迴圈執行 OCR,然後在拼寫檢查前彙總結果。 + +## 視覺概覽(圖片替代文字) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*上圖說明端對端流程:圖像 → OCR 引擎 → 原始文字 → 拼寫檢查器 → 建議。* + +## 常見問題與進階小技巧 + +| Question | Answer | +|----------|--------| +| **是否需要網路連線?** | 不需要。Aspose.OCR 完全在本機執行,適合離線或高安全性環境。 | +| **拼寫檢查的準確度如何?** | 使用約 15 萬筆英文單字的字典與模糊匹配,大多數常見錯別字都能被捕捉。 | +| **可以自訂字典嗎?** | 可以。`SpellChecker.AddUserDictionary("custom.txt")` 讓你載入領域專屬詞彙(例如產品名稱)。 | +| **圖像若傾斜該怎麼辦?** | OCR 引擎會自動偵測方向,但對於頑固情況,可手動呼叫 `ocrEngine.ImagePreprocessing.Rotate(angle)` 進行旋轉。 | +| **有沒有方法在 UI 上標示建議?** | 取得 `misspellings` 集合後,可將每個 `entry.Word` 對應回 `ocrResult.Text` 中的位置,並在 RichTextBox 或 WebView 中加底線或高亮。 | + +## 結論 + +我們已示範如何 **perform OCR on image**、**extract text from image**,再 **detect misspelled words** 並 **get spelling suggestions**,全部透過簡潔的 C# 主控台應用程式完成。核心概念很簡單:讓 Aspose.OCR 負責字元辨識,然後利用內建的拼寫檢查器清理輸出。接下來,你可以將此示範擴充為完整的文件處理服務、整合至 Web API,或嵌入桌面編輯器。 + +準備好進一步挑戰了嗎?試著改用西班牙語、處理多頁 PDF,或打造一個小型 WPF 前端,讓使用者點擊單字接受建議。所有基礎已備妥,只等你持續實驗。 + +如果在實作過程中遇到問題或有擴充想法,歡迎在下方留言。祝開發順利! + +## 接下來該學什麼? + +以下教學與本篇內容緊密相關,能進一步深化你的技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能與替代實作方式。 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/hongkong/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..09b8f10ae --- /dev/null +++ b/ocr/hongkong/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose OCR 在 C# 中對圖像執行 OCR。學習如何載入圖像進行 OCR,並離線提取印地語文字圖像,提供逐步程式碼說明。 +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: zh-hant +og_description: 在 C# 中使用 Aspose OCR 進行圖像 OCR。此教學示範如何載入圖像進行 OCR,離線提取印地語文字,並提供可執行的程式碼。 +og_title: 對圖像執行 OCR – Aspose OCR 印地語指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: 使用 Aspose OCR 在圖像上執行 OCR – 印地語指南 +url: /zh-hant/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 Aspose OCR 在圖像上執行 OCR – 印地語指南 + +有沒有曾經需要**在圖像上執行 OCR**,卻不知道如何取得印地語字元?你並不孤單——許多開發者在首次嘗試讀取非拉丁文字時都會碰到這個問題。好消息是 Aspose OCR 讓這個過程相當簡單,而且甚至可以完全離線執行。 + +在本指南中,我們將**載入圖像以進行 OCR**,將引擎指向離線語言套件,最後**擷取印地語文字圖像**資料,且全程不需要連線。完成後,你將擁有一個可直接執行的 C# 主控台應用程式,能讀取印地語收據並將文字輸出到主控台。 + +## 需要的環境 + +- **.NET 6.0** 或更新版本(程式碼亦相容 .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet 套件 + `dotnet add package Aspose.OCR` +- 包含**離線印地語語言資源**的資料夾(可從 Aspose 入口網站下載) +- 含有印地語文字的圖像檔,例如 `receipt_hindi.png` + +就這樣——不需要外部服務、API 金鑰,只有直接的程式碼。 + +## 在圖像上執行 OCR – 步驟實作 + +以下我們將流程分為七個清晰步驟。每個步驟都說明**為什麼**它重要,而不僅僅是**要輸入什麼**。 + +### 步驟 1:建立 OCR 引擎實例 + +引擎是 Aspose OCR 的核心。實例化它即可取得之後會調整的所有設定。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **為什麼?** +> 如果沒有 `OcrEngine`,就沒有物件可以呼叫 `Recognize`。把它想像成稍後會掃描圖片的「相機」。 + +### 步驟 2:將引擎指向離線資源 + +Aspose 會提供可本機儲存的語言套件。設定 `ResourcesFolder` 讓引擎知道要去哪裡尋找。 + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **提示:** +> 在開發期間使用絕對路徑,之後在正式環境切換為相對路徑或設定檔設定。 + +### 步驟 3:強制離線模式 + +你可能會想,「真的需要停用線上查詢嗎?」如果你在防火牆後或只想要確定的結果,請將 `UseOfflineResources` 設為 `true`。 + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **專業提示:** +> 若將此旗標保留為 `false`,引擎可能會下載額外資料,導致延遲,甚至違反安全政策。 + +### 步驟 4:選擇印地語作為辨識語言 + +在此我們透過告訴引擎預期的語言來**擷取印地語文字圖像**。這會大幅提升準確度。 + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **為什麼有效:** +> OCR 引擎使用特定語言的字元模型。鎖定印地語後,可避免引擎在數十種文字間猜測。 + +### 步驟 5:載入圖像以進行 OCR + +現在我們真正**載入圖像以進行 OCR**。`OcrImage.FromFile` 方法會將位圖讀取成引擎可理解的格式。 + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **常見陷阱:** +> 在 Windows 上使用正斜線路徑仍可運作,但使用 `Path.Combine` 可讓程式碼跨平台。 + +### 步驟 6:執行辨識 + +在所有設定完成後,我們最終透過呼叫 `Recognize` **在圖像上執行 OCR**。 + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **發生了什麼?** +> 引擎會掃描每個像素,將圖樣與印地語字形資料庫比對,並組合成 Unicode 字元字串。 + +### 步驟 7:輸出辨識文字 + +結果物件包含 `Text` 屬性,內含擷取的字串。我們只需將它寫入主控台。 + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **預期輸出:** +> 如果 `receipt_hindi.png` 包含「भुगतान सफल」,主控台會精確列印該行,保留變音符號。 + +## 載入圖像以進行 OCR – 準備資源 + +如果你在想是否可以改用串流而非檔案提供給引擎,答案是可以。將 `OcrImage.FromFile` 替換為: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **為什麼使用串流?** +> 串流讓你能處理儲存在資料庫、雲端 Blob 或嵌入式資源的圖像——非常適合可擴充的服務。 + +## 擷取印地語文字圖像 – 處理邊緣案例 + +1. **缺少語言套件** – 若找不到印地語套件,`Recognize` 會拋出例外。請將呼叫包在 try/catch 中,並記錄友善訊息。 +2. **低解析度圖像** – OCR 準確度在低於 300 dpi 時會下降。載入前先對圖像做前處理(調整大小、銳化)。 +3. **混合語言文件** – 你可以啟用多語言: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +這些調整可確保你的**在圖像上執行 OCR**流程在正式環境中保持穩定。 + +## 執行完整範例 + +將以下程式碼儲存為 `Program.cs`,替換佔位路徑後執行: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +執行 `dotnet run` 後,應會看到類似以下的輸出: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +若得到空字串,請再次確認 **ResourcesFolder** 指向包含 `Hindi.traineddata` 的資料夾,且圖像足夠清晰。 + +## 結論 + +我們已說明如何使用 Aspose OCR **在圖像上執行 OCR**,從 **載入圖像以進行 OCR** 到 **擷取印地語文字圖像**,全部在離線環境下完成。上方完整可執行的程式碼提供了堅實的基礎,而關於串流、錯誤處理與多語言支援的技巧,將協助你將此解決方案套用到實務專案。 + +準備好下一步了嗎?試著將語言切換為 **OcrLanguage.Tamil**,或從 Azure Blob 儲存體提供圖像。你也可以嘗試 `ImagePreprocessing` 設定,以提升噪點收據的辨識準確度。 + +有任何問題或遇到卡關嗎?留下評論吧——祝開發愉快! + +![Perform OCR on image example + +## 接下來該學什麼? + +以下教學涵蓋與本指南緊密相關的主題,建立在本篇示範的技術之上。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [使用 Aspose.OCR 於 C# 進行圖像文字擷取與語言選擇](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [使用 Aspose OCR 進行多語言圖像文字辨識](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [從圖像擷取文字 – 使用 Aspose.OCR for .NET 進行 OCR 最佳化](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/hongkong/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..365463c5e --- /dev/null +++ b/ocr/hongkong/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-03 +description: 使用 Aspose.OCR 對 PDF 進行光學字符辨識,將掃描版 PDF 轉換為可搜尋的 PDF。了解如何從 PDF 識別文字,並在數分鐘內建立可搜尋的 + PDF。 +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: zh-hant +og_description: 執行 OCR 於 PDF 並即時產生可搜尋的 PDF。本教學逐步說明如何使用 Aspose.OCR 從 PDF 識別文字。 +og_title: 在 PDF 上執行 OCR – 完整 C# 指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: 使用 Aspose.OCR 在 PDF 上執行 OCR – 完整 C# 指南 +url: /zh-hant/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 PDF 上執行 OCR – 完整 C# 教學 + +有沒有想過 **如何在 PDF 檔案上執行 OCR**,卻不想與數十個命令列工具糾纏?你並不孤單。無論是數位化發票、保存舊報告,或只是需要可搜尋的掃描合約版本,將靜態 PDF 變成可搜尋的檔案都是顛覆性的改變。 + +在本教學中,我們將一步步說明 **如何使用 Aspose.OCR for .NET**,將掃描 PDF(甚至純圖片)轉換成可搜尋的 PDF。完成後,你只需要幾行 C# 程式碼就能 **從 PDF 辨識文字**,同時了解每一步背後的原理,讓你能將此解決方案套用到自己的專案。 + +> **快速重點:** 整個流程只需要三件事——初始化 OCR 引擎、提供來源(PDF 或圖片),以及儲存可搜尋的 PDF 輸出。讓我們深入探討。 + +--- + +## 需要的條件 + +在開始之前,請確保你已具備以下項目: + +| 前置條件 | 為何重要 | +|--------------|----------------| +| **.NET 6.0+**(或 .NET Framework 4.6+) | Aspose.OCR 針對現代執行環境;舊版可能缺少 API 更新。 | +| **Aspose.OCR for .NET** NuGet 套件 | 提供 `OcrEngine` 類別與 PDF 處理工具。 | +| **有效的 Aspose 授權**(或使用免費評估版) | 未授權會受到 30 天評估限制與浮水印。 | +| **一份要轉成可搜尋的掃描 PDF**(或影像檔) | 這是 OCR 的來源文件。 | +| **Visual Studio 2022**(或任何 C# 編輯器) | 方便除錯,但任何 IDE 都可使用。 | + +你可以使用以下 NuGet 指令安裝程式庫: + +```bash +dotnet add package Aspose.OCR +``` + +> **專業小技巧:** 若在 CI 流程中使用,請將授權檔加入建置產物,並在執行時載入,以避免硬編碼路徑。 + +--- + +## 在 PDF 上執行 OCR – 設定 Aspose.OCR + +首先,我們需要一個全新的 `OcrEngine` 實例。把它想像成會閱讀文件的大腦。 + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +為什麼每次都要建立新實例?引擎會保存設定(例如語言),不同文件可能需要不同設定。每次執行時重新實例化可確保乾淨的狀態,避免工作之間的相互影響。 + +--- + +## 如何建立可搜尋的 PDF – 設定密碼(可選) + +如果你的 PDF 受保護,必須先告訴引擎密碼,才能讀取頁面: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +在受保護的檔案上跳過此步驟會拋出 `PdfPasswordException`。若不確定檔案是否受保護,請務必使用 try‑catch 包住。 + +--- + +## 將掃描 PDF 轉換為可搜尋 PDF – 載入來源 + +Aspose.OCR 使用 `OcrImage` 抽象層,可包裝 PDF、TIFF、JPEG 等。以下示範如何將掃描 PDF 載入記憶體: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +在背後,`FromFile` 會把每一頁解析成光柵影像,供 OCR 引擎處理。若 PDF 為多頁,引擎會自動遍歷每一頁。 + +--- + +## 從 PDF 辨識文字 – 執行 OCR + +現在進入教學核心:請求引擎辨識文字並輸出可搜尋的 PDF。 + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` 告訴引擎在原始掃描影像上嵌入隱形文字層。產生的 PDF 保留掃描的視覺品質,同時變得完全可搜尋——正是合規稽核所需。 + +--- + +## 將影像轉成可搜尋 PDF – 儲存結果 + +最後,將二進位資料寫入磁碟: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary` 屬性保存原始 PDF 位元組。若你在開發 API,也可以直接將其串流回應。 + +--- + +![顯示 OCR 轉換流程以建立可搜尋 PDF 的圖示](https://example.com/ocr-flow.png "執行 PDF OCR 流程圖示") + +*圖片說明:執行 PDF OCR 流程圖示,說明如何將掃描 PDF 轉換為可搜尋 PDF。* + +--- + +## 邊緣情況與實務技巧 + +### 1. 大檔案與記憶體管理 +若處理超過 100 MB 的 PDF,建議使用 `OcrEngineSettings.MemoryLimit` 來限制記憶體使用量。另外,分批處理頁面以避免 `OutOfMemoryException`。 + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. 語言支援 +預設 Aspose.OCR 假設英文。若要辨識其他語言,請設定 `Language` 屬性: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. 多執行緒情境 +`OcrEngine` **不**具備執行緒安全性。若需要平行處理,請為每個執行緒建立獨立的引擎實例。 + +### 4. 偵錯 OCR 正確度 +你可以從 `ocrResult` 取出純文字以進行偵錯: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +如果輸出雜亂,可嘗試調整 `PreprocessSettings`(例如去斜、除噪)以提升品質。 + +### 5. 授權注意事項 +使用評估版時,Aspose 會在輸出 PDF 加上浮水印。請在應用程式啟動時盡早註冊授權: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## 完整範例 – 從頭到尾 + +以下提供一個完整、可直接執行的程式,已整合上述所有技巧。可直接複製貼上至新的 Console 專案。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**預期輸出:** 執行後,主控台會顯示檔案位置。使用任何 PDF 閱讀器開啟 `output.pdf`,嘗試搜尋原始掃描中已知的字詞。若文字被高亮,即代表你已成功 **在 PDF 上執行 OCR** 並建立可搜尋文件。 + +--- + +## 常見問題 + +**Q: 我可以用它把單張影像(PNG/JPEG)轉成可搜尋的 PDF 嗎?** +A: 當然可以。只要把 `OcrImage.FromFile("input.pdf")` 換成你的影像檔路徑,引擎會同樣將影像光柵化並嵌入 OCR 文字層。 + +**Q: 若我的 PDF 同時包含掃描頁面與原生文字,會怎樣?** +A: 引擎會在現有內容上覆蓋 OCR 文字層,原生文字仍可選取,掃描頁面則變為可搜尋。 + +**Q: OCR 的準確度如何?** +A: 準確度取決於來源品質。乾淨且高解析度(>300 dpi)的掃描可達 >95 % 的準確率。對於噪點較多的文件,可在呼叫 `Recognize` 前啟用 `PreprocessSettings`(去斜、除噪)以改善效果。 + +--- + +## 後續步驟 – 擴充你的 OCR 工具箱 + +既然已能 **從 PDF 辨識文字** 並 **將掃描 PDF 轉換為可搜尋 PDF**,以下是可進一步探索的主題: + +- **批次處理**:遍歷資料夾中的多個 PDF,自動產生可搜尋版本。 +- **文字抽取**:使用 `ocrResult.Text` 將結果送入搜尋索引(例如 Elasticsearch)。 +- **自訂語言套件**:從 Aspose 下載額外語言資料,以支援亞洲文字。 +- **PDF/A 合規**:結合 Aspose.PDF 與 OCR 輸出,產生符合保存標準的 PDF。 + +上述每項都以本教學的核心步驟為基礎,讓你輕鬆擴展解決方案。 + +--- + +## 結語 + +我們已示範如何使用 Aspose.OCR 在 PDF 上執行 OCR,將掃描 PDF 轉換為完整可搜尋的 PDF,甚至說明了如何把純影像轉成可搜尋 PDF。以下程式碼 + +## 接下來該學什麼? + +以下教學與本指南緊密相關,能進一步深化你所學的技巧。每個資源皆提供完整可執行的程式碼範例與逐步說明,協助你掌握更多 API 功能,並在自己的專案中探索替代實作方式。 + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/hongkong/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..ff05ec84a --- /dev/null +++ b/ocr/hongkong/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: 影片字幕 OCR 教學,示範如何從影片中擷取畫格,並使用 Aspose.OCR 讀取 MP4 等影片檔案的文字。 +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: zh-hant +og_description: 使用 Aspose.OCR 學習影片字幕文字辨識。只需幾分鐘,即可從影片擷取畫格、讀取文字,並從 MP4 中提取文字。 +og_title: C# 影片字幕 OCR – 逐步指南 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: C# 影片字幕 OCR – 完整指南 +url: /zh-hant/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# 影片字幕 OCR 完整指南 + +曾經需要 **video subtitle ocr** 卻不知從何下手嗎?你並不孤單。無論是數位化講座錄影、從訓練影片中擷取字幕,或只是好奇如何從影片中讀取文字,本教學都會一步步示範如何使用 C# 與 Aspose.OCR 完成。 + +在接下來的幾分鐘內,我們會從影片中擷取畫格、對這些畫格執行 OCR,最後逐格顯示字幕文字。完成後,你將能 **read text from video** 檔案(包括 MP4),不必再尋找第三方工具。 + +## 你將會建立的功能 + +我們會建立一個小型 console 應用程式,具備以下功能: + +1. 將 MP4(或任何支援格式)解碼成單獨的 `Bitmap` 畫格。 +2. 限制 OCR 區域至字幕帶,避免引擎被整張畫面分散注意力。 +3. 使用 Aspose 的 `VideoOcrProcessor` 處理每一個畫格。 +4. 將辨識出的字幕文字印出到 console。 + +沒有多餘的說明,只有可直接套用於實際專案的完整端對端範例。 + +## 前置條件 + +- **.NET 6.0** 或更新版本(此程式碼亦可於 .NET Framework 4.7+ 執行)。 +- **Aspose.OCR for .NET** – 透過 NuGet 安裝:`Install-Package Aspose.OCR`。 +- 一個影片檔案(MP4 表現最佳)。 +- 用於解碼影片畫格的方式 – 示範使用佔位方法,你可以自行接入 FFmpeg、OpenCV 或任何回傳 `Bitmap` 物件的函式庫。 + +> 小技巧:若在 Windows 上,`System.Drawing.Common` 套件可直接使用 `Bitmap`。在 Linux/macOS 上則需安裝原生的 `libgdiplus` 相依性。 + +## 步驟 1 – 從影片擷取畫格 + +第一道關卡是把動態影像轉成靜態圖片。下面的 `GetVideoFrames` 方法故意留空;請以你慣用的解碼器取代。以下示範使用 FFmpeg‑Core(僅為說明資料結構): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **為什麼這很重要:** 擷取畫格讓 OCR 引擎能對靜態影像進行辨識,較直接從影片串流讀取時的準確度提升許多。 + +## 步驟 2 – 設定 VideoOcrProcessor + +現在我們手上有一系列 `Bitmap` 物件,可以把它們交給 Aspose.OCR。`VideoOcrProcessor` 允許我們定義 **Region of Interest (ROI)**,非常適合只針對通常位於畫面上下方的字幕帶。 + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **為什麼要限制 ROI?** 忽略畫面的其他部分可減少雜訊、縮短處理時間,並避免因背景圖形產生的誤判。 + +## 步驟 3 – 對畫格序列執行 OCR + +處理器準備好後,只要一行程式碼即可送入畫格。`Process` 方法會回傳 `OcrResult` 物件的可列舉集合,每個物件包含對應畫格的辨識文字。 + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **底層發生了什麼?** Aspose.OCR 會先正規化每張 bitmap,接著使用神經網路辨識器,最後進行後處理以改善標點與換行。 + +## 步驟 4 – 顯示擷取的文字 + +最後,我們遍歷結果並將每行字幕印出。你也可以把它寫入 SRT 檔、資料庫,或送入翻譯服務。 + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### 完整可執行範例 + +將所有程式碼組合起來,即成為一個自包含的 console 程式: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**預期輸出(範例)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +如果 OCR 在某個畫格上無法辨識,你會看到空字串——這表示需要調整 ROI 或提升畫格擷取頻率。 + +## 常見問題與解決方式 + +| 問題 | 為什麼會發生 | 解決方法 | +|------|--------------|----------| +| **雜訊字元** | 畫格解析度低或壓縮過重 | 提高擷取畫格的位元率,或在 OCR 前將 bitmap 放大(`Bitmap.Clone(new Size(...), ...)`)。 | +| **沒有返回文字** | ROI 並未真正覆蓋字幕帶 | 檢查矩形座標(可使用截圖工具測量)。 | +| **效能瓶頸** | 以 30 fps 處理每一帧過度 | 降低至 1‑2 fps 仍能捕捉大多數字幕變化。 | +| **找不到 FFmpeg** | `ffmpeg.exe` 不在 `PATH` 中 | 在 `ProcessStartInfo.FileName` 中提供完整路徑,或全域安裝 FFmpeg。 | + +## 延伸應用 + +- **匯出為 SRT** – 把時間戳與 OCR 文字串接,寫入 SubRip 檔。 +- **多語言支援** – 設定 `ocrProcessor.Language = OcrLanguage.Spanish`(或任何支援語言)。 +- **即時處理** – 直接從直播串流傳入畫格,而非先寫入磁碟。 + +所有這些變化仍圍繞著 **extract frames from video**、**read text from video**、**extract text from mp4** 這三大核心概念。 + +## 結論 + +我們剛剛完整走過一個 **video subtitle ocr** 工作流程的每一步。透過從影片擷取畫格、將 OCR 聚焦於字幕帶,並遍歷結果,你可以可靠地 **read text from video** 檔案(如 MP4)。程式碼已可直接複製貼上,且模組化設計允許你自由替換任何畫格解碼器。 + +接下來的步驟是什麼?試著將結果匯出為 SRT 檔、調整不同的 ROI 大小,或把字幕送入翻譯 API 產生多語系字幕。掌握了從影片擷取文字的基礎後,未來的可能性無限。 + +祝開發順利,願你的字幕永遠清晰可辨! + +## 接下來該學什麼? + +以下教學與本指南緊密相關,能在此基礎上延伸技巧。每篇資源皆提供完整可執行的程式碼範例與逐步說明,協助你精通更多 API 功能,並探索在專案中實作的其他方式。 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/ocr-configuration/_index.md b/ocr/hungarian/net/ocr-configuration/_index.md index 47bb729fd..0ea0f5eaf 100644 --- a/ocr/hungarian/net/ocr-configuration/_index.md +++ b/ocr/hungarian/net/ocr-configuration/_index.md @@ -61,7 +61,9 @@ Szabadítsa fel az OCR képfelismerés erejét .NET-ben az Aspose.OCR-rel. Kény ### [OCROperation nyelvválasztással az OCR képfelismerésben](./ocr-operation-with-language-selection/) Használja ki az OCR erőteljes képességeit az Aspose.OCR for .NET-ben. Zökkenőmentesen nyerjen ki szöveget a képekből. ### [OCROperation listával az OCR képfelismerésben](./ocr-operation-with-list/) -Fedezze fel az Aspose.OCR for .NET lehetőségeit. Könnyedén végezzen OCR képfelismerést listákkal, növelje a termelékenységet és az adatkinyerést alkalmazásaiban. +Fedezze fel az Aspose.OCR for .NET lehetőségeit. Könnyedén végezzen OCR képfelismerést listákkal, növelje a termelékenységet és az adatkinyerést alkalmazásaiban. +### [Az Aspose OCR verzió lekérése C#‑ban – Teljes útmutató](./get-aspose-ocr-version-in-c-complete-guide/) +Ismerje meg, hogyan kérheti le az Aspose OCR könyvtár verziószámát C#‑ban, egyszerű kóddal. ### Gyakori felhasználási esetek - **Szöveg kinyerése** beolvasott számlákról az automatizált könyveléshez. @@ -98,4 +100,4 @@ A: Igen, az `OcrResult` objektum bizalmi értékeket biztosít, amelyeket progra {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/hungarian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..0e84ab1d9 --- /dev/null +++ b/ocr/hungarian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-03 +description: Szerezze be az Aspose OCR verzióját C#-ban egy egyszerű kódrészlettel. + Tanulja meg, hogyan lehet lekérni az Aspose OCR könyvtár verzióját az OcrEngine + GetVersion segítségével. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: hu +og_description: Szerezze be gyorsan az Aspose OCR verzióját C#-ban. Ez az útmutató + pontosan bemutatja, hogyan lehet lekérni az Aspose OCR könyvtár verzióját az OcrEngine + GetVersion segítségével. +og_title: Szerezze meg az Aspose OCR verziót C#-ban – Teljes útmutató +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Az Aspose OCR verzió beszerzése C#-ban – Teljes útmutató +url: /hu/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR verzió lekérése C#‑ban – Teljes útmutató + +Gondolkodtál már azon, hogyan **kaphatod meg az Aspose OCR verzióját** a .NET projektedből? Lehet, hogy egy verzióeltérés hibaelhárításán dolgozol, vagy egyszerűen csak szeretnéd naplózni a pontos könyvtár‑buildet, amely a termelésben fut. Bármelyik ok is legyen, a megfelelő helyen vagy. + +Ebben az útmutatóban egy kis, önálló C# programon keresztül vezetünk végig, amely meghívja az `OcrEngine.GetVersion()` metódust és kiírja az eredményt. A végére nem csak *hogyan* kell lekérni a verziót, hanem *miért* segíthet a verzió ellenőrzése a fejfájás elkerülésében az **Aspose OCR library** frissítésekor is. + +## Mit fogsz megtanulni + +- Add the Aspose.OCR NuGet csomagot egy C# projekthez +- Használd az `OcrEngine.GetVersion()` metódust (a **ocrengine getversion** belépési pont) +- Kezeld a lehetséges kivételeket és ellenőrizd a kimenetet +- Bővítsd a kódrészletet valós helyzetekhez, például naplózáshoz vagy feltételes funkciókapcsolókhoz + +Nincs szükség előzetes OCR tapasztalatra – csak egy alapvető C# és Visual Studio (vagy a kedvenc IDE-d) ismeretére. Kezdjünk bele. + +--- + +## 1. lépés: A projekt beállítása és az Aspose OCR könyvtár beszerzése + +Mielőtt bármilyen OCR‑hez kapcsolódó API‑t meghívnál, a **Aspose OCR library**-t hivatkozni kell a projektedben. + +1. Nyiss egy terminált vagy a Package Manager Console‑t a Visual Studio-ban. +2. Futtasd a következő parancsot a legújabb stabil verzió telepítéséhez: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Ha .NET Framework‑ot célozol meg a .NET Core helyett, használd a NuGet Package Manager UI‑t, és válaszd ki a futtatókörnyezetnek megfelelő verziót. A csomag tartalmazza a később használandó `OcrEngine` osztályt. + +### Miért fontos ez + +Amikor telepíted a csomagot, a lemezen lévő assembly verzió eltérhet a futás közben a könyvtár által jelentett verziótól. A verzió kódon keresztüli lekérdezése biztosítja, hogy a pontos, a CLR által betöltött buildet olvasod, ami elengedhetetlen a hibakereséshez és a megfelelőségi auditokhoz. + +--- + +## 2. lépés: Írd meg a minimális kódot az **Aspose OCR verzió lekéréséhez** + +Hozz létre egy új konzolos alkalmazást (`dotnet new console -n OcrVersionDemo`) és cseréld le az alapértelmezett `Program.cs`-t a következőre: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Az egyes részek magyarázata** + +- `using Aspose.OCR;` bevezeti az OCR névteret, lehetővé téve az `OcrEngine` hívását. +- `OcrEngine.GetVersion()` a **ocrengine getversion** statikus metódus, amely például `"24.5.7"` formátumú stringet ad vissza. +- A hívás `try/catch` blokkba helyezése megvédi a futás közbeni meglepetésektől – előfordulhat, hogy a natív binárisok nem találhatók a célgépen. +- Az interpolált string `$"Aspose OCR version: {version}"` egy tiszta, ember által olvasható sort ír ki. + +### Várható kimenet + +Amikor a projekt mappájában futtatod a `dotnet run` parancsot, valami hasonlót kell látnod: + +``` +Aspose OCR version: 24.5.7 +``` + +Ha a könyvtár nem tölthető be, a hibáág egy tömör üzenetet ad ki, ami segít gyorsan megtalálni a problémát. + +--- + +## 3. lépés: Ellenőrizd, hogy a verzió megegyezik-e a NuGet csomagoddal + +Könnyű azt feltételezni, hogy a telepített NuGet verzió az, amelyik a futás közben használva van, de a környezeti sajátosságok közbeléphetnek. A dupla ellenőrzéshez: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Ennek a kiegészítő kódrészletnek a futtatása valami ilyesmit fog kiírni: + +``` +Assembly file version: 24.5.7.0 +``` + +Ha a két érték eltér, előfordulhat, hogy egy régebbi DLL-t tölt be a Global Assembly Cache (GAC) vagy egy korábbi build mappából. Ebben az esetben tisztítsd meg a megoldást (`dotnet clean`) és építsd újra. + +--- + +## 4. lépés: Helyezd a verzió ellenőrzést a termelési naplózásba + +A legtöbb valós alkalmazás nem csak a konzolra ír; egy naplófájlba vagy telemetriai rendszerbe is ír. Íme egy gyors példa a `Microsoft.Extensions.Logging` használatával: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Most a verzió megjelenik a strukturált naplóidban, ami később egyszerűvé teszi a `{Version}` szerinti szűrést. Ez a minta különösen hasznos, ha több mikroszolgáltatásod van, amelyek mind különböző OCR DLL‑t húzhatnak be. + +## Gyakori kérdések és szélhelyzetek + +### Mi van, ha a `GetVersion()` üres stringet ad vissza? + +Ez általában sérült telepítést vagy hiányzó natív függőséget jelez. Telepítsd újra a NuGet csomagot, és ellenőrizd, hogy a `Aspose.OCR.Native.dll` (vagy a megfelelő platform‑specifikus bináris) a végrehajtható fájl mellett helyezkedik-e el. + +### Működik a metódus .NET Core 2.0‑n? + +Igen, a **Aspose OCR** támogatja a .NET Standard 2.0‑t és újabbakat, így bármely .NET Core verzió, amely ezt a szabványt implementálja, képes meghívni az `OcrEngine.GetVersion()`‑t. Csak győződj meg róla, hogy a megfelelő runtime azonosítókat (`win-x64`, `linux-x64`, stb.) hivatkozod, ha önálló alkalmazást publikálsz. + +### Lekérhetem a verziót licencfájl nélkül? + +Természetesen. A `GetVersion()` **nem** igényel licencet; egyszerűen csak a könyvtár build számát adja vissza. Azonban, ha licenc nélkül próbálsz OCR‑t végrehajtani, futásidejű kivételt kapsz. Ezért hasznos a `try/catch` a példában – elkülöníti a verzió ellenőrzést az OCR végrehajtási folyamattól. + +## Teljes működő példa (másolás‑beillesztés kész) + +Az alábbiakban a teljes program látható, amely készen áll egy új konzolos projektbe beilleszteni. Tartalmazza a opcionális naplózási blokkot is, így mind a konzol kimenetet, mind a strukturált naplókat láthatod működés közben. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Futtasd a `dotnet run` paranccsal, és két sort látsz, amelyek megerősítik a verziót, valamint egy debug sort, ha engedélyezed a `LogLevel.Debug`‑et. + +## Összegzés + +Minden szükséges információt áttekintettünk ahhoz, hogy **lekérd az Aspose OCR verziót** egy C# környezetben – a **Aspose OCR library** telepítésétől, a **ocrengine getversion** metódus meghívásáig, a hibakezelésig, egészen a verzió eredményének termelés‑szintű naplózásba ágyazásáig. Ezzel a tudással most megbízhatóan ellenőrizheted a pontos OCR buildet, amelyet az alkalmazásod használ, elkerülheted a verzióval kapcsolatos hibákat, és megfelelhetsz a megfelelőségi követelményeknek anélkül, hogy izzadnál. + +Következő lépések? Próbáld meg összekapcsolni ezt a verzió ellenőrzést egy tényleges OCR hívással (`OcrEngine` → `RecognizeImage`), és naplózd a verziót és a felismerési eredményt is. Érdemes lehet a **retrieve aspose version** mintát is felfedezni más Aspose termékeknél (PDF, Slides, Cells), hogy az egész csomag szinkronban legyen. + +Kellemes kódolást, és legyenek a OCR csővezetékek mindig élesek! + +## Mit érdemes legközelebb megtanulni? + +A következő útmutatók szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes működő kódpéldákat tartalmaz lépésről‑lépésre magyarázatokkal, hogy elsajátíthasd a további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Hogyan kapjunk OCR eredményeket az Aspose.OCR .NET-hez](/ocr/english/net/text-recognition/get-recognition-result/) +- [Képszöveg kinyerése C#‑ban nyelvválasztással az Aspose.OCR használatával](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Hogyan batch‑eljünk OCR képeket listával az Aspose.OCR .NET-ben](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/hungarian/net/ocr-optimization/_index.md index 89201a564..12bbffe21 100644 --- a/ocr/hungarian/net/ocr-optimization/_index.md +++ b/ocr/hungarian/net/ocr-optimization/_index.md @@ -74,6 +74,9 @@ Növelje az OCR pontosságát az Aspose.OCR for .NET segítségével. Javítsa a ### [Többoldalas eredmény mentése dokumentumként OCR kép felismerésben](./save-multipage-result-as-document/) Fedezze fel az Aspose.OCR for .NET lehetőségeit. Könnyedén mentse a többoldalas OCR eredményeket dokumentumokként ezzel az átfogó lépésről‑lépésre útmutatóval. +### [Aspose OCR C# példa – GPU engedélyezése, memóriahatár beállítása és TIF képek feldolgozása](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Ismerje meg, hogyan használhatja a GPU-t, állíthatja be a memória korlátot és dolgozhat fel TIF képeket az Aspose OCR C# példában. + ## Gyakran Ismételt Kérdések **Q: Can I extract text from image files that contain multiple languages?** diff --git a/ocr/hungarian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/hungarian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..1df74762a --- /dev/null +++ b/ocr/hungarian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# példa, amely bemutatja, hogyan állítható be a GPU memória + korlát, hogyan tölthető be a kép OCR-hez, és hogyan ismerhető fel a szöveg TIF fájlokból, + teljes kóddal és tippekkel. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: hu +og_description: 'Ismerjen meg egy teljes Aspose OCR C# példát: engedélyezze a GPU-t, + állítsa be a GPU memória korlátot, töltsön be egy képet OCR-hez, és ismerje fel + a szöveget TIF fájlokból. Teljes kód mellékelve.' +og_title: Aspose OCR C# példa – GPU gyorsítás, memóriakorlát és TIF feldolgozás +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# példa – GPU engedélyezése, memóriakorlát beállítása és TIF képek + feldolgozása +url: /hu/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# példa – GPU engedélyezése, memóriahatár beállítása és TIF képek feldolgozása + +Gondolkodtál már azon, hogyan hozhatod ki a legtöbb teljesítményt a **Aspose OCR C# example** kódból, amikor hatalmas TIFF szkennekkel dolgozol? Nem vagy egyedül. Sok valós projektben – gondoljunk csak az archívumok digitalizálására vagy a nagy felbontású nyugták adatkinyerésére – a szűk keresztmetszet nem maga az OCR algoritmus, hanem a hardver kihasználtsága. + +A lényeg: az Aspose OCR támogatja a GPU gyorsítást, de meg kell mondanod, mennyi memóriát használhat, be kell tölteni a megfelelő képtípust, és végül ki kell nyerni a felismert szöveget a .tif fájlból. Ez a tutorial minden lépést végigvezet, a SDK telepítésétől a GPU beállítások finomhangolásáig, hogy villámgyors OCR-t futtathass anélkül, hogy a GPU RAM-ját kifosztanád. + +Néhány „mi lenne ha” szituációt is bemutatunk – például többoldalas TIFF-ek kezelése vagy CPU-ra való visszaesés, ha nincs GPU – így egy robusztus megoldást kapsz, nem csak egy egyszeri kódrészletet. + +## Amire szükséged lesz + +Mielőtt belevágnánk, győződj meg róla, hogy a következő elemek a gépeden vannak: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6 SDK** (vagy újabb) | Az Aspose OCR a .NET Standard 2.0+ célplatformot használja, így bármely friss .NET verzió megfelelő. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | A főkönyvtár, amely biztosítja az `OcrEngine`, `GpuSettings` stb. osztályokat. | +| **CUDA 11+** (NVIDIA) **vagy ROCm 5+** (AMD) | A GPU gyorsításhoz szükséges; a SDK futásidőben ellenőrzi a kompatibilis drivert. | +| **GPU legalább 2 GB VRAM-mal** (a példában 2048 MB-ra korlátozzuk) | Elég memória nélkül a motor csendben CPU-ra vált. | +| **magas felbontású TIFF** kép, amelyet feldolgozni szeretnél | Az Aspose OCR gyakorlatilag bármilyen raszteres formátumot olvas, de a TIF gyakori a szkennelésnél. | +| Visual Studio 2022 (vagy kedvenc szerkesztőd) | A C# projekt felépítéséhez és hibakereséséhez. | + +Ha valamelyik hiányzik, a kód még mindig lefordul, de nem fogja elérni a kívánt teljesítményjavulást. + +## 1. lépés: Hozd létre az Aspose OCR C# Example Engine-et + +Az első dolog minden **Aspose OCR C# example**‑ben, hogy példányosítsuk az OCR motort. Az `OcrEngine`‑t tekintheted egy film rendezőjének – koordinálja a kép betöltésétől a szöveg kinyeréséig minden lépést. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** Ha sok képet szeretnél egymás után feldolgozni, tarts egyetlen `OcrEngine`‑t életben. Minden egyes képhez újra létrehozni jelentős overheadet okoz, ami felülmúlhatja az OCR időt. + +## 2. lépés: GPU memóriahatár beállítása (és gyorsítás engedélyezése) + +Most jön a rész, amely gyakran elakadja az embereket: **GPU memóriahatár beállítása**. Alapértelmezés szerint az Aspose OCR annyi VRAM‑ot próbál használni, amennyit csak tud, ami egy megosztott munkaállomáson más alkalmazásokat elnyelhet. A `GpuSettings` objektummal korlátozhatod a lefoglalást. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Miért érdemes memóriahatárt beállítani? + +- **Stabilitás:** Megakadályozza az out‑of‑memory összeomlásokat óriási képek feldolgozásakor. +- **Együttműködés:** Lehetővé teszi, hogy más GPU‑igényes alkalmazások (pl. TensorFlow modellek) is párhuzamosan fusson. +- **Előrejelezhetőség:** A teljesítménytesztek ismételhetők, mert a GPU nem kezd el swap‑elni. + +Ha kihagyod a `MemoryLimitMb` beállítást, az Aspose annyit fog lefoglalni, amennyit szükségesnek tart, ami egy dedikált inference szerveren rendben van, de egy fejlesztői laptopon kockázatos. + +## 3. lépés: Kép betöltése OCR-hez + +A megfelelő fájlformátum betöltése a következő kritikus lépés. Az `OcrImage.FromFile` metódus automatikusan felismeri a kép típusát, de mégis ellenőrizned kell, hogy a fájl létezik, és hogy támogatott TIFF változatról van‑e szó (pl. LZW‑tömörített vagy CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Többoldalas TIFF‑ek kezelése + +Ha a TIFF több oldalt tartalmaz, az Aspose OCR alapértelmezés szerint csak az elsőt olvassa be. Az összes oldal feldolgozásához végigiterálhatsz az `image.Pages`‑en (újabb SDK verziókban elérhető), és minden oldalt külön adsz át a motornak. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +A fenti kódrészlet egy **load image for OCR** mintát mutat, amely egy‑ és többoldalas fájlok esetén is működik. + +## 4. lépés: Szöveg felismerése TIF‑ből (vagy bármely raszteres formátumból) + +Miután a kép a memóriában van, megkérjük az Aspose‑t, hogy csinálja meg a varázslatot. A `Recognize` metódus egy `OcrResult`‑ot ad vissza, amely tartalmazza a nyers szöveget, a megbízhatósági pontszámokat, sőt akár a bounding‑box információkat is, ha szükséged van rájuk. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Miért működik ez jól TIF‑kel + +- **Veszteségmentes tömörítés:** A TIFF gyakran nyers pixel adatot tárol, ami a legmagasabb hűséget biztosítja az OCR motor számára. +- **Több színterület:** Az Aspose képes kezelni a szürkeárnyalatos, RGB vagy akár CMYK TIFF‑eket extra konverziós kód nélkül. + +Ha nyelvi csomagokat kell finomhangolnod (pl. francia vagy japán), állítsd be `ocrEngine.Settings.Language = "fr"`‑t a `Recognize` hívása előtt. + +## 5. lépés: Felismert szöveg megjelenítése + +Végül a szöveget a konzolra írjuk ki. Egy valódi alkalmazásban adatbázisba, JSON fájlba vagy egy downstream NLP pipeline‑ba is továbbíthatod a karakterláncot. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Várható kimenet + +Egy tiszta, 300 dpi felbontású nyomtatott oldal szkennelésén a program általában valami ilyesmit ad vissza: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Ha a kép elmosódott vagy a GPU memóriahatár túl alacsony, torz karaktereket vagy csonkolt eredményt láthatsz. A `MemoryLimitMb` túl alacsonyra állítása (gyakran ~1 GB egy 6000×8000 pixel TIFF‑hez) automatikusan CPU‑ra váltást eredményezhet. + +## Teljes működő példa + +Az alábbiakban a teljes, azonnal futtatható programot találod. Másold be egy új Console App projektbe, cseréld le a `YOUR_DIRECTORY/large_photo.tif`‑t a saját TIFF‑ed elérési útjára, majd nyomd meg az **F5**‑öt. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Gyors ellenőrzőlista + +- ✅ **Aspose OCR C# example** hibamentesen lefordítva. +- ✅ **GPU engedélyezve** (`Enable = true`). +- ✅ **GPU memóriahatár** 2048 MB‑ra állítva. +- ✅ **Kép betöltve** TIF fájlból. +- ✅ **Szöveg felismert** és kiírva. + +## Gyakori hibák és megoldások + +| Symptom | Likely cause | Fix | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA runtime nincs telepítve vagy verzióeltérés. | Telepítsd a CUDA 11.x (vagy 12.x) verziót, amely illeszkedik a driverhez. | +| OCR üres stringet ad vissza | A kép túl sötét vagy DPI < 150. | Előfeldolgozás `image.AdjustContrast()`‑val vagy átmintavételezés 300 dpi‑ra. | +| GPU‑n out‑of‑memory összeomlás | `MemoryLimitMb` túl alacsony a képhez képest. | Emeld a határt, vagy oszd fel a képet csempékre a `image.Crop` segítségével. | +| `Unsupported image format` hiba | A TIFF egzotikus tömörítést használ (pl. JPEG‑2000). | Konvertáld a TIFF‑et támogatott formátumba az ImageMagick‑kel OCR előtt. | + +## A demó bővítése + +Miután már van egy stabil **aspose ocr c# example**‑ed, érdemes lehet: + +- **Kötegelt feldolgozás:** Egy mappában lévő TIF‑ek bejárása, minden eredmény `.txt` fájlba írása. +- **Nyelvi csomagok:** `ocrEngine.Settings.Language = "es"` spanyolhoz, vagy egyedi szótárak betöltése. +- **Bounding box‑ok:** Használd az `ocrResult.Regions`‑t, hogy minden szó koordinátáit megkapd – hasznos például redakciós eszközökhöz. +- **CPU visszaesés:** A GPU blokkot try/catch‑ben tedd; hiba esetén állítsd `ocrEngine.Settings.Gpu.Enable = false`‑ra és próbáld újra. + +Ezek a kiegészítések megőrzik az alapminta struktúráját, miközben specifikus igényekhez adnak hozzáértéket. + +## Mit érdemes még tanulni? + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás komplett, működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy további API funkciókat saját projektjeidben is könnyedén alkalmazhass. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/hungarian/net/skew-angle-calculation/_index.md index f323290eb..5b7a560af 100644 --- a/ocr/hungarian/net/skew-angle-calculation/_index.md +++ b/ocr/hungarian/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Fedezze fel az Aspose.OCR for .NET-et, amely egy hatékony OCR-megoldás a ponto Engedje szabadjára az Aspose.OCR for .NET erejét, amely egy robusztus megoldás a képfelismeréshez. Tanulja meg a ferde szögek egyszerű kiszámítását. ### [Számítsa ki a ferde szöget az URI-ből az OCR képfelismerésben](./calculate-skew-angle-from-uri/) Fedezze fel az Aspose.OCR for .NET alkalmazást, amellyel könnyedén kiszámíthatja a ferde szögeket az OCR képfelismerésben. Fokozza projektjeit pontossággal és hatékonysággal. +### [OCR elforgatott dokumentum oktatóanyag – automatikus ferde korrekció és forgatás javítása C#-ban](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Fedezze fel, hogyan javíthatja automatikusan az elforgatott dokumentumok ferdeségét és forgását C#-ban az Aspose.OCR segítségével. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/hungarian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..e1810f64a --- /dev/null +++ b/ocr/hungarian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: OCR elforgatott dokumentum oktató, amely bemutatja, hogyan lehet automatikusan + korrigálni a dőlést és észlelni a forgást az Aspose OCR C# használatával. Tanulj + lépésről lépésre a teljes kóddal. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: hu +og_description: Az OCR forgatott dokumentumok oktatóanyaga bemutatja, hogyan lehet + automatikusan korrigálni a ferdeséget és felismerni a forgatást az Aspose OCR C#-ban + történő használatával. Kövesse a teljes útmutatót. +og_title: OCR elforgatott dokumentum útmutató – Automatikus ferde korrekció és forgatás + javítása C#-ban +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR elforgatott dokumentum útmutató – Automatikus ferde korrekció és forgatás + javítása C#-ban +url: /hu/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR elforgatott dokumentum oktató – Teljes útmutató C# fejlesztőknek + +Valaha is belefutottál egy **ocr rotated document tutorial**-ra, amikor egy beolvasott űrlap oldalra állítva vagy ferde érkezett? Nem vagy egyedül. Az ilyen görnyedt képek tönkretehetik a tiszta szövegkinyerést, de a jó hír, hogy az Aspose OCR automatikusan kiegyenesíti őket. + +Ebben a lépésről‑lépésre útmutatóban elindítunk egy `OcrEngine`-t, bekapcsoljuk a **automatic skew correction**‑t és a **auto detect rotation**‑t, futtatjuk a motort egy elforgatott képen, és kiírjuk a tiszta szöveget. A végére pontosan tudni fogod, miért fontos minden beállítás, hogyan állíthatod őket speciális esetekhez, és lesz egy azonnal futtatható C# programod. + +## Mit fogsz megtanulni + +* Hogyan telepítsd és hivatkozd a **Aspose OCR**-t egy .NET projektben. +* Miért kulcsfontosságú a `AutoCorrectSkew` és `AutoDetectRotation` engedélyezése egy megbízható **ocr rotated document tutorial**-hoz. +* Hogyan tölts be bármilyen képet (JPG, PNG, TIFF), és hagyd, hogy a motor elvégezze a nehéz munkát. +* Tippek a többoldalas PDF-ek, alacsony felbontású beolvasások és egyedi nyelvi csomagok kezeléséhez. + +> **Előfeltételek:** Visual Studio 2022 (vagy bármely C# IDE), .NET 6+ futtatókörnyezet, és egy érvényes Aspose OCR licenc (vagy az ingyenes próba). Előző OCR tapasztalat nem szükséges. + +--- + +## 1. lépés – Aspose OCR telepítése és a projekt beállítása + +Először is. Szerezd be a NuGet csomagot: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tipp:** Ha próba licencet használsz, helyezd a `Aspose.OCR.lic` fájlt ugyanabba a mappába, ahol a végrehajtható állományod van, vagy regisztráld programozottan a `License license = new License(); license.SetLicense("Aspose.OCR.lic");` kóddal. + +Hozz létre egy új konzolos alkalmazást: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Most már tiszta kiindulási pontod van a **ocr rotated document tutorial**-hoz. + +## 2. lépés – Az OCR motor inicializálása + +A motor a folyamat szíve. Gondolj rá úgy, mint egy svájci bicskára a szövegkinyeréshez; csak meg kell mondanod, mely trükköket engedélyezze. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Miért ezek a beállítások?** +* `AutoCorrectSkew` elemzi a karakterek alapvonalát, és annyira elforgatja a képet, hogy a sorok vízszintessé váljanak. +* `AutoDetectRotation` megvizsgálja az általános tájolást (0°, 90°, 180°, 270°), és megfordítja az oldalt, ha fejjel lefelé van. Nélkül a motor a “pɹᴉʍ” szöveget olvasná a “word” helyett. + +## 3. lépés – A feldolgozni kívánt kép betöltése + +Az Aspose OCR bármely általános raszteres formátummal működik. Cseréld ki a helyőrző útvonalat a elforgatott űrlapod tényleges helyére. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Különleges eset:** Ha többoldalas TIFF-et kapsz, használd a `OcrImage.FromMultiPageTiff(filePath)`-t, és iterálj a `image.Pages`-en. + +## 4. lépés – A felismerés futtatása + +Most a motor varázsol. Először kiegyenesíti a képet (köszönhetően a skew/rotation jelzőinknek), majd kihúzza a karaktereket. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Ha az angol nyelven kívül más nyelvi támogatásra van szükséged, állítsd be a `Recognize` hívása előtt: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## 5. lépés – A felismert szöveg kiírása + +Végül írd ki a tiszta szöveget a konzolra – vagy irányítsd egy fájlba, adatbázisba, bármi, ami a munkafolyamatodba illik. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Várható kimenet** (feltételezve, hogy a minta kép a “Invoice #1234” szöveget tartalmazza): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Vedd észre, hogy a szöveg helyesen jelenik meg, annak ellenére, hogy a forráskép 90°-kal el volt forgatva és kissé ferde volt. + +--- + +## Gyakori buktatók kezelése + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Üres kimenet** | A ferdeségkorrekció le van tiltva vagy a kép túl sötét. | `AutoCorrectSkew` engedélyezése (már be van kapcsolva) és a kép kontrasztjának növelése a `image.AdjustContrast(1.2)` segítségével. | +| **Hibás karakterek** | Helytelen nyelvi beállítás. | `ocrEngine.Settings.Language` beállítása a dokumentum nyelvének megfelelően. | +| **Teljesítménycsökkenés nagy PDF-eknél** | A motor minden oldalt sorban dolgoz fel. | Használd a `Parallel.ForEach`-t az `image.Pages`-en a többmagos CPU-k kihasználásához. | +| **Licenc kivétel** | A próbaidő lejárt. | Szerezz be egy állandó licencet, vagy tartsd be a próba korlátait (5 oldal futásonként). | + +--- + +## Profi tippek egy robusztus OCR elforgatott dokumentum oktatóhoz + +* **Kötegelt feldolgozás:** Csomagold az egész folyamatot egy metódusba, amely mappát fogad, végigiterál minden képen, és az eredményt egy `.txt` fájlba írja. +* **Előfeldolgozás:** Néha egy zajos beolvasás előnyös a `image.Denoise()` használata a felismerés előtt. +* **Utófeldolgozás:** Használj reguláris kifejezéseket a gyakori OCR hibák tisztításához, pl. cseréld a “0” karaktert “O”‑ra csak akkor, ha betűk között van. +* **Naplózás:** Az Aspose OCR biztosítja a `ocrEngine.Logger`‑t – csatlakoztasd egy fájl naplózóhoz, hogy rögzítsd az alacsony bizalmi pontszámú figyelmeztetéseket. + +--- + +## Teljes, azonnal futtatható kód + +Mentsd el a következőt `Program.cs` néven a konzolos projektedben. Tartalmazza az összes lépést, megjegyzéseket, és egy kis segédeszközt a kötegelt feldolgozáshoz. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Futtasd: + +```bash +dotnet run +``` + +A konzolon meg kell jelennie a megtisztított szövegnek, bizonyítva, hogy a **ocr rotated document tutorial** végponttól végpontig működik. + +--- + +## Következtetés + +Most már van egy teljes **ocr rotated document tutorial**-od, amely automatikusan korrigálja a ferdeséget, felismeri a tájolást, és tiszta szöveget nyer ki az Aspose OCR használatával C#-ban. A fő tanulság? A `AutoCorrectSkew` **és** `AutoDetectRotation` engedélyezése egy reménytelenül ferde beolvasást tökéletesen olvasható kimenetté alakít néhány kódsorral. + +Innen tovább bővítheted kötegelt feladatokra, integrálhatod a nyelvi csomagokat, vagy betáplálhatod az eredményeket a downstream analitikai csővezetékekbe. Szeretnél mélyebben belemenni a **automatic skew correction**-be? Nézd meg az Aspose képelőfeldolgozó API-ját, vagy kísérletezz egyedi küszöbértékekkel a zajos beolvasásokhoz. + +Van kérdésed a PDF-ek, többoldalas TIFF-ek kezelése vagy az Azure Functions integrálása kapcsán? Írj egy megjegyzést, és jó kódolást! + +--- + +## Mit érdemes következőként megtanulni? + +A következő oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljes működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [ocr dokumentum mód – Területek detektálása mód az OCR képfelismerésben](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Kép szövegének kinyerése C#-ban nyelvválasztással az Aspose.OCR használatával](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR oktató – Optikai karakterfelismerés](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/hungarian/net/text-recognition/_index.md index 61ddd9f74..cb46a433f 100644 --- a/ocr/hungarian/net/text-recognition/_index.md +++ b/ocr/hungarian/net/text-recognition/_index.md @@ -55,9 +55,20 @@ Bővítse .NET-alkalmazásait az Aspose.OCR segítségével a hatékony képszö Az Aspose.OCR segítségével tárja fel az OCR-ben rejlő lehetőségeket a .NET-ben. Könnyedén bontsa ki a szöveget a PDF-ekből. Töltse le most a zökkenőmentes integrációs élményért. ### [Táblázat felismerése az OCR képfelismerésben](./recognize-table/) A .NET-hez készült Aspose.OCR-ben rejlő lehetőségeket az OCR-képfelismerés tábláinak felismeréséről szóló átfogó útmutatónkkal tárja fel. +### [OCR végrehajtása képen az Aspose OCR segítségével – Hindi útmutató](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Ismerje meg, hogyan végezhet OCR-t képeken az Aspose OCR .NET használatával, Hindi nyelvű útmutatóval. +### [PDF-en OCR végrehajtása az Aspose.OCR segítségével – Teljes C# útmutató](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Ismerje meg, hogyan végezhet teljes körű OCR-t PDF-fájlokon az Aspose.OCR .NET használatával C# nyelven. +### [Az Aspose használata: Kép konvertálása HTML-re OCR-rel](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Ismerje meg, hogyan konvertálhat képeket HTML formátumba az Aspose OCR segítségével .NET környezetben. +### [OCR végrehajtása képen és helyesírási hibák felismerése C#-ban](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Ismerje meg, hogyan végezhet OCR-t képeken és azonosíthatja a helytelenül írt szavakat C#-ban az Aspose.OCR segítségével. +### [Videó felirat OCR C#-ban – Teljes útmutató](./video-subtitle-ocr-in-c-complete-guide/) +Ismerje meg, hogyan végezhet OCR-t videó feliratokon C#-ban az Aspose.OCR segítségével, lépésről-lépésre útmutatóval. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/hungarian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..f84d4e6a7 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-03 +description: Hogyan használjuk az Aspose-t képek HTML-re konvertálásához és szöveg + kinyeréséhez a képből C#-ban. Tanulja meg gyorsan HTML-t generálni a képből, és + OCR-rel képet HTML-re konvertálni. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: hu +og_description: Hogyan használjuk az Aspose-t képek HTML-re konvertálásához, szöveg + kinyeréséhez a képből, és OCR-rel HTML generálásához C#-ban. Kövesse ezt a teljes + útmutatót. +og_title: 'Hogyan használjuk az Aspose-ot: Kép konvertálása HTML-re OCR-rel' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Hogyan használjuk az Aspose-t: Kép konvertálása HTML-re OCR-rel' +url: /hu/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan használjuk az Aspose: Kép konvertálása HTML-re OCR-rel + +Valaha is elgondolkodtál már azon, **hogyan használjuk az Aspose‑t**, hogy egy beolvasott képet rendezett HTML‑re alakítsunk? Lehet, hogy egy magazinoldalad, egy nyugta vagy egy kézzel írott jegyzeted van, és a szöveget és az elrendezést meg kell őrizni a webes közzétételhez. A jó hír, hogy nem kell saját elemzőt írnod vagy alacsony szintű képfeldolgozással bajlódnod – az Aspose.OCR elvégzi a nehéz munkát helyetted. + +Ebben az oktatóanyagban egy **teljes, futtatható példán** keresztül mutatjuk be, hogyan **konvertáljunk képet HTML‑re**, **nyerjünk ki szöveget a képből**, és **generáljunk HTML‑t a képből** az Aspose OCR könyvtár C#‑ban történő használatával. A végére egy kis konzolalkalmazásod lesz, amely egy HTML‑fájlt hoz létre az eredeti oldal elrendezésével, készen állva bármely weboldalba való beillesztésre. + +## Előkövetelmények + +Mielőtt belevágnánk, győződj meg róla, hogy a következők telepítve vannak a gépeden: + +- **.NET 6.0 SDK** vagy újabb (a kód .NET Core‑val és .NET Framework‑kel egyaránt működik). +- **Visual Studio 2022** (vagy bármelyik kedvenc szerkesztő). +- **Aspose.OCR for .NET** – telepítsd a NuGet‑en keresztül: `dotnet add package Aspose.OCR`. +- Egy kép fájl (JPEG/PNG), amelyet konvertálni szeretnél, például `magazine_page.jpg`. + +Nem szükséges extra konfigurációs fájl; a könyvtár mindent magában hordoz az OCR‑hez és a HTML‑elrendezés generálásához. + +## 1. lépés: Projekt létrehozása és az Aspose.OCR hozzáadása + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Hasznos tipp:** Ha a Visual Studio‑t használod, egyszerűen jobb‑klikkelj a projektre → *Manage NuGet Packages* → keresd meg a **Aspose.OCR**‑t és telepítsd. Ez a lépés biztosítja, hogy **ocr image to html** nélkül hiányzó hivatkozások legyenek. + +## 2. lépés: OCR motor inicializálása + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Itt példányosítjuk az `OcrEngine`‑t. A ingyenes verzióhoz nem kell hitelesítő adatot megadni; a könyvtár a beépített felismerési modelleket használja. + +## 3. lépés: Forráskép betöltése + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Cseréld le a `YOUR_DIRECTORY`‑t arra az abszolút vagy relatív útvonalra, ahol a képed található. Ha a kép ugyanabban a mappában van, mint a futtatható állomány, egyszerűen használhatod a `"magazine_page.jpg"`‑t. + +## 4. lépés: Felismerés és HTML kérése elrendezéssel + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +A `recognitionResult.Text` tulajdonság most már egy teljes HTML‑dokumentumot tartalmaz. Ha csak egyszerű szöveget szeretnél, használhatod az `OutputFormat.Text`‑et, de most a **convert image to html** elrendezés‑hűséggel történő generálására fókuszálunk. + +## 5. lépés: HTML fájl mentése + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +A program futtatása `magazine.html`‑t hoz létre. Nyisd meg, és láthatod, hogy az eredeti oldal szövege pontosan úgy helyezkedik el, ahogyan a forrásképen megjelent – tökéletes archiváláshoz vagy webes közzétételhez. + +## Teljes működő példa + +Az alábbi **komplett, másolás‑beillesztés‑kész** program. Semmi nincs kihagyva, így a helyes útvonalak beállítása után azonnal lefordíthatod és futtathatod. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Várható kimenet + +Amikor a `magazine.html`‑t megnyitod egy böngészőben, valami ehhez hasonlót kell látnod (az illusztráció egyszerűsített): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +A pontos `style` attribútumok az eredeti képtől fognak eltérni, de a struktúra garantálja, hogy a **extract text from image** és a **generate html from image** egyetlen, zökkenőmentes lépésben történjen. + +## Gyakori kérdések és szélhelyzetek + +### Mi van, ha a kép alacsony felbontású? + +Az Aspose.OCR a legjobban olyan képekkel működik, amelyek legalább **300 DPI**‑vel rendelkeznek. Ha a fájl elmosódott, próbáld meg előfeldolgozni egy kép‑javító könyvtárral (pl. ImageSharp), mielőtt az OCR‑motorba adod. Az alacsony minőség befolyásolhatja mind a **extract text from image** pontosságát, mind a generált HTML‑elrendezés hűségét. + +### Azt befolyásolhatom, hogy milyen nyelven történjen az OCR? + +Igen. Állítsd be a `Language` tulajdonságot az `OcrEngine`‑en, mielőtt meghívod a `Recognize`‑t: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Ez javítja a felismerést, ha nem‑angol karakterekkel dolgozol. + +### Hogyan kapok egyszerű szöveget HTML helyett? + +Ha csak a nyers karakterláncra van szükséged, cseréld le az `OutputFormat.HtmlWithLayout`‑t `OutputFormat.Text`‑re. Ebben az esetben a `recognitionResult.Text` csak a kinyert karaktereket tartalmazza. + +### Van mód arra, hogy a generált HTML‑be beágyazzuk a képeket? + +Az Aspose.OCR képes az eredeti képet base‑64 adat‑URI‑ként beágyazni, ha az `OutputFormat.HtmlWithLayoutAndImages`‑t használod. Ez akkor hasznos, ha egyetlen HTML‑fájlt szeretnél külső erőforrások nélkül. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Hogyan kezeljünk nagy kötegelt feldolgozást? + +Kötegelt feldolgozáshoz tedd a logikát egy `foreach` ciklusba, amely egy fájlútvonal‑listán iterál. Az ugyanazon `OcrEngine` példány újrahasználata csökkenti a terhelést és felgyorsítja a **convert image to html** folyamatot. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tippek a termelés‑kész kódhoz + +- **Erőforrások felszabadítása**: Mind az `OcrEngine`, mind az `OcrImage` implementálja az `IDisposable`‑t. Tedd őket `using` blokkokba a natív memória azonnali felszabadításához. +- **Hibakezelés**: Fogd el az `IOException`‑t fájl‑kapcsolatos problémákra és az `OcrException`‑t a felismerési hibákra. +- **Teljesítmény**: Ha sok képet dolgozol fel, fontold meg a **párhuzamosság** engedélyezését (`Parallel.ForEach`), de figyelj a CPU‑használatra – az OCR CPU‑igényes. +- **Naplózás**: Integrálj egy naplózót (pl. Serilog), hogy rögzítsd az OCR bizalmi pontszámokat (`recognitionResult.Confidence`) a minőségfigyeléshez. + +## Összegzés + +Most már tudod, **hogyan használjuk az Aspose‑t** a **convert image to HTML**, **extract text from image**, és **generate HTML from image** feladatok elvégzéséhez néhány egyszerű lépésben. A teljes kódminta megmutatja, hogyan **ocr image to html** a layout megőrzésével, így erős alapot nyújt bármely dokumentum‑digitalizációs projekthez. + +Innen tovább: + +- Kísérletezz különböző `OutputFormat` opciókkal, hogy megfeleljenek az igényeidnek. +- Kombináld a HTML kimenetet egy CSS keretrendszerrel a reszponzív stílushoz. +- Tedd a kinyert szöveget keresőindexbe vagy gépi‑tanulási folyamatba. + +Próbáld ki, finomítsd a beállításokat, és nézd meg, milyen könnyedén alakítja át az Aspose a képeket web‑kész tartalommá. Ha elakadsz, írj egy megjegyzést – jó programozást! + +![Diagram, amely bemutatja az OCR csővezetékét a képről HTML elrendezésre – hogyan használjuk az Aspose‑t](/images/ocr-pipeline.png "hogyan használjuk az aspose") + +--- + + +## Mit érdemes még megtanulni? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódpéldákat lépés‑ről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API‑funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Kép szövegének kinyerése C#‑ban nyelvválasztással az Aspose.OCR használatával](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Kép konvertálása szöveggé – OCR végrehajtása URL‑ről származó képen](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/hungarian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..6c3bfd343 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,245 @@ +--- +category: general +date: 2026-06-03 +description: Kép OCR feldolgozása és a szöveg kinyerése a képről az Aspose.OCR segítségével. + Tanulja meg, hogyan lehet felismerni a helytelenül írt szavakat, és hogyan kap helyesírási + javaslatokat egyetlen C# demóban. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: hu +og_description: Képen OCR-t hajtson végre a szöveg kinyeréséhez, majd azonosítsa a + helytelenül írt szavakat és adjon helyesírási javaslatokat az Aspose.OCR segítségével + C#-ban. +og_title: Képen OCR végrehajtása és helyesírási hibák észlelése C#-ban +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Kép OCR-vel történő feldolgozása és helytelen szavak felismerése C#-ban +url: /hu/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kép OCR végrehajtása és helyesírási hibák észlelése C#-ban + +Gondolkodtál már azon, hogyan **perform OCR on image** fájlokon anélkül, hogy a hajadba ragadnál? Nem vagy egyedül. Akár régi leveleket digitalizálsz, számlákat szkennelsz, vagy egy intelligens dokumentumfolyamot építesz, a képekből tiszta szöveget kinyerni az első akadály. A jó hír? Az Aspose.OCR segítségével percek alatt felállíthatsz egy megoldást, és ráadásul **detect misspelled words** és **get spelling suggestions** is elvégezhető egy futtatásban. + +Ebben a tutorialban végigvezetünk egy teljes, kész‑futásra alkalmas C# konzolalkalmazáson, amely **extracts text from image**, futtat egy angol helyesírás-ellenőrzőt, és minden hibát kényelmes javítási ötletekkel nyomtat ki. A végére pontosan tudni fogod, **how to extract text**, hogyan kell csatlakoztatni a spell‑check API‑t, és milyen lesz a várt konzol kimenet. + +## What You’ll Build + +- Betöltesz egy bitmapet (vagy PNG‑t), amely tipográfiai hibákat tartalmaz. +- Az Aspose.OCR‑t használod **perform OCR on image** és nyers karakterlánc adatot kapsz. +- Inicializálod a beépített angol spell‑checkert. +- **Detect misspelled words** és **get spelling suggestions** minden egyes szóhoz. +- Szép jelentést nyomsz a konzolra. + +Nincs külső szolgáltatás, nincs bonyolult HTTP hívás — csak egy NuGet csomag és néhány kódsor. + +## Prerequisites + +- .NET 6.0 SDK vagy újabb (a kód .NET Framework 4.7+‑on is működik). +- Visual Studio 2022 (vagy bármely kedvenc szerkesztő). +- Aspose.OCR for .NET NuGet csomag (`Aspose.OCR`). +- Egy képfájl (`letter_with_typos.png`), amelyet a projektből elérhetsz. + +Ha még soha nem használtad az Aspose‑t, ne aggódj — a csomag telepítése olyan egyszerű, mint a következő parancs futtatása: + +```bash +dotnet add package Aspose.OCR +``` + +Most merüljünk el a megvalósításban. + +## Step 1: Set Up the Project and Install Aspose.OCR + +Hozz létre egy új konzolprojektet, és húzd be az OCR könyvtárat: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +A visszaállítás befejeződése után nyisd meg a `Program.cs`‑t. Később a teljes demó kóddal fogjuk felülírni az alapértelmezett tartalmat, de először beszéljünk arról, miért fontos minden névtér. + +- `Aspose.OCR` – A core OCR motor és képfeldolgozás. +- `Aspose.OCR.SpellCheck` – A könyvtárral szálló helyesírás-ellenőrző segédprogramok. +- `System` – Standard .NET alaposztályok (pl. `Console`). + +## Step 2: Load the Image and Perform OCR on Image + +Az első igazi feladat a kép betáplálása az OCR motorba. Az Aspose.OCR sok formátumot olvas (PNG, JPEG, TIFF). Íme a részlet, amely a nehéz munkát elvégzi: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Why this matters:** Az `OcrImage.FromFile` elrejti a pixel‑szintű részleteket, míg az `OcrEngine.Recognize` lefuttatja a betanított neurális modellt, amely a vizuális glifeket Unicode karakterekké alakítja. Az `ocrResult.Text` tulajdonság most már a nyers karakterláncot tartalmazza — pontosan azt, amire **extract text from image**‑hez szükséged van. + +> **Pro tip:** Ha a képed több nyelvet tartalmaz, a `ocrEngine.Language = OcrLanguage.Multilingual;` beállítással a `Recognize` hívás előtt többnyelvű módba kapcsolhatsz. + +## Step 3: Initialise the English Spell‑Checker + +Az Aspose.OCR egy beépített spell‑checking motort szállít, amely alapból érti az angolt. Az inicializálása egyetlen sorban megoldható: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Why this step is crucial:** Az OCR kimenet tartalmazhat félreolvasott karaktereket (pl. „l” vs „1”) vagy valódi elütéseket a forrásdokumentumból. A spell‑checker átvizsgálja a szöveget, megtalálja a gyanús tokeneket, és alternatívákat javasol. + +## Step 4: Detect Misspelled Words and Get Spelling Suggestions + +Most a OCR szöveget adjuk át a checkernek: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +A `misspellings` egy gyűjtemény, ahol minden elem a hibás szót és egy lehetséges javítások tömbjét tartalmazza. + +## Step 5: Output the Results + +Végül végigiterálunk a gyűjteményen, és emberi olvasásra alkalmas jelentést nyomtatunk: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Expected Console Output + +Tegyük fel, hogy a `letter_with_typos.png` a következő mondatot tartalmazza: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +A demo futtatása valami ilyesmit eredményez: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Figyeld meg, hogy minden elütéshez néhány reális javítás párosul — pontosan azt, amire egy felhasználóbarát korrigáló UI‑ban szükséged van. + +## Full Working Example + +Alább a **complete, copy‑paste‑ready** program. Cseréld le a `YOUR_DIRECTORY`‑t a képfájlod tényleges elérési útjára. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Edge Cases to Consider** +> - **Empty Image:** Ha az OCR motor üres karakterláncot ad vissza, a `spellChecker.Check` egyszerűen egy üres gyűjteményt ad vissza — nem omlik össze. +> - **Non‑English Text:** Cseréld le az `OcrLanguage.English`‑t `OcrLanguage.French`‑ra (vagy bármely támogatott nyelvre), hogy **detect misspelled words** más nyelveken is. +> - **Large Documents:** Többoldalas PDF‑ek esetén minden oldalt külön kell feldolgozni, OCR‑t futtatni, majd az eredményeket aggregálni a spell‑check előtt. + +## Visual Overview (Image Alt Text) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*A fenti diagram bemutatja a vég‑től‑végig folyamatot: kép → OCR motor → nyers szöveg → spell‑checker → javaslatok.* + +## Common Questions & Pro Tips + +| Question | Answer | +|----------|--------| +| **Do I need an internet connection?** | No. Aspose.OCR runs entirely locally; perfect for offline or secure environments. | +| **How accurate is the spell‑checker?** | It uses a dictionary of ~150k English words and fuzzy matching, so most common typos are caught. | +| **Can I customize the dictionary?** | Yes. `SpellChecker.AddUserDictionary("custom.txt")` lets you load domain‑specific terms (e.g., product names). | +| **What if the image is skewed?** | The OCR engine auto‑detects orientation, but you can manually call `ocrEngine.ImagePreprocessing.Rotate(angle)` for stubborn cases. | +| **Is there a way to highlight suggestions in UI?** | After you have the `misspellings` collection, you can map each `entry.Word` back to its position in `ocrResult.Text` and underline it in a RichTextBox or web view. | + +## Conclusion + +Most már tudod, **how to perform OCR on image**, **extract text from image**, majd **detect misspelled words** és **get spelling suggestions** — mindezt egy tömör C# konzolalkalmazással. A lényeg egyszerű: hagyd, hogy az Aspose.OCR végezze a karakterfelismerést, majd a beépített spell‑checker tisztítsa meg a kimenetet. Innen továbbfejlesztheted a demót egy teljes dokumentumfeldolgozó szolgáltatássá, integrálhatod egy web API‑ba, vagy egy asztali szerkesztőbe ágyazhatod. + +Készen állsz a következő lépésre? Próbáld ki a nyelvet spanyolra állítani, tölts be egy többoldalas PDF‑et, vagy építs egy kis WPF front‑endet, amely lehetővé teszi a felhasználónak, hogy egy szóra kattintva elfogadja a javaslatot. Az építőkövek már megvannak — csak folytasd a kísérletezést. + +Ha bármilyen problémába ütköztél, vagy ötleteid vannak a kiterjesztésre, hagyj egy megjegyzést alább. Boldog kódolást! + + +## What Should You Learn Next? + + +A következő tutorialok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljesen működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API‑funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/hungarian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..feffa59b8 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Kép OCR-feldolgozása Aspose OCR használatával C#-ban. Tanulja meg, hogyan + töltsön be képet OCR-hez, és offline módon lépésről lépésre kóddal vonja ki a hindi + szöveget. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: hu +og_description: Végezz OCR-t képen az Aspose OCR-rel C#-ban. Ez az útmutató bemutatja, + hogyan töltsünk be képet OCR-hez, és hogyan vonjunk ki offline hindi szöveget a + képről, teljesen futtatható kóddal. +og_title: OCR végrehajtása képen – Aspose OCR Hindi útmutató +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Kép OCR-olása az Aspose OCR segítségével – Hindi útmutató +url: /hu/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR végrehajtása képen az Aspose OCR-rel – Hindi útmutató + +Valaha szükséged volt **OCR végrehajtására képen** fájlokon, de elakadtál a hindi karakterek kinyerésében? Nem vagy egyedül – sok fejlesztő szembesül ezzel, amikor először próbál meg nem latin írásrendszereket olvasni. A jó hír, hogy az Aspose OCR ezt meglehetősen egyszerűvé teszi, ráadásul teljesen offline is használható. + +Ebben az útmutatóban **betöltjük a képet OCR-hez**, beállítjuk a motorra az offline nyelvi csomagokat, és végül **kinyerjük a hindi szöveget a képről** anélkül, hogy az internetet használnánk. A végére egy kész, futtatható C# konzolalkalmazást kapsz, amely beolvassa a hindi nyugtát és kiírja a szöveget a konzolra. + +## What You’ll Need + +- **.NET 6.0** vagy újabb (a kód .NET Framework 4.7+ esetén is működik) +- **Aspose.OCR for .NET** NuGet csomag + `dotnet add package Aspose.OCR` +- Egy mappa, amely tartalmazza az **offline hindi nyelvi erőforrásokat** (letölthető az Aspose portáljáról) +- Egy képfájl hindi szöveggel, például `receipt_hindi.png` + +Ennyi—nincs külső szolgáltatás, nincs API kulcs, csak egyszerű kód. + +## Perform OCR on Image – Step‑by‑Step Implementation + +Az alábbiakban a folyamatot hét egyértelmű lépésre bontjuk. Minden lépést **miért** fontos, nem csak **mit** kell beírni, magyarázattal látunk el. + +### Step 1: Create the OCR Engine Instance + +A motor az Aspose OCR szíve. Példányosítva hozzáférést kapsz minden beállításhoz, amelyet később módosíthatsz. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Miért?** +> `OcrEngine` nélkül nincs objektum, amelyen a `Recognize` hívható. Gondolj rá úgy, mint egy “kamerára”, amely később beolvassa a képedet. + +### Step 2: Point the Engine to Offline Resources + +Az Aspose nyelvi csomagokat szállít, amelyeket helyben tárolhatsz. A `ResourcesFolder` beállítása megmondja a motornak, hol keresse őket. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tipp:** +> Fejlesztés során használj abszolút útvonalat, majd a termeléshez válts relatív útvonalra vagy konfigurációs beállításra. + +### Step 3: Force Offline Mode + +Elgondolkodtál már azon, hogy “Valóban le kell tiltani az online keresést?” +Ha tűzfal mögött dolgozol, vagy determinisztikus eredményeket szeretnél, állítsd a `UseOfflineResources` értékét **true**‑ra. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tipp:** +> Ha ezt a jelzőt **false**‑ra hagyod, a motor további adatokat tölthet le, ami késleltetést okoz és esetleg megsértheti a biztonsági szabályzatokat. + +### Step 4: Select Hindi as the Recognition Language + +Itt **kinyerjük a hindi szöveget a képről**, a motor számára megadva, hogy melyik nyelvet várja. Ez drámaian javítja a pontosságot. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Miért segít:** +> Az OCR motorok nyelvspecifikus karaktermodelleket használnak. Ha a nyelvet hindi‑re rögzíted, elkerülöd, hogy a motor tucatnyi írásrendszer között tippeljen. + +### Step 5: Load Image for OCR + +Most ténylegesen **betöltjük a képet OCR-hez**. Az `OcrImage.FromFile` metódus beolvassa a bitmapet olyan formátumba, amelyet a motor ért. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Gyakori buktató:** +> Windows alatt a perjel (`/`) használata működik, de a `Path.Combine` használata platform‑függetlenné teszi a kódot. + +### Step 6: Run the Recognition + +Minden beállítva, végül **OCR-t hajtunk végre a képen** a `Recognize` meghívásával. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Mi történik?** +> A motor minden pixelt átvizsgál, a mintákat a hindi glif adatbázissal hasonlítja össze, és Unicode karakterekből álló sztringet épít. + +### Step 7: Output the Recognized Text + +Az eredményobjektum `Text` tulajdonsága tartalmazza a kinyert szöveget. Egyszerűen kiírjuk a konzolra. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Várható kimenet:** +> Ha a `receipt_hindi.png` tartalmazza a “भुगतान सफल” szöveget, a konzol pontosan ezt a sort fogja kiírni, a diakritikus jeleket megőrizve. + +## Load Image for OCR – Preparing the Resource + +Ha azon gondolkodsz, hogy a motorba fájl helyett streamet is be lehet-e adni, a válasz igen. Cseréld le az `OcrImage.FromFile`-t a következőre: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Miért használj streamet?** +> A streamek lehetővé teszik képek adatbázisokból, felhő‑blobokból vagy beágyazott erőforrásokból történő feldolgozását – tökéletes skálázható szolgáltatásokhoz. + +## Extract Hindi Text Image – Handling Edge Cases + +1. **Hiányzó nyelvi csomag** – Ha a hindi csomag nem található, a `Recognize` kivételt dob. Tedd a hívást try/catch‑be, és naplózz egy barátságos üzenetet. +2. **Alacsony felbontású képek** – Az OCR pontossága 300 dpi alá csökken. A betöltés előtt előfeldolgozd a képet (átméretezés, élesítés). +3. **Vegyes nyelvű dokumentumok** – Több nyelvet is engedélyezhetsz: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Ezek a finomhangolások biztosítják, hogy a **OCR végrehajtása képen** rutinod robusztus maradjon a termelésben. + +## Running the Full Example + +Mentsd el a következő fájlt `Program.cs` néven, cseréld ki a helyőrző útvonalakat, majd futtasd: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Amikor a `dotnet run` parancsot végrehajtod, valami ilyesmit kell látnod: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Ha üres stringet kapsz, ellenőrizd újra, hogy a **ResourcesFolder** a `Hindi.traineddata`‑t tartalmazó mappára mutat-e, és hogy a kép elég tiszta‑e. + +## Conclusion + +Átbeszéltük, hogyan **OCR-t hajtsunk végre képen** az Aspose OCR segítségével, a **kép betöltését OCR-hez**ől a **hindi szöveg kinyeréséig** egy teljesen offline környezetben. A fenti, futtatható kód szilárd alapot nyújt, a streamekkel, hibakezeléssel és többnyelvű támogatással kapcsolatos tippek pedig segítenek a megoldás valós projektekbe való beépítésében. + +Készen állsz a következő lépésre? Próbáld meg a nyelvet **OcrLanguage.Tamil**‑re állítani, vagy képeket betáplálni egy Azure Blob tárolóból. Kísérletezhetsz az `ImagePreprocessing` beállításokkal is, hogy javítsd a pontosságot a zajos nyugták esetén. + +Van kérdésed vagy elakadtál? Írj egy megjegyzést – jó kódolást! + +![Perform OCR on image example + + +## What Should You Learn Next? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódrészleteket lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Képszöveg kinyerése C#-ban nyelvválasztással az Aspose.OCR használatával](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Képszöveg felismerése több nyelven az Aspose OCR-rel](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Képről szöveg kinyerése – OCR optimalizálás Aspose.OCR for .NET használatával](/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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/hungarian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..88fe02d6a --- /dev/null +++ b/ocr/hungarian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-06-03 +description: Végezzen OCR-t PDF-en, és konvertálja a beolvasott PDF-et kereshető PDF-re + az Aspose.OCR segítségével. Tanulja meg, hogyan ismerje fel a szöveget PDF-ből, + és hogyan hozzon létre kereshető PDF-eket percek alatt. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: hu +og_description: Végezzen OCR-t PDF-en, és azonnal hozzon létre kereshető PDF-et. Ez + az útmutató lépésről lépésre bemutatja, hogyan ismerje fel a szöveget PDF-ből az + Aspose.OCR használatával. +og_title: OCR végrehajtása PDF-en – Teljes C# útmutató +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: OCR végrehajtása PDF-en az Aspose.OCR-rel – Teljes C# útmutató +url: /hu/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR végrehajtása PDF-en az Aspose.OCR-rel – Teljes C# útmutató + +Gondolkodtál már azon, **hogyan lehet OCR-t végrehajtani PDF** fájlokon anélkül, hogy tucatnyi parancssori eszközzel küzdenél? Nem vagy egyedül. Legyen szó számlák digitalizálásáról, régi jelentések archiválásáról, vagy egyszerűen csak egy kereshető változatról egy beolvasott szerződésről, egy statikus PDF-et olyan formátummá alakítani, amelyben ténylegesen kereshetsz, igazi áttörés. + +Ebben az útmutatóban végigvezetünk a **kereshető PDF** fájlok létrehozásának folyamatán beolvasott PDF-ekből (és akár egyszerű képekből) az Aspose.OCR for .NET használatával. A végére képes leszel **szöveget felismerni PDF-ből** néhány C# sor kóddal, és megérted az egyes lépések mögötti okokat, hogy a megoldást saját projektjeidhez igazíthasd. + +> **Gyors összefoglaló:** Az egész folyamat három dologra redukálódik – az OCR motor inicializálása, a forrás (PDF vagy kép) betáplálása, és a kereshető PDF kimenet mentése. Merüljünk el benne. + +--- + +## Amire szükséged lesz + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6.0+** (or .NET Framework 4.6+) | Az Aspose.OCR modern futtatókörnyezeteket céloz meg; a régebbi verziók esetleg hiányoznak API frissítései. | +| **Aspose.OCR for .NET** NuGet package | Biztosítja az `OcrEngine` osztályt és a PDF kezelő segédprogramokat. | +| **A valid Aspose license** (or use the free evaluation) | Licenc nélkül 30 napos értékelési korlátot és vízjeleket kapsz. | +| **A scanned PDF** (or an image file) you want to make searchable | Ez a forrásdokumentum az OCR-hez. | +| **Visual Studio 2022** (or any C# editor) | Megkönnyíti a hibakeresést, de bármely IDE működik. | + +A könyvtárat a következő NuGet paranccsal telepítheted: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tipp:** Ha CI pipeline-on dolgozol, add hozzá a licencfájlt a build artefaktumokhoz, és töltsd be futásidőben, hogy elkerüld a keménykódolt útvonalakat. + +--- + +## OCR végrehajtása PDF-en – Az Aspose.OCR beállítása + +Az első dolog, amire szükségünk van, egy új `OcrEngine` példány. Gondolj rá úgy, mint az agyra, amely elolvassa a dokumentumodat. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Miért új példány minden alkalommal? A motor konfigurációt (például nyelvi beállításokat) tárol, amelyek dokumentumonként eltérhetnek. Minden futtatásnál új példány létrehozása tiszta állapotot biztosít, és elkerüli a feladatok közötti átfedéseket. + +--- + +## Hogyan hozzunk létre kereshető PDF-et – Jelszavak beállítása (opcionális) + +Ha a PDF védett, meg kell adnod a motor számára a jelszót, mielőtt olvasni tudná az oldalakat: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Ennek a lépésnek a kihagyása egy védett fájlnál `PdfPasswordException`-t fog kiváltani. Mindig tedd try‑catch blokkba, ha nem vagy biztos a védelem állapotában. + +--- + +## Beolvasott PDF konvertálása kereshető PDF‑é – A forrás betöltése + +Az Aspose.OCR a `OcrImage` absztrakcióval dolgozik, amely PDF-eket, TIFF-eket, JPEG-eket stb. tud becsomagolni. Íme, hogyan töltöd be a beolvasott PDF-et a memóriába: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +A háttérben a `FromFile` minden oldalt raszteres képpé alakít, amelyet az OCR motor feldolgozhat. Ha többoldalas PDF-ed van, a motor automatikusan végigiterál minden oldalon. + +--- + +## Szöveg felismerése PDF‑ből – OCR végrehajtása + +Most a tutorial központi része: kérd meg a motort, hogy ismerje fel a szöveget, és hozzon létre egy kereshető PDF-et. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +Az `OutputFormat.SearchablePdf` azt mondja a motornak, hogy ágyazzon be egy láthatatlan szövegréteget az eredeti beolvasott képek tetejére. Az eredményül kapott PDF megőrzi a szkennelés vizuális hűségét, miközben teljesen kereshető lesz – pontosan ez szükséges a megfelelőségi auditokhoz. + +--- + +## Kép konvertálása kereshető PDF‑é – Az eredmény mentése + +Végül írd a bináris adatot a lemezre: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +A `Binary` tulajdonság a nyers PDF bájtokat tartalmazza. API-t építve közvetlenül is streamelheted őket egy webválaszba. + +![Diagram, amely bemutatja az OCR átalakítási folyamatot a kereshető PDF létrehozásához](https://example.com/ocr-flow.png "OCR végrehajtása PDF-en folyamatábra") + +*Kép alt szöveg: OCR végrehajtása PDF-en folyamatábra, amely bemutatja, hogyan alakul egy beolvasott PDF kereshető PDF‑é.* + +--- + +## Széljegyek és gyakorlati tippek + +### 1. Nagy fájlok és memória kezelés +Ha 100 MB-nál nagyobb PDF-eket dolgozol fel, fontold meg a `OcrEngineSettings.MemoryLimit` használatát a memóriahasználat korlátozásához. Emellett dolgozd fel az oldalakat kötegekben, hogy elkerüld az `OutOfMemoryException`-t. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Nyelvtámogatás +Alapértelmezés szerint az Aspose.OCR az angolt feltételezi. Más nyelvek felismeréséhez állítsd be a `Language` tulajdonságot: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Többszálú helyzetek +Az `OcrEngine` **nem** szálbiztos. Ha párhuzamos feldolgozásra van szükséged, hozz létre külön motorokat szálanként. + +### 4. OCR pontosság hibakeresése +A `ocrResult`-ből kinyerheted a sima szöveget hibakeresés céljából: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Ha a kimenet torzultnak tűnik, kísérletezz a `PreprocessSettings`-szel (pl. kiegyenesítés, zajcsökkentés) a minőség javítása érdekében. + +### 5. Licencelési csapdák +Ha az értékelő verziót futtatod, az Aspose vízjelet ad az eredmény PDF-hez. Regisztráld a licencet korán az alkalmazásban: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Teljes működő példa – A kezdetektől a végéig + +Az alábbiakban a teljes, azonnal futtatható program található, amely tartalmazza a fentiekben szereplő összes tippet. Nyugodtan másold be egy új konzolprojektbe. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Várható kimenet:** A futtatás után egy konzolos sor jelenik meg, amely megerősíti a fájl helyét. Nyisd meg az `output.pdf`-et bármely PDF‑nézőben; próbálj beírni egy szót, amelyet tudsz, hogy megjelenik az eredeti beolvasásban. Ha a szöveg kiemelésre kerül, sikeresen **végrehajtottad az OCR-t PDF-en**, és létrehoztál egy kereshető dokumentumot. + +--- + +## Gyakran Ismételt Kérdések + +**Q: Használhatom ezt egyetlen kép (PNG/JPEG) kereshető PDF‑é konvertálására?** +A: Természetesen. Cseréld le a `OcrImage.FromFile("input.pdf")`-t a képfájlod elérési útjára. A motor rasterizálja a képet, és ugyanúgy beágyazza az OCR réteget. + +**Q: Mi van, ha a PDF-em tartalmaz beolvasott oldalakat és natív szöveget is?** +A: A motor az OCR szöveget az existing tartalomra helyezi, így a natív szöveg továbbra is kiválasztható marad, míg a beolvasott oldalak kereshetővé válnak. + +**Q: Mennyire pontos az OCR?** +A: A pontosság a forrás minőségétől függ. Tiszta, nagy felbontású szkennelések (>300 dpi) >95 % pontosságot adnak. Zajos dokumentumok esetén engedélyezd a `PreprocessSettings`-t (kiegyenesítés, zajcsökkentés) a `Recognize` hívása előtt. + +--- + +## Következő lépések – OCR eszköztárad bővítése + +Most, hogy **szöveget tudsz felismerni PDF‑ből** és **beolvasott PDF‑et kereshető PDF‑é konvertálni**, fontold meg a következő témákat: + +- **Batch processing**: Egy mappában lévő PDF-eket ciklusba véve automatikusan generálj kereshető verziókat. +- **Text extraction**: Használd a `ocrResult.Text`-et egy kereső index (pl. Elasticsearch) feltöltéséhez. +- **Custom language packs**: Tölts le további nyelvi adatokat az Aspose‑tól az ázsiai írásrendszerek támogatásához. +- **PDF/A compliance**: Kombináld az Aspose.PDF-et az OCR kimenettel, hogy archiválásra kész PDF-eket hozz létre. + +--- + +## Összegzés + +Most mutattuk meg, **hogyan kell OCR-t végrehajtani PDF** fájlokon az Aspose.OCR használatával, a beolvasott PDF-eket teljesen kereshető PDF‑ekké alakítottuk, és még a sima képek kereshető PDF‑évé konvertálásról is szó esett. A kód + +## Mit érdemes most tanulni? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás teljesen működő kódrészleteket tartalmaz lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [PDF szöveg felismerése – OCR műveletek Aspose.OCR for Java-val](/ocr/english/java/ocr-operations/) +- [Hogyan OCR-elj PDF-et .NET-ben az Aspose.OCR-rel](/ocr/english/net/text-recognition/recognize-pdf/) +- [Képek konvertálása PDF‑é C#‑ban – Többoldalas OCR eredmény mentése](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/hungarian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..319f3cf98 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-06-03 +description: Videó felirat OCR oktatóanyag, amely bemutatja, hogyan lehet képkockákat + kinyerni a videóból, és szöveget olvasni MP4-hez hasonló videofájlokból az Aspose.OCR + használatával. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: hu +og_description: Tanulja meg a videó felirat OCR-t az Aspose.OCR-rel. Kivonja a képkockákat + a videóból, beolvassa a szöveget a videóból, és néhány perc alatt kinyeri a szöveget + az MP4-ből. +og_title: Videó felirat OCR C#-ban – Lépésről lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: Videó felirat OCR C#-ban – Teljes útmutató +url: /hu/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Videó felirat OCR C#‑ben – Teljes útmutató + +Valaha szükséged volt **video subtitle ocr**‑ra, de nem tudtad, hol kezdjed? Nem vagy egyedül. Akár előadások felvételeit digitalizálod, akár képzési videókból szeretnél feliratokat kinyerni, vagy egyszerűen csak kíváncsi vagy a videóból **szöveg olvasása videóból** szöveg olvasására, ez a bemutató pontosan megmutatja, hogyan teheted meg C#‑ben és az Aspose.OCR‑rel. + +A következő néhány percben kinyerjük a videó képkockáit, futtatunk OCR‑t ezeken a képkockákon, és végül megjelenítjük a felirat szöveget képkockáról képkockára. A végére képes leszel **szöveg olvasása videóból** fájlokból – beleértve az MP4‑et – anélkül, hogy harmadik féltől származó eszközöket keresnél. + +## Amit építeni fogsz + +Készítünk egy kis konzolos alkalmazást, amely: + +1. Dekódolja az MP4‑et (vagy bármely támogatott formátumot) egyedi `Bitmap` képkockákra. +2. Korlátozza az OCR régiót a feliratsávra, hogy a motor ne legyen elterelve a teljes képről. +3. Feldolgozza minden képkockát az Aspose `VideoOcrProcessor`‑rel. +4. Kiírja a felismert felirat szöveget a konzolra. + +Nincs felesleges részlet, csak egy működő, vég‑től‑végig példakód, amelyet beilleszthetsz egy valódi projektbe. + +## Előfeltételek + +- **.NET 6.0** vagy újabb (a kód .NET Framework 4.7+‑on is működik). +- **Aspose.OCR for .NET** – telepítsd a NuGet‑en: `Install-Package Aspose.OCR`. +- Egy videófájl (az MP4 remekül működik). +- Egy mód a videó képkockáinak dekódolására – a demó egy helykitöltő metódust használ, de beillesztheted az FFmpeg‑et, OpenCV‑t vagy bármely könyvtárat, amely `Bitmap` objektumokat ad vissza. + +> Pro tipp: Ha Windows‑t használsz, a `System.Drawing.Common` csomag jól működik `Bitmap`‑hez. Linux/macOS alatt a natív `libgdiplus` függőségre lesz szükséged. + +## 1. lépés – Képkockák kinyerése a videóból + +Az első akadály a mozgó kép átalakítása álló képekké. Az alábbi `GetVideoFrames` metódus szándékosan üresen maradt; cseréld le a kedvenc dekóderedre. Itt egy gyors vázlat FFmpeg‑Core használatával (csak a data struktúra bemutatására): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Miért fontos:** A képkockák kinyerése statikus képet biztosít az OCR motor számára, ami drámaian javítja a pontosságot a videófolyamból való közvetlen olvasáshoz képest. + +## 2. lépés – A VideoOcrProcessor beállítása + +Most, hogy van egy sor `Bitmap` objektumunk, átadhatjuk őket az Aspose.OCR‑nek. A `VideoOcrProcessor` lehetővé teszi egy **Region of Interest (ROI)** meghatározását – tökéletes a feliratokhoz, amelyek általában a képkocka tetején vagy alján helyezkednek el. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Miért korlátozzuk az ROI‑t?** A kép többi részének figyelmen kívül hagyásával csökkentjük a zajt, lerövidítjük a feldolgozási időt, és elkerüljük a háttérgrafikából származó hamis pozitív találatokat. + +## 3. lépés – OCR futtatása a képkockasorozaton + +A processzor készen áll, a képkockák betáplálása egyetlen sorban megoldható. A `Process` metódus egy `OcrResult` objektumok enumerálhatóját adja vissza, amelyek mindegyike a megfelelő képkockához tartozó felismert szöveget tartalmazza. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Mi történik a háttérben?** Az Aspose.OCR belsőleg normalizálja minden bitmapet, egy neurális hálózaton alapuló felismerőt futtat, majd utófeldolgozza a kimenetet a központozás és sortörések javítása érdekében. + +## 4. lépés – A kinyert szöveg megjelenítése + +Végül végigiterálunk az eredményeken és kiírjuk minden feliratsort. Írhatsz is egy SRT fájlba, adatbázisba, vagy továbbíthatod egy fordítási szolgáltatás felé. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Teljes működő példa + +Mindent egybe rakva egy önálló konzolos programot kapunk: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Várható kimenet (példa)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Ha az OCR nehézségekbe ütközik egy adott képkockán, egy üres stringet látsz – ez jelzés arra, hogy módosítsd az ROI‑t vagy növeld a képkocka‑kinyerési gyakoriságot. + +## Gyakori hibák és megoldások + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Rossz karakterek** | Alacsony felbontású képkockák vagy erős tömörítés | Képkockákat magasabb bitrátával nyerj ki, vagy méretezd fel a bitmapet OCR előtt (`Bitmap.Clone(new Size(...), ...)`). | +| **Nincs visszaadott szöveg** | Az ROI nem fedi le a feliratsávot | Ellenőrizd a téglalap koordinátáit (használj képernyőképező eszközt a méréshez). | +| **Teljesítmény szűk keresztmetszet** | Minden képkocka feldolgozása 30 fps‑nél túlzott | Csökkentsd a mintavételezést 1‑2 fps‑re a legtöbb feliratsorozatnál; így is el tudod kapni minden feliratszakaszt. | +| **FFmpeg nem található** | `ffmpeg.exe` nincs a `PATH`‑ban | Add meg a teljes elérési utat a `ProcessStartInfo.FileName`‑ben, vagy telepítsd globálisan az FFmpeg‑et. | + +## A megoldás bővítése + +- **Exportálás SRT‑be** – fűzd össze az időbélyegeket az OCR szöveggel, és írd ki egy SubRip fájlba. +- **Többnyelvű támogatás** – állítsd be `ocrProcessor.Language = OcrLanguage.Spanish` (vagy bármely támogatott nyelvet). +- **Valós idejű feldolgozás** – csővezess képkockákat közvetlenül egy élő streame‑ből a lemezről való olvasás helyett. + +Mindezek a variációk továbbra is a **képkockák kinyerése a videóból**, **szöveg olvasása videóból**, és **szöveg kinyerése mp4‑ből** alapgondolatokra épülnek. + +## Következtetés + +Most végigvezettünk egy teljes **video subtitle ocr** munkafolyamaton C#‑ben. A videóból képkockák kinyerésével, az OCR fókuszálásával a feliratsávra, és az eredmények iterálásával megbízhatóan **szöveg olvasása videóból** fájlokból, például MP4‑ből, tudsz. A kód készen áll a másolás‑beillesztésre, és a moduláris felépítés lehetővé teszi, hogy bármilyen kedvenc képkocka‑dekódert használj. + +Mi a következő lépés? Próbáld meg az eredményeket SRT‑fájlba exportálni, kísérletezz különböző ROI méretekkel, vagy add a feliratokat egy fordítási API‑nak a többnyelvű feliratokhoz. A lehetőségek határtalanok, amint elsajátítottad a videóból szöveg kinyerésének alapjait. + +Boldog kódolást, és legyenek a felirataid mindig kristálytiszta! + +## Mit érdemes következőként megtanulni? + +Az alábbi oktatóanyagok szorosan kapcsolódó témákat fednek le, amelyek a jelen útmutatóban bemutatott technikákra épülnek. Minden forrás tartalmaz teljes, működő kódpéldákat lépésről‑lépésre magyarázatokkal, hogy segítsenek elsajátítani további API‑funkciókat és alternatív megvalósítási megközelítéseket a saját projektjeidben. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/indonesian/net/ocr-configuration/_index.md index 6dff131fd..5bda1f04b 100644 --- a/ocr/indonesian/net/ocr-configuration/_index.md +++ b/ocr/indonesian/net/ocr-configuration/_index.md @@ -56,13 +56,19 @@ Jelajahi potensi besar Aspose.OCR untuk .NET saat Anda dengan mudah melakukan pe ## Tutorial Konfigurasi OCR ### [OCROperation dengan Arsip dalam Pengenalan Gambar OCR](./ocr-operation-with-archive/) Buka potensi OCR dalam aplikasi .NET dengan Aspose.OCR. Pelajari cara mengekstrak teks dari gambar arsip langkah demi langkah. + ### [OCROperation dengan Folder dalam Pengenalan Gambar OCR](./ocr-operation-with-folder/) Buka kekuatan pengenalan gambar OCR di .NET dengan Aspose.OCR. Ekstrak teks dengan mudah dari gambar. + ### [OCROperation dengan Pemilihan Bahasa dalam Pengenalan Gambar OCR](./ocr-operation-with-language-selection/) Buka kemampuan OCR yang kuat dengan Aspose.OCR untuk .NET. Ekstrak teks dari gambar secara mulus. + ### [OCROperation dengan Daftar dalam Pengenalan Gambar OCR](./ocr-operation-with-list/) Buka potensi Aspose.OCR untuk .NET. Lakukan pengenalan gambar OCR dengan daftar secara mudah. Tingkatkan produktivitas dan ekstraksi data dalam aplikasi Anda. +### [Dapatkan Versi Aspose OCR di C# – Panduan Lengkap](./get-aspose-ocr-version-in-c-complete-guide/) +Pelajari cara mengambil versi Aspose.OCR yang terpasang dalam aplikasi C# Anda dengan contoh kode lengkap. + ### Kasus Penggunaan Umum - **Ekstrak gambar teks** dari faktur yang dipindai untuk akuntansi otomatis. - Mengindeks arsip dokumen besar untuk repositori yang dapat dicari. @@ -98,4 +104,4 @@ A: Ya, objek `OcrResult` menyediakan nilai kepercayaan yang dapat Anda periksa s {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/indonesian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..af952a5fc --- /dev/null +++ b/ocr/indonesian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-06-03 +description: Dapatkan versi Aspose OCR di C# dengan potongan kode sederhana. Pelajari + cara mengambil versi perpustakaan Aspose OCR menggunakan OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: id +og_description: Dapatkan versi Aspose OCR di C# dengan cepat. Tutorial ini menunjukkan + secara tepat cara mengambil versi perpustakaan Aspose OCR menggunakan OcrEngine + GetVersion. +og_title: Dapatkan Versi Aspose OCR di C# – Panduan Lengkap +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Dapatkan Versi Aspose OCR di C# – Panduan Lengkap +url: /id/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Dapatkan Versi Aspose OCR di C# – Panduan Lengkap + +Pernah bertanya-tanya bagaimana cara **get Aspose OCR version** dari dalam proyek .NET Anda? Mungkin Anda sedang memecahkan masalah ketidakcocokan, atau Anda hanya ingin mencatat build perpustakaan yang tepat yang berjalan di produksi. Apa pun alasannya, Anda berada di tempat yang tepat. + +Dalam tutorial ini kami akan membahas sebuah program C# kecil yang berdiri sendiri yang memanggil `OcrEngine.GetVersion()` dan mencetak hasilnya. Pada akhir tutorial Anda akan tahu tidak hanya *bagaimana* mengambil versi, tetapi juga *mengapa* memeriksa versi dapat menghindarkan Anda dari masalah saat memperbarui **Aspose OCR library**. + +## Apa yang Akan Anda Pelajari + +- Tambahkan paket NuGet Aspose.OCR ke proyek C# +- Gunakan metode `OcrEngine.GetVersion()` (titik masuk **ocrengine getversion**) +- Tangani kemungkinan pengecualian dan verifikasi output +- Perluas potongan kode untuk skenario dunia nyata seperti pencatatan atau pengalihan fitur bersyarat + +Tidak diperlukan pengalaman sebelumnya dengan OCR—hanya pemahaman dasar tentang C# dan Visual Studio (atau IDE favorit Anda). Mari kita mulai. + +--- + +## Langkah 1: Siapkan Proyek dan Tarik Perpustakaan Aspose OCR + +Sebelum Anda dapat memanggil API terkait OCR apa pun, Anda perlu **Aspose OCR library** direferensikan dalam proyek Anda. + +1. Buka terminal atau Package Manager Console di Visual Studio. +2. Jalankan perintah berikut untuk menginstal versi stabil terbaru: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Jika Anda menargetkan .NET Framework alih-alih .NET Core, gunakan UI NuGet Package Manager dan pilih versi yang cocok dengan runtime Anda. Paket tersebut menyertakan kelas `OcrEngine` yang akan kami gunakan nanti. + +### Mengapa ini penting + +Saat Anda menginstal paket, versi assembly di disk mungkin berbeda dari versi yang dilaporkan oleh perpustakaan pada runtime. Menanyakan versi melalui kode memastikan Anda membaca build yang tepat yang dimuat CLR, yang penting untuk debugging dan audit kepatuhan. + +## Langkah 2: Tulis Kode Minimal untuk **Get Aspose OCR Version** + +Buat aplikasi konsol baru (`dotnet new console -n OcrVersionDemo`) dan ganti `Program.cs` default dengan yang berikut: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Penjelasan setiap bagian** + +- `using Aspose.OCR;` membawa namespace OCR ke dalam cakupan, memungkinkan kami memanggil `OcrEngine`. +- `OcrEngine.GetVersion()` adalah metode statik **ocrengine getversion** yang mengembalikan string seperti `"24.5.7"`. +- Membungkus pemanggilan dalam blok `try/catch` melindungi Anda dari kejutan runtime—mungkin binary native tidak ditemukan di mesin target. +- String interpolasi `$"Aspose OCR version: {version}"` mencetak baris yang jelas dan dapat dibaca manusia. + +### Output yang Diharapkan + +Saat Anda menjalankan `dotnet run` di dalam folder proyek, Anda harus melihat sesuatu yang mirip dengan: + +``` +Aspose OCR version: 24.5.7 +``` + +Jika perpustakaan tidak dapat dimuat, cabang error akan mengeluarkan pesan singkat, membantu Anda mengidentifikasi masalah dengan cepat. + +## Langkah 3: Verifikasi Versi Sesuai dengan Paket NuGet Anda + +Mudah mengasumsikan versi NuGet yang Anda instal adalah yang digunakan pada runtime, tetapi keanehan lingkungan dapat mengganggu. Untuk memeriksa kembali: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Menjalankan potongan tambahan ini akan mencetak sesuatu yang mirip dengan: + +``` +Assembly file version: 24.5.7.0 +``` + +Jika kedua nilai berbeda, Anda mungkin memuat DLL lama dari Global Assembly Cache (GAC) atau dari folder build sebelumnya. Dalam kasus itu, bersihkan solusi Anda (`dotnet clean`) dan bangun kembali. + +## Langkah 4: Masukkan Pemeriksaan Versi ke dalam Logging Produksi + +Sebagian besar aplikasi dunia nyata tidak hanya mencetak ke konsol; mereka menulis ke file log atau sistem telemetri. Berikut contoh cepat menggunakan `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Sekarang versi muncul di log terstruktur Anda, memudahkan penyaringan berdasarkan `{Version}` nanti. Pola ini sangat berguna ketika Anda memiliki beberapa micro‑services yang masing‑masing menarik OCR DLL yang mungkin berbeda. + +## Pertanyaan Umum & Kasus Tepi + +### Bagaimana jika `GetVersion()` mengembalikan string kosong? + +Itu biasanya menandakan instalasi yang rusak atau ketergantungan native yang hilang. Instal ulang paket NuGet dan pastikan `Aspose.OCR.Native.dll` (atau binary spesifik platform yang sesuai) berada di samping executable Anda. + +### Apakah metode ini bekerja pada .NET Core 2.0? + +Ya, **Aspose OCR** mendukung .NET Standard 2.0 dan lebih tinggi, jadi versi .NET Core apa pun yang mengimplementasikan standar tersebut dapat memanggil `OcrEngine.GetVersion()`. Pastikan Anda merujuk pada identifier runtime yang tepat (`win‑x64`, `linux‑x64`, dll.) jika Anda mempublikasikan aplikasi self‑contained. + +### Bisakah saya mengambil versi tanpa file lisensi? + +Tentu saja. `GetVersion()` **tidak** memerlukan lisensi; ia hanya melaporkan nomor build perpustakaan. Namun, jika Anda mencoba melakukan OCR tanpa lisensi yang valid, Anda akan mendapatkan pengecualian runtime. Itulah mengapa `try/catch` dalam potongan kode kami berharga—ia memisahkan pemeriksaan versi dari alur eksekusi OCR. + +## Contoh Lengkap yang Berfungsi (Siap Salin‑Tempel) + +Berikut seluruh program, siap dimasukkan ke dalam proyek konsol baru. Ini mencakup blok logging opsional, sehingga Anda dapat melihat output konsol dan log terstruktur secara bersamaan. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Jalankan dengan `dotnet run` dan Anda akan melihat dua baris yang mengonfirmasi versi, plus baris debug jika Anda mengaktifkan `LogLevel.Debug`. + +## Kesimpulan + +Kami telah membahas semua yang Anda perlukan untuk **get Aspose OCR version** di lingkungan C#—dari menginstal **Aspose OCR library**, memanggil metode **ocrengine getversion**, menangani kesalahan, hingga menyematkan hasil dalam logging tingkat produksi. Dengan pengetahuan ini, Anda kini dapat memverifikasi secara andal build OCR yang tepat yang digunakan aplikasi Anda, menghindari bug terkait versi, dan memenuhi persyaratan kepatuhan tanpa kesulitan. + +Langkah selanjutnya? Coba gabungkan pemeriksaan versi ini dengan panggilan OCR sebenarnya (`OcrEngine` → `RecognizeImage`) dan catat baik versi maupun hasil pengenalan. Anda juga dapat menjelajahi pola **retrieve aspose version** untuk produk Aspose lainnya (PDF, Slides, Cells) agar seluruh suite Anda tetap sinkron. + +Selamat coding, dan semoga pipeline OCR Anda tetap tajam! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda. + +- [Cara Mendapatkan Hasil OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Cara Memproses Batch Gambar OCR dengan List di Aspose.OCR untuk .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/indonesian/net/ocr-optimization/_index.md index 74145b54e..1359c972c 100644 --- a/ocr/indonesian/net/ocr-optimization/_index.md +++ b/ocr/indonesian/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Jelajahi Aspose.OCR untuk .NET. Tingkatkan akurasi OCR dengan filter preprocessi Tingkatkan akurasi OCR dengan Aspose.OCR untuk .NET. Perbaiki ejaan, sesuaikan kamus, dan capai pengenalan teks bebas kesalahan dengan mudah. ### [Simpan Hasil Multipage sebagai Dokumen dalam OCR Image Recognition](./save-multipage-result-as-document/) Buka potensi Aspose.OCR untuk .NET. Simpan hasil OCR multipage sebagai dokumen dengan mudah menggunakan panduan langkah demi langkah yang komprehensif ini. +### [Contoh Aspose OCR C# – Aktifkan GPU, Atur Batas Memori & Proses Gambar TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Pelajari cara mengaktifkan GPU, mengatur batas memori, dan memproses file TIF dengan Aspose OCR menggunakan C#. ## Pertanyaan yang Sering Diajukan diff --git a/ocr/indonesian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/indonesian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..71260fb5a --- /dev/null +++ b/ocr/indonesian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,285 @@ +--- +category: general +date: 2026-06-03 +description: Contoh Aspose OCR C# yang menunjukkan cara mengatur batas memori GPU, + memuat gambar untuk OCR, dan mengenali teks dari file TIF dengan kode lengkap serta + tips. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: id +og_description: 'Pelajari contoh lengkap Aspose OCR C#: aktifkan GPU, atur batas memori + GPU, muat gambar untuk OCR, dan kenali teks dari file TIF. Kode lengkap disertakan.' +og_title: Contoh Aspose OCR C# – Akselerasi GPU, Batas Memori & Pemrosesan TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Contoh Aspose OCR C# – Aktifkan GPU, Atur Batas Memori & Proses Gambar TIF +url: /id/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – Aktifkan GPU, Atur Batas Memori & Proses Gambar TIF + +Pernahkah Anda bertanya-tanya bagaimana cara memaksimalkan kinerja kode **Aspose OCR C# example** saat menangani pemindaian TIFF yang besar? Anda tidak sendirian. Dalam banyak proyek dunia nyata—bayangkan mendigitalkan arsip atau mengekstrak data dari kwitansi resolusi tinggi—bottleneck bukanlah algoritma OCR itu sendiri, melainkan pemanfaatan perangkat keras. + +Begini: Aspose OCR mendukung percepatan GPU, tetapi Anda harus memberi tahu berapa banyak memori yang boleh digunakannya, memuat tipe gambar yang tepat, dan akhirnya mengambil teks yang dikenali dari file .tif. Tutorial ini memandu Anda melalui setiap langkah, mulai dari menginstal SDK hingga menyesuaikan pengaturan GPU, sehingga Anda dapat menjalankan OCR dengan kecepatan tinggi tanpa menghabiskan RAM GPU Anda. + +Kami juga akan menambahkan beberapa skenario “bagaimana jika”—seperti menangani TIFF multi‑halaman atau kembali ke CPU ketika GPU tidak tersedia—sehingga Anda mendapatkan solusi yang kuat, bukan hanya potongan kode satu kali. + +## Apa yang Anda Butuhkan + +Sebelum kita mulai, pastikan Anda memiliki hal‑hal berikut di mesin Anda: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6 SDK** (or later) | Aspose OCR menargetkan .NET Standard 2.0+, jadi semua versi .NET terbaru dapat digunakan. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | Pustaka inti yang menyediakan `OcrEngine`, `GpuSettings`, dll. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Diperlukan untuk percepatan GPU; SDK akan memeriksa driver yang kompatibel pada saat runtime. | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | Tanpa memori yang cukup, engine dapat beralih ke CPU secara diam‑diam. | +| A **high‑resolution TIFF** image you want to process | Aspose OCR dapat membaca hampir semua format raster, tetapi TIF umum untuk pemindaian. | +| Visual Studio 2022 (or any editor you like) | Untuk membangun dan men-debug proyek C#. | + +Jika ada yang kurang, kode tetap dapat dikompilasi, tetapi Anda tidak akan melihat peningkatan kinerja yang diinginkan. + +## Langkah 1: Buat Engine Aspose OCR C# Example + +Hal pertama dalam setiap **Aspose OCR C# example** adalah menginstansiasi engine OCR. Anggap `OcrEngine` sebagai sutradara film—ia mengoordinasikan segala hal mulai dari pemuatan gambar hingga ekstraksi teks. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** Jika Anda berencana memproses banyak gambar secara berurutan, pertahankan satu `OcrEngine` tetap hidup. Membuatnya kembali per gambar menambah overhead yang dapat melampaui waktu OCR. + +## Langkah 2: Atur Batas Memori GPU (dan Aktifkan Akselerasi) + +Sekarang datang bagian yang sering membuat orang kebingungan: **atur batas memori GPU**. Secara default Aspose OCR akan mencoba menggunakan sebanyak mungkin VRAM, yang pada workstation bersama dapat menghambat aplikasi lain. Objek `GpuSettings` memungkinkan Anda membatasi alokasi. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Mengapa mengatur batas memori? + +- **Stability:** Mencegah crash out‑of‑memory saat memproses gambar raksasa. +- **Co‑existence:** Memungkinkan aplikasi berat GPU lain (misalnya model TensorFlow) berjalan berdampingan. +- **Predictability:** Membuat pengujian kinerja dapat diulang karena GPU tidak akan mulai swapping. + +Jika Anda menghilangkan `MemoryLimitMb`, Aspose akan mengalokasikan apa pun yang dianggap perlu, yang mungkin baik pada server inferensi khusus tetapi berisiko pada laptop pengembang. + +## Langkah 3: Muat Gambar untuk OCR + +Memuat format file yang tepat adalah langkah penting berikutnya. Metode `OcrImage.FromFile` secara otomatis mendeteksi tipe gambar, tetapi Anda tetap harus memverifikasi bahwa file ada dan merupakan varian TIFF yang didukung (misalnya LZW‑compressed atau CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Menangani TIFF multi‑halaman + +Jika TIFF Anda berisi beberapa halaman, Aspose OCR secara default hanya membaca halaman pertama. Untuk memproses semua halaman, Anda dapat melakukan loop pada `image.Pages` (tersedia pada versi SDK terbaru) dan memberi setiap halaman ke engine secara terpisah. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Potongan kode di atas menunjukkan pola **load image for OCR** yang bekerja untuk file tunggal maupun multi‑halaman. + +## Langkah 4: Kenali Teks dari TIF (atau raster apa pun) + +Sekarang gambar berada di memori, kami meminta Aspose melakukan magisnya. Metode `Recognize` mengembalikan `OcrResult` yang berisi teks polos, skor kepercayaan, dan bahkan informasi bounding‑box jika Anda memerlukannya. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Mengapa ini bekerja baik dengan TIF + +- **Lossless compression:** TIFF sering menyimpan data piksel mentah, memberikan engine OCR fidelitas tertinggi. +- **Multiple color spaces:** Aspose dapat menangani TIFF grayscale, RGB, atau bahkan CMYK tanpa kode konversi tambahan. + +Jika Anda perlu menyesuaikan paket bahasa (misalnya Prancis atau Jepang), setel `ocrEngine.Settings.Language = "fr"` sebelum memanggil `Recognize`. + +## Langkah 5: Tampilkan Teks yang Dikenali + +Akhirnya, kami menampilkan teks ke konsol. Dalam aplikasi nyata Anda mungkin menulis ke basis data, file JSON, atau mengirim string ke pipeline NLP berikutnya. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Output yang Diharapkan + +Menjalankan program pada pemindaian bersih 300 dpi dari halaman cetak biasanya menghasilkan sesuatu seperti: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Jika gambar buram atau batas memori GPU terlalu rendah, Anda mungkin melihat karakter acak atau hasil terpotong. Menurunkan `MemoryLimitMb` di bawah jejak memori gambar (sering ~1 GB untuk TIFF 6000×8000 piksel) dapat menyebabkan engine beralih ke CPU secara otomatis. + +## Contoh Lengkap yang Berfungsi + +Berikut adalah program lengkap yang siap dijalankan. Salin‑tempel ke dalam proyek Console App baru, ganti `YOUR_DIRECTORY/large_photo.tif` dengan path ke TIFF Anda sendiri, dan tekan **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Daftar Periksa Cepat + +- ✅ **Aspose OCR C# example** berhasil dikompilasi tanpa error. +- ✅ **GPU diaktifkan** (`Enable = true`). +- ✅ **Batas memori GPU** diatur ke 2048 MB. +- ✅ **Gambar dimuat** dari file TIF. +- ✅ **Teks dikenali** dan dicetak. + +## Kesalahan Umum & Cara Menghindarinya + +| Gejala | Penyebab kemungkinan | Solusi | +|--------|----------------------|--------| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA runtime tidak terinstal atau versi tidak cocok. | Instal CUDA 11.x (atau 12.x) yang cocok dengan driver Anda. | +| OCR returns empty string | Gambar terlalu gelap atau DPI < 150. | Pra‑proses dengan `image.AdjustContrast()` atau ubah resolusi menjadi 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` terlalu rendah untuk gambar. | Tingkatkan batasnya atau bagi gambar menjadi ubin melalui `image.Crop`. | +| `Unsupported image format` error | TIFF menggunakan kompresi eksotis (misalnya JPEG‑2000). | Konversi TIFF ke format yang didukung dengan ImageMagick sebelum OCR. | + +## Memperluas Demo + +Sekarang Anda memiliki **aspose ocr c# example** yang solid, Anda mungkin ingin menjelajahi: + +- **Batch processing:** Loop melalui folder TIF, tulis setiap hasil ke file `.txt`. +- **Language packs:** `ocrEngine.Settings.Language = "es"` untuk bahasa Spanyol, atau muat kamus khusus. +- **Bounding boxes:** Gunakan `ocrResult.Regions` untuk mendapatkan koordinat setiap kata—berguna untuk alat redaksi. +- **CPU fallback:** Bungkus blok GPU dalam try/catch; jika gagal, setel `ocrEngine.Settings.Gpu.Enable = false` dan coba lagi. + +Ekstensi ini menjaga pola inti tetap utuh sambil menambah nilai untuk penggunaan spesifik — + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/indonesian/net/skew-angle-calculation/_index.md index c65ca9177..6e2b675bc 100644 --- a/ocr/indonesian/net/skew-angle-calculation/_index.md +++ b/ocr/indonesian/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Jelajahi Aspose.OCR untuk .NET, solusi OCR canggih untuk pengenalan teks akurat Bebaskan kecanggihan Aspose.OCR untuk .NET, solusi tangguh untuk pengenalan gambar. Pelajari cara menghitung sudut kemiringan dengan mudah. ### [Hitung Sudut Kemiringan dari URI dalam Pengenalan Gambar OCR](./calculate-skew-angle-from-uri/) Jelajahi Aspose.OCR untuk .NET untuk menghitung sudut kemiringan dengan mudah dalam pengenalan gambar OCR. Tingkatkan proyek Anda dengan presisi dan efisiensi. +### [Tutorial Dokumen OCR Berputar – Perbaikan Skew & Rotasi Otomatis di C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Pelajari cara memperbaiki dokumen OCR yang miring secara otomatis dengan Aspose.OCR untuk .NET menggunakan C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/indonesian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..e105831c7 --- /dev/null +++ b/ocr/indonesian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial OCR dokumen berputar yang menunjukkan cara otomatis memperbaiki + kemiringan dan mendeteksi rotasi menggunakan Aspose OCR dalam C#. Pelajari langkah + demi langkah dengan kode lengkap. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: id +og_description: Tutorial OCR dokumen yang diputar mengajarkan Anda cara secara otomatis + memperbaiki kemiringan dan mendeteksi rotasi menggunakan Aspose OCR dalam C#. Ikuti + panduan lengkap. +og_title: Tutorial OCR Dokumen yang Diputar – Perbaikan Skew & Rotasi Otomatis di + C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Tutorial OCR Dokumen Diputar – Perbaikan Skew dan Rotasi Otomatis di C# +url: /id/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial Dokumen OCR yang Diputar – Panduan Lengkap untuk Pengembang C# + +Pernah menemukan **ocr rotated document tutorial** ketika formulir yang dipindai datang dalam posisi miring atau condong? Anda tidak sendirian. Gambar-gambar yang tidak rata itu dapat merusak ekstraksi teks yang bersih, tetapi kabar baiknya adalah Aspose OCR dapat meluruskan semuanya secara otomatis. + +Dalam panduan langkah demi langkah ini kami akan membuat sebuah `OcrEngine`, mengaktifkan **automatic skew correction** dan **auto detect rotation**, menjalankan mesin pada gambar yang diputar, dan mencetak teks yang bersih. Pada akhir tutorial Anda akan tahu persis mengapa setiap pengaturan penting, cara menyesuaikannya untuk kasus tepi, dan Anda akan memiliki program C# yang siap dijalankan. + +## Apa yang Akan Anda Pelajari + +* Cara menginstal dan mereferensikan **Aspose OCR** dalam proyek .NET. +* Mengapa mengaktifkan `AutoCorrectSkew` dan `AutoDetectRotation` adalah kunci untuk **ocr rotated document tutorial** yang handal. +* Cara memuat gambar apa pun (JPG, PNG, TIFF) dan membiarkan mesin melakukan pekerjaan berat. +* Tips untuk menangani PDF multi‑halaman, pemindaian beresolusi rendah, dan paket bahasa khusus. + +> **Prasyarat:** Visual Studio 2022 (atau IDE C# apa pun), runtime .NET 6+, dan lisensi Aspose OCR yang valid (atau percobaan gratis). Tidak diperlukan pengalaman OCR sebelumnya. + +--- + +## Langkah 1 – Instal Aspose OCR dan Siapkan Proyek + +Pertama-tama. Dapatkan paket NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Tips Pro:** Jika Anda menggunakan lisensi percobaan, letakkan file `Aspose.OCR.lic` di folder yang sama dengan executable Anda, atau daftarkan secara programatis dengan `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Buat aplikasi konsol baru: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Sekarang Anda memiliki kanvas bersih untuk **ocr rotated document tutorial** kami. + +## Langkah 2 – Inisialisasi OCR Engine + +Mesin adalah inti dari proses. Anggaplah sebagai pisau Swiss‑army untuk ekstraksi teks; Anda hanya perlu memberi tahu trik apa yang harus diaktifkan. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Mengapa pengaturan ini?** +* `AutoCorrectSkew` menganalisis garis dasar karakter dan memutar gambar cukup untuk membuat baris menjadi horizontal. +* `AutoDetectRotation` memeriksa orientasi keseluruhan (0°, 90°, 180°, 270°) dan membalik halaman jika terbalik. Tanpa keduanya, mesin akan membaca “pɹᴉʍ” alih-alih “word”. + +## Langkah 3 – Muat Gambar yang Ingin Diproses + +Aspose OCR bekerja dengan format raster umum apa pun. Ganti path placeholder dengan lokasi sebenarnya dari formulir yang diputar. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Kasus Tepi:** Jika Anda menerima TIFF multi‑halaman, gunakan `OcrImage.FromMultiPageTiff(filePath)` dan lakukan loop melalui `image.Pages`. + +## Langkah 4 – Jalankan Pengenalan + +Sekarang mesin melakukan keajaiban. Ia akan pertama-tama meluruskan gambar (berkat flag skew/rotation kami) dan kemudian mengekstrak karakter. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Jika Anda membutuhkan dukungan bahasa selain Bahasa Inggris, atur sebelum memanggil `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Langkah 5 – Keluarkan Teks yang Diakui + +Akhirnya, dump teks bersih ke konsol—atau alirkan ke file, basis data, apa pun yang sesuai dengan alur kerja Anda. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Output yang Diharapkan** (asumsi gambar contoh berisi “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Perhatikan bagaimana teks muncul dengan benar meskipun gambar sumber diputar 90° dan sedikit miring. + +## Menangani Kendala Umum + +| Masalah | Mengapa Terjadi | Solusi | +|------|----------------|-----| +| **Output kosong** | Koreksi skew dinonaktifkan atau gambar terlalu gelap. | Aktifkan `AutoCorrectSkew` (sudah aktif) dan tingkatkan kontras gambar melalui `image.AdjustContrast(1.2)`. | +| **Karakter sampah** | Pengaturan bahasa salah. | Setel `ocrEngine.Settings.Language` agar sesuai dengan bahasa dokumen. | +| **Keterlambatan kinerja pada PDF besar** | Mesin memproses setiap halaman secara berurutan. | Gunakan `Parallel.ForEach` pada `image.Pages` untuk memanfaatkan CPU multi‑core. | +| **Pengecualian lisensi** | Percobaan telah kedaluwarsa. | Dapatkan lisensi permanen atau tetap dalam batas percobaan (5 halaman per run). | + +## Tips Pro untuk Tutorial Dokumen OCR yang Diputar yang Tangguh + +* **Pemrosesan batch:** Bungkus seluruh alur dalam sebuah metode yang menerima path folder, melakukan loop pada setiap gambar, dan menulis setiap hasil ke file `.txt`. +* **Pra‑pemrosesan:** Kadang pemindaian yang berisik mendapat manfaat dari `image.Denoise()` sebelum pengenalan. +* **Pasca‑pemrosesan:** Gunakan ekspresi reguler untuk membersihkan kesalahan umum OCR, misalnya, ganti “0” dengan “O” hanya ketika dikelilingi oleh huruf. +* **Logging:** Aspose OCR menyediakan `ocrEngine.Logger` – hubungkan ke logger file untuk menangkap peringatan tentang skor kepercayaan rendah. + +## Kode Lengkap, Siap‑Jalankan + +Simpan yang berikut sebagai `Program.cs` di dalam proyek konsol Anda. Ini mencakup semua langkah, komentar, dan helper kecil untuk pemrosesan batch. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Jalankan: + +```bash +dotnet run +``` + +Anda seharusnya melihat teks yang telah dibersihkan dicetak ke konsol, membuktikan bahwa **ocr rotated document tutorial** kami berfungsi end‑to‑end. + +## Kesimpulan + +Anda kini memiliki **ocr rotated document tutorial** lengkap yang secara otomatis memperbaiki skew, mendeteksi rotasi, dan mengekstrak teks bersih menggunakan Aspose OCR dalam C#. Pelajaran utama? Mengaktifkan `AutoCorrectSkew` **dan** `AutoDetectRotation` mengubah pemindaian yang sangat miring menjadi output yang dapat dibaca dengan sempurna hanya dengan beberapa baris kode. + +Dari sini, Anda dapat memperluas ke pekerjaan batch, mengintegrasikan paket bahasa, atau mengalirkan hasil ke pipeline analitik hilir. Ingin menjelajahi **automatic skew correction** lebih lanjut? Lihat API pra‑pemrosesan gambar Aspose, atau coba ambang khusus untuk pemindaian berisik. + +Punya pertanyaan tentang penanganan PDF, TIFF multi‑halaman, atau integrasi dengan Azure Functions? Tinggalkan komentar, dan selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait erat yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda sendiri. + +- [mode dokumen ocr – Deteksi Mode Area dalam Pengenalan Gambar OCR](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Tutorial Aspose OCR – Pengenalan Karakter Optik](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/indonesian/net/text-recognition/_index.md index 7aee7bb85..2c87ebeae 100644 --- a/ocr/indonesian/net/text-recognition/_index.md +++ b/ocr/indonesian/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Bebaskan kekuatan Aspose.OCR untuk .NET. Pelajari cara mendapatkan hasil OCR dal Tingkatkan aplikasi .NET Anda dengan Aspose.OCR untuk pengenalan teks gambar yang efisien. Jelajahi Mode Deteksi Area OCR untuk hasil yang presisi. ### [Kenali PDF dalam Pengenalan Gambar OCR](./recognize-pdf/) Buka potensi OCR di .NET dengan Aspose.OCR. Ekstrak teks dari PDF dengan mudah. Unduh sekarang untuk pengalaman integrasi yang lancar. +### [Lakukan OCR pada PDF dengan Aspose.OCR – Panduan Lengkap C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Pelajari cara melakukan OCR pada PDF menggunakan Aspose.OCR dengan panduan lengkap C#. ### [Kenali Tabel dalam Pengenalan Gambar OCR](./recognize-table/) Buka potensi Aspose.OCR untuk .NET dengan panduan komprehensif kami tentang mengenali tabel dalam pengenalan gambar OCR. +### [Lakukan OCR pada Gambar dengan Aspose OCR – Panduan Bahasa Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Pelajari cara melakukan OCR pada gambar menggunakan Aspose OCR dengan panduan bahasa Hindi. +### [Cara Menggunakan Aspose: Mengonversi Gambar ke HTML dengan OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Pelajari cara mengonversi gambar menjadi file HTML menggunakan Aspose OCR dalam langkah mudah. +### [Lakukan OCR pada Gambar dan Deteksi Kata Salah Eja dalam C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Pelajari cara melakukan OCR pada gambar dan mendeteksi kata yang salah eja menggunakan Aspose.OCR dalam C#. +### [OCR Subtitle Video dalam C# – Panduan Lengkap](./video-subtitle-ocr-in-c-complete-guide/) +Pelajari cara melakukan OCR pada subtitle video menggunakan Aspose.OCR dengan panduan lengkap C#. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/indonesian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..c6b044799 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Cara menggunakan Aspose untuk mengonversi gambar ke HTML dan mengekstrak + teks dari gambar dalam C#. Pelajari cara menghasilkan HTML dari gambar dan melakukan + OCR gambar ke HTML dengan cepat. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: id +og_description: Cara menggunakan Aspose untuk mengonversi gambar ke HTML, mengekstrak + teks dari gambar, dan menghasilkan HTML dari gambar dengan OCR di C#. Ikuti panduan + lengkap ini. +og_title: 'Cara Menggunakan Aspose: Mengonversi Gambar ke HTML dengan OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Cara Menggunakan Aspose: Mengonversi Gambar ke HTML dengan OCR' +url: /id/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Menggunakan Aspose: Mengonversi Gambar ke HTML dengan OCR + +Pernah bertanya-tanya **bagaimana cara menggunakan Aspose** untuk mengubah gambar yang dipindai menjadi HTML yang rapi? Mungkin Anda memiliki halaman majalah, struk, atau catatan tulisan tangan dan Anda memerlukan teks serta tata letak yang dipertahankan untuk publikasi web. Kabar baiknya, Anda tidak perlu menulis parser khusus atau berurusan dengan pemrosesan gambar tingkat rendah—Aspose.OCR melakukan pekerjaan berat untuk Anda. + +Dalam tutorial ini kami akan membahas **contoh lengkap yang dapat dijalankan** yang menunjukkan cara **mengonversi gambar ke HTML**, **mengekstrak teks dari gambar**, dan **menghasilkan HTML dari gambar** menggunakan pustaka Aspose OCR dalam C#. Pada akhir tutorial Anda akan memiliki aplikasi konsol kecil yang menghasilkan file HTML dengan tata letak halaman asli tetap utuh, siap untuk dimasukkan ke situs web mana pun. + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki hal‑hal berikut di mesin Anda: + +- **.NET 6.0 SDK** atau yang lebih baru (kode ini bekerja dengan .NET Core dan .NET Framework). +- **Visual Studio 2022** (atau editor apa pun yang Anda suka). +- **Aspose.OCR for .NET** – instal melalui NuGet: `dotnet add package Aspose.OCR`. +- File gambar (JPEG/PNG) yang ingin Anda ubah, misalnya `magazine_page.jpg`. + +Tidak diperlukan file konfigurasi tambahan; pustaka sudah menyertakan semua yang diperlukan untuk OCR dan pembuatan tata letak HTML. + +## Langkah 1: Siapkan Proyek dan Tambahkan Aspose.OCR + +Pertama, buat proyek konsol baru dan tambahkan paket Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Jika Anda menggunakan Visual Studio, cukup klik kanan proyek → *Manage NuGet Packages* → cari **Aspose.OCR** dan instal. Langkah ini memastikan Anda dapat **ocr image to html** tanpa referensi yang hilang. + +## Langkah 2: Inisialisasi OCR Engine + +Inti dari proses ini adalah kelas `OcrEngine`. Anggaplah sebagai otak yang membaca gambar dan memutuskan bagaimana menghasilkan hasil. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Di sini kami menginstansiasi `OcrEngine`. Anda tidak perlu memberikan kredensial apa pun untuk versi gratis; pustaka akan menggunakan model pengenalan bawaan. + +## Langkah 3: Muat Gambar Sumber + +Selanjutnya, arahkan engine ke file yang ingin Anda proses. Aspose menyediakan metode `OcrImage.FromFile` yang nyaman dan menangani sebagian besar format gambar. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Ganti `YOUR_DIRECTORY` dengan jalur absolut atau relatif tempat gambar Anda berada. Jika gambar berada di folder yang sama dengan executable, Anda dapat langsung menggunakan `"magazine_page.jpg"`. + +## Langkah 4: Kenali dan Minta HTML dengan Tata Letak + +Ini adalah inti dari tutorial. Dengan memberikan `OutputFormat.HtmlWithLayout` kami memberi tahu Aspose untuk **menghasilkan HTML dari gambar** sambil mempertahankan posisi asli blok teks, gambar, dan tabel. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Properti `recognitionResult.Text` kini berisi dokumen HTML lengkap. Jika Anda hanya membutuhkan teks biasa, Anda dapat menggunakan `OutputFormat.Text`, tetapi kami fokus pada **convert image to html** dengan kesetiaan tata letak. + +## Langkah 5: Simpan File HTML + +Akhirnya, tulis string HTML ke disk. Ini memberi Anda file siap pakai yang dapat dibuka di browser mana pun. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Menjalankan program akan menghasilkan `magazine.html`. Buka file tersebut, dan Anda akan melihat teks halaman asli diposisikan persis seperti yang muncul pada gambar sumber—sempurna untuk pengarsipan atau publikasi web. + +## Contoh Lengkap yang Berfungsi + +Di bawah ini adalah program **lengkap, siap salin‑tempel**. Tidak ada bagian yang dihilangkan, sehingga Anda dapat mengompilasi dan menjalankannya segera setelah mengatur jalur yang benar. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Output yang Diharapkan + +Saat Anda membuka `magazine.html` di browser, Anda akan melihat sesuatu yang mirip dengan ini (disederhanakan untuk ilustrasi): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Atribut `style` yang tepat akan berbeda tergantung pada gambar asli, tetapi struktur ini menjamin bahwa **extract text from image** dan **generate html from image** terjadi dalam satu langkah yang mulus. + +## Pertanyaan Umum & Kasus Tepi + +### Bagaimana jika gambar beresolusi rendah? + +Aspose.OCR bekerja paling baik dengan gambar yang memiliki setidaknya **300 DPI**. Jika file Anda buram, coba pra‑proses dengan pustaka peningkatan gambar (mis., ImageSharp) sebelum memberi makan ke OCR engine. Kualitas rendah dapat memengaruhi akurasi **extract text from image** dan kesetiaan tata letak HTML yang dihasilkan. + +### Bisakah saya mengontrol bahasa OCR? + +Ya. Atur properti `Language` pada `OcrEngine` sebelum memanggil `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Ini meningkatkan pengenalan saat menangani karakter non‑Inggris. + +### Bagaimana cara mendapatkan teks biasa alih-alih HTML? + +Jika Anda hanya membutuhkan string mentah, ganti `OutputFormat.HtmlWithLayout` dengan `OutputFormat.Text`. Properti `recognitionResult.Text` yang sama kemudian akan berisi hanya karakter yang diekstrak. + +### Apakah ada cara untuk menyematkan gambar ke dalam HTML yang dihasilkan? + +Aspose.OCR dapat menyematkan gambar asli sebagai data URI base‑64 ketika Anda menggunakan `OutputFormat.HtmlWithLayoutAndImages`. Ini berguna ketika Anda menginginkan satu file HTML tanpa aset eksternal. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Bagaimana dengan penanganan batch besar? + +Untuk pemrosesan batch, bungkus logika dalam loop `foreach` atas daftar jalur file. Menggunakan kembali instance `OcrEngine` yang sama mengurangi overhead dan mempercepat pipeline **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tips untuk Kode Siap Produksi + +- **Dispose resources**: Baik `OcrEngine` maupun `OcrImage` mengimplementasikan `IDisposable`. Bungkus mereka dalam pernyataan `using` untuk membebaskan memori native dengan cepat. +- **Error handling**: Tangkap `IOException` untuk masalah terkait file dan `OcrException` untuk masalah pengenalan. +- **Performance**: Jika Anda memproses banyak gambar, pertimbangkan mengaktifkan **parallelism** (`Parallel.ForEach`) tetapi perhatikan penggunaan CPU—OCR sangat intensif CPU. +- **Logging**: Integrasikan logger (mis., Serilog) untuk menangkap skor kepercayaan OCR (`recognitionResult.Confidence`) untuk pemantauan kualitas. + +## Kesimpulan + +Kami baru saja membahas **cara menggunakan Aspose** untuk **mengonversi gambar ke HTML**, **mengekstrak teks dari gambar**, dan **menghasilkan HTML dari gambar** dalam beberapa langkah sederhana. Contoh kode lengkap menunjukkan cara **ocr image to html** sambil mempertahankan tata letak, menjadikannya fondasi yang kuat untuk proyek digitalisasi dokumen apa pun. + +Dari sini Anda dapat: + +- Bereksperimen dengan opsi `OutputFormat` yang berbeda untuk memenuhi kebutuhan Anda. +- Menggabungkan output HTML dengan kerangka kerja CSS untuk gaya responsif. +- Mengirimkan teks yang diekstrak ke indeks pencarian atau pipeline pembelajaran mesin. + +Cobalah, sesuaikan pengaturannya, dan lihat betapa mudahnya Aspose mengubah gambar menjadi konten siap web. Jika Anda mengalami kendala, tinggalkan komentar—selamat coding! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah demi langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Konversi Gambar ke Teks – Lakukan OCR pada Gambar dari URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Mengenali teks gambar dengan Aspose OCR untuk banyak bahasa](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/indonesian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..31710ac54 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-03 +description: Lakukan OCR pada gambar dan ekstrak teks dari gambar menggunakan Aspose.OCR. + Pelajari cara mendeteksi kata yang salah eja dan mendapatkan saran ejaan dalam satu + demo C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: id +og_description: Lakukan OCR pada gambar untuk mengekstrak teks, kemudian deteksi kata + yang salah eja dan dapatkan saran ejaan menggunakan Aspose.OCR dalam C#. +og_title: Lakukan OCR pada Gambar dan Deteksi Kata yang Salah Eja di C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Lakukan OCR pada Gambar dan Deteksi Kata yang Salah Eja di C# +url: /id/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lakukan OCR pada Gambar dan Deteksi Kata Salah Eja dalam C# + +Pernah bertanya-tanya bagaimana cara **perform OCR on image** tanpa membuat kepala Anda pusing? Anda tidak sendirian. Baik Anda sedang mendigitalkan surat lama, memindai kwitansi, atau membangun alur kerja dokumen cerdas, mengekstrak teks bersih dari gambar adalah rintangan pertama. Kabar baiknya? Dengan Aspose.OCR Anda dapat membuat solusi dalam hitungan menit, dan bonusnya Anda juga dapat **detect misspelled words** dan **get spelling suggestions** dalam satu proses. + +Dalam tutorial ini kami akan menuntun Anda melalui aplikasi konsol C# lengkap yang **extracts text from image**, menjalankan pemeriksa ejaan bahasa Inggris, dan mencetak setiap kesalahan beserta saran perbaikannya. Pada akhir tutorial Anda akan tahu persis **how to extract text**, cara menghubungkan spell‑check API, dan seperti apa output konsol yang diharapkan. + +## Apa yang Akan Anda Bangun + +- Memuat bitmap (atau PNG) yang berisi kesalahan tipografi. +- Menjalankan Aspose.OCR untuk **perform OCR on image** dan memperoleh data string mentah. +- Menginisialisasi pemeriksa ejaan bahasa Inggris bawaan. +- **Detect misspelled words** dan **get spelling suggestions** untuk masing‑masing. +- Mencetak laporan rapi ke konsol. + +Tanpa layanan eksternal, tanpa panggilan HTTP yang rumit—hanya satu paket NuGet dan beberapa baris kode. + +## Prasyarat + +- .NET 6.0 SDK atau yang lebih baru (kode juga berfungsi pada .NET Framework 4.7+). +- Visual Studio 2022 (atau editor pilihan Anda). +- Paket NuGet Aspose.OCR untuk .NET (`Aspose.OCR`). +- Sebuah file gambar (`letter_with_typos.png`) yang ditempatkan di lokasi yang dapat direferensikan dari proyek. + +Jika Anda belum pernah menggunakan Aspose sebelumnya, jangan khawatir—menginstal paketnya semudah menjalankan: + +```bash +dotnet add package Aspose.OCR +``` + +Sekarang mari kita selami implementasinya. + +## Langkah 1: Siapkan Proyek dan Instal Aspose.OCR + +Buat proyek konsol baru dan tarik pustaka OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Setelah proses restore selesai, buka `Program.cs`. Kami akan mengganti konten default dengan kode demo lengkap nanti, tetapi pertama-tama mari bahas mengapa setiap namespace penting. + +- `Aspose.OCR` – Mesin OCR inti dan penanganan gambar. +- `Aspose.OCR.SpellCheck` – Utilitas pemeriksa ejaan yang disertakan dalam pustaka. +- `System` – Kelas dasar .NET standar (misalnya, `Console`). + +## Langkah 2: Muat Gambar dan Lakukan OCR pada Gambar + +Pekerjaan nyata pertama adalah memberi gambar ke mesin OCR. Aspose.OCR membaca banyak format (PNG, JPEG, TIFF). Berikut cuplikan kode yang melakukan pekerjaan berat: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Mengapa ini penting:** `OcrImage.FromFile` menyembunyikan detail tingkat piksel, sementara `OcrEngine.Recognize` menjalankan model neural terlatih yang menerjemahkan glif visual menjadi karakter Unicode. Properti `ocrResult.Text` kini berisi string mentah—tepat apa yang Anda butuhkan untuk **extract text from image**. + +> **Pro tip:** Jika gambar Anda berisi beberapa bahasa, Anda dapat mengatur `ocrEngine.Language = OcrLanguage.Multilingual;` sebelum memanggil `Recognize`. + +## Langkah 3: Inisialisasi Pemeriksa Ejaan Bahasa Inggris + +Aspose.OCR dilengkapi dengan mesin pemeriksa ejaan bawaan yang memahami bahasa Inggris secara langsung. Inisialisasinya hanya satu baris: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Mengapa langkah ini krusial:** Output OCR mungkin mencakup karakter yang salah dikenali (misalnya “l” vs “1”) atau typo nyata dari dokumen sumber. Pemeriksa ejaan akan memindai string, menemukan token mencurigakan, dan menyarankan alternatif. + +## Langkah 4: Deteksi Kata Salah Eja dan Dapatkan Saran Ejaan + +Sekarang kita masukkan teks OCR ke dalam pemeriksa: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` adalah koleksi di mana setiap entri berisi kata yang salah dan array kemungkinan perbaikan. + +## Langkah 5: Tampilkan Hasil + +Akhirnya, kita iterasi koleksi tersebut dan mencetak laporan yang mudah dibaca: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Output Konsol yang Diharapkan + +Dengan asumsi `letter_with_typos.png` berisi kalimat: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Menjalankan demo akan menghasilkan sesuatu seperti: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Perhatikan bagaimana setiap typo dipasangkan dengan beberapa perbaikan yang masuk akal—tepat apa yang Anda butuhkan saat membangun UI koreksi yang ramah pengguna. + +## Contoh Kerja Lengkap + +Berikut adalah program **lengkap, siap salin‑tempel**. Ganti `YOUR_DIRECTORY` dengan jalur sebenarnya ke file gambar Anda. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Kasus Tepi yang Perlu Dipertimbangkan** +> - **Gambar Kosong:** Jika mesin OCR mengembalikan string kosong, `spellChecker.Check` hanya akan mengembalikan koleksi kosong—tidak ada crash. +> - **Teks Non‑Inggris:** Ganti `OcrLanguage.English` dengan `OcrLanguage.French` (atau bahasa lain yang didukung) untuk **detect misspelled words** dalam locale lain. +> - **Dokumen Besar:** Untuk PDF multi‑halaman, Anda dapat melakukan loop pada tiap halaman, melakukan OCR, lalu menggabungkan hasil sebelum pemeriksaan ejaan. + +## Gambaran Visual (Teks Alt Gambar) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*Diagram di atas menggambarkan alur end‑to‑end: gambar → mesin OCR → teks mentah → pemeriksa ejaan → saran.* + +## Pertanyaan Umum & Pro Tips + +| Pertanyaan | Jawaban | +|------------|---------| +| **Apakah saya memerlukan koneksi internet?** | Tidak. Aspose.OCR berjalan sepenuhnya secara lokal; cocok untuk lingkungan offline atau yang memerlukan keamanan tinggi. | +| **Seberapa akurat pemeriksa ejaan?** | Menggunakan kamus sekitar 150 ribu kata bahasa Inggris dan pencocokan fuzzy, sehingga sebagian besar typo umum terdeteksi. | +| **Bisakah saya menyesuaikan kamus?** | Ya. `SpellChecker.AddUserDictionary("custom.txt")` memungkinkan Anda memuat istilah khusus domain (misalnya nama produk). | +| **Bagaimana jika gambar miring?** | Mesin OCR secara otomatis mendeteksi orientasi, tetapi Anda dapat memanggil secara manual `ocrEngine.ImagePreprocessing.Rotate(angle)` untuk kasus yang sulit. | +| **Apakah ada cara menyorot saran di UI?** | Setelah Anda memiliki koleksi `misspellings`, Anda dapat memetakan setiap `entry.Word` kembali ke posisinya di `ocrResult.Text` dan menggarisbawahi di RichTextBox atau tampilan web. | + +## Kesimpulan + +Kami baru saja menunjukkan **how to perform OCR on image**, **extract text from image**, dan kemudian **detect misspelled words** sambil **getting spelling suggestions**—semua dengan aplikasi konsol C# yang ringkas. Ide dasarnya sederhana: biarkan Aspose.OCR menangani pengenalan karakter, lalu biarkan pemeriksa ejaan bawaan membersihkan outputnya. Dari sini Anda dapat mengembangkan demo menjadi layanan pemrosesan dokumen lengkap, mengintegrasikannya dengan API web, atau menambahkannya ke editor desktop. + +Siap untuk langkah selanjutnya? Coba ganti bahasa ke Spanyol, beri PDF multi‑halaman, atau bangun front‑end WPF kecil yang memungkinkan pengguna mengklik kata untuk menerima saran. Blok‑blok bangunan sudah tersedia—terus bereksperimen. + +Jika Anda mengalami kendala atau memiliki ide untuk ekstensi, tinggalkan komentar di bawah. Selamat coding! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/indonesian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..0ec8c8112 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-03 +description: Lakukan OCR pada gambar menggunakan Aspose OCR di C#. Pelajari cara memuat + gambar untuk OCR dan mengekstrak teks Hindi dari gambar secara offline dengan kode + langkah demi langkah. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: id +og_description: Lakukan OCR pada gambar dengan Aspose OCR di C#. Tutorial ini menunjukkan + cara memuat gambar untuk OCR dan mengekstrak teks Hindi dari gambar secara offline, + lengkap dengan kode yang dapat dijalankan. +og_title: Lakukan OCR pada Gambar – Panduan Aspose OCR Hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Lakukan OCR pada Gambar dengan Aspose OCR – Panduan Bahasa Hindi +url: /id/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lakukan OCR pada Gambar dengan Aspose OCR – Panduan Bahasa Hindi + +Pernah perlu **melakukan OCR pada file gambar** tetapi terhambat cara mendapatkan karakter Hindi darinya? Anda tidak sendirian—banyak pengembang mengalami hal yang sama saat pertama kali mencoba membaca skrip non‑Latin. Kabar baiknya, Aspose OCR membuatnya cukup mudah, dan Anda bahkan dapat melakukannya sepenuhnya secara offline. + +Dalam panduan ini kita akan **memuat gambar untuk OCR**, mengarahkan mesin ke paket bahasa offline Anda, dan akhirnya **mengekstrak teks Hindi dari gambar** tanpa pernah menyentuh internet. Pada akhir tutorial Anda akan memiliki aplikasi konsol C# siap‑jalankan yang membaca struk berbahasa Hindi dan mencetak teksnya ke konsol. + +## Apa yang Anda Butuhkan + +- **.NET 6.0** atau lebih baru (kode ini juga bekerja pada .NET Framework 4.7+) +- Paket NuGet **Aspose.OCR for .NET** + `dotnet add package Aspose.OCR` +- Sebuah folder yang berisi **sumber daya bahasa Hindi offline** (unduh dari portal Aspose) +- Sebuah file gambar dengan teks Hindi, misalnya `receipt_hindi.png` + +Itu saja—tanpa layanan eksternal, tanpa kunci API, hanya kode langsung. + +## Lakukan OCR pada Gambar – Implementasi Langkah‑per‑Langkah + +Berikut kami membagi proses menjadi tujuh langkah jelas. Setiap langkah dijelaskan **mengapa** penting, bukan hanya **apa** yang harus diketik. + +### Langkah 1: Buat Instance OCR Engine + +Mesin adalah inti dari Aspose OCR. Menginstansiasinya memberi Anda akses ke semua pengaturan yang akan Anda ubah nanti. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Mengapa?** +> Tanpa `OcrEngine` Anda tidak memiliki objek untuk memanggil `Recognize`. Anggap saja ini sebagai “kamera” yang nanti akan memindai gambar Anda. + +### Langkah 2: Arahkan Mesin ke Sumber Daya Offline + +Aspose menyediakan paket bahasa yang dapat Anda simpan secara lokal. Menetapkan `ResourcesFolder` memberi tahu mesin ke mana harus mencari. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tip:** +> Gunakan path absolut selama pengembangan, kemudian beralih ke path relatif atau pengaturan konfigurasi untuk produksi. + +### Langkah 3: Paksa Mode Offline + +Anda mungkin bertanya, “Apakah saya benar‑benar perlu menonaktifkan pencarian online?” +Jika Anda bekerja di belakang firewall atau hanya menginginkan hasil yang deterministik, setel `UseOfflineResources` ke `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> Membiarkan flag ini `false` dapat menyebabkan mesin mengunduh data tambahan, yang menambah latensi dan mungkin melanggar kebijakan keamanan. + +### Langkah 4: Pilih Hindi sebagai Bahasa Pengakuan + +Di sini kami **mengekstrak teks Hindi dari gambar** dengan memberi tahu mesin bahasa apa yang diharapkan. Ini secara dramatis meningkatkan akurasi. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Mengapa membantu:** +> Mesin OCR menggunakan model karakter spesifik bahasa. Dengan mengunci pada Hindi, Anda menghindari mesin menebak di antara puluhan skrip. + +### Langkah 5: Muat Gambar untuk OCR + +Sekarang kami benar‑benar **memuat gambar untuk OCR**. Metode `OcrImage.FromFile` membaca bitmap ke dalam format yang dipahami mesin. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Jebakan umum:** +> Menyediakan path dengan garis miring maju pada Windows memang bekerja, tetapi menggunakan `Path.Combine` membuat kode Anda platform‑agnostik. + +### Langkah 6: Jalankan Pengakuan + +Setelah semua disiapkan, kami akhirnya **melakukan OCR pada gambar** dengan memanggil `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Apa yang terjadi?** +> Mesin memindai setiap piksel, mencocokkan pola dengan basis data glif Hindi, dan membangun string karakter Unicode. + +### Langkah 7: Keluarkan Teks yang Diakui + +Objek hasil berisi properti `Text` yang menyimpan string yang diekstrak. Kami cukup menuliskannya ke konsol. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Output yang diharapkan:** +> Jika `receipt_hindi.png` berisi “भुगतान सफल”, konsol akan mencetak tepat baris itu, mempertahankan diakritik. + +## Muat Gambar untuk OCR – Menyiapkan Sumber Daya + +Jika Anda bertanya-tanya apakah dapat memberi mesin aliran (stream) alih‑alih file, jawabannya ya. Ganti `OcrImage.FromFile` dengan: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Mengapa menggunakan stream?** +> Stream memungkinkan Anda bekerja dengan gambar yang disimpan di basis data, blob cloud, atau sumber daya tersemat—sempurna untuk layanan yang skalabel. + +## Ekstrak Teks Hindi dari Gambar – Menangani Kasus Edge + +1. **Paket bahasa tidak ditemukan** – Jika paket Hindi tidak ditemukan, `Recognize` akan melempar pengecualian. Bungkus pemanggilan dalam try/catch dan log pesan yang ramah. +2. **Gambar beresolusi rendah** – Akurasi OCR turun di bawah 300 dpi. Praproses gambar (ubah ukuran, tajamkan) sebelum memuat. +3. **Dokumen multibahasa** – Anda dapat mengaktifkan beberapa bahasa: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Penyesuaian ini memastikan rutinitas **melakukan OCR pada gambar** tetap kuat dalam produksi. + +## Menjalankan Contoh Lengkap + +Simpan file berikut sebagai `Program.cs`, ganti path placeholder, dan jalankan: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Saat Anda mengeksekusi `dotnet run`, Anda akan melihat sesuatu seperti: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Jika Anda mendapatkan string kosong, periksa kembali bahwa **ResourcesFolder** mengarah ke folder yang berisi `Hindi.traineddata` dan bahwa gambar cukup jelas. + +## Kesimpulan + +Kami telah menelusuri cara **melakukan OCR pada file gambar** dengan Aspose OCR, mencakup semua hal mulai dari **memuat gambar untuk OCR** hingga **mengekstrak teks Hindi dari gambar** dalam skenario sepenuhnya offline. Kode lengkap yang dapat dijalankan di atas memberi Anda fondasi yang solid, dan tip tentang stream, penanganan error, serta dukungan multibahasa akan membantu Anda menyesuaikan solusi untuk proyek dunia nyata. + +Siap untuk langkah berikutnya? Coba ganti bahasa ke **OcrLanguage.Tamil** atau beri gambar dari penyimpanan Azure Blob. Anda juga dapat bereksperimen dengan pengaturan `ImagePreprocessing` untuk meningkatkan akurasi pada struk yang berisik. + +Ada pertanyaan atau menemukan kendala? Tinggalkan komentar—selamat coding! + +![Perform OCR on image example + + +## Apa yang Harus Anda Pelajari Selanjutnya? + + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber daya menyertakan contoh kode lengkap yang berfungsi dengan penjelasan langkah‑per‑langkah untuk membantu Anda menguasai fitur API tambahan dan menjelajahi pendekatan implementasi alternatif dalam proyek Anda. + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/indonesian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..b0e751df6 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-03 +description: Lakukan OCR pada PDF dan konversi PDF yang dipindai menjadi PDF yang + dapat dicari menggunakan Aspose.OCR. Pelajari cara mengenali teks dari PDF dan membuat + PDF yang dapat dicari dalam hitungan menit. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: id +og_description: Lakukan OCR pada PDF dan segera buat PDF yang dapat dicari. Tutorial + ini menunjukkan langkah demi langkah cara mengenali teks dari PDF menggunakan Aspose.OCR. +og_title: Lakukan OCR pada PDF – Panduan Lengkap C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Lakukan OCR pada PDF dengan Aspose.OCR – Panduan Lengkap C# +url: /id/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lakukan OCR pada PDF dengan Aspose.OCR – Panduan Lengkap C# + +Pernah bertanya‑tanya **bagaimana cara melakukan OCR pada PDF** tanpa harus berurusan dengan puluhan alat baris perintah? Anda tidak sendirian. Baik Anda sedang mendigitalkan faktur, mengarsipkan laporan lama, atau hanya membutuhkan versi yang dapat dicari dari kontrak yang dipindai, mengubah PDF statis menjadi sesuatu yang dapat Anda cari memang mengubah permainan. + +Dalam panduan ini kami akan menunjukkan **cara membuat file PDF yang dapat dicari** dari PDF yang dipindai (bahkan dari gambar biasa) menggunakan Aspose.OCR untuk .NET. Pada akhir tutorial Anda akan dapat **mengenali teks dari PDF** dengan beberapa baris kode C#, dan Anda akan memahami alasan di balik setiap langkah sehingga Anda dapat menyesuaikan solusi ini untuk proyek Anda sendiri. + +> **Intisari cepat:** Seluruh proses dapat diringkas menjadi tiga hal—menginisialisasi mesin OCR, memberi sumber (PDF atau gambar), dan menyimpan output PDF yang dapat dicari. Mari kita mulai. + +--- + +## Apa yang Anda Butuhkan + +Sebelum kita mulai, pastikan Anda memiliki: + +| Prasyarat | Mengapa penting | +|--------------|----------------| +| **.NET 6.0+** (atau .NET Framework 4.6+) | Aspose.OCR menargetkan runtime modern; versi lama mungkin kehilangan pembaruan API. | +| **Aspose.OCR for .NET** paket NuGet | Menyediakan kelas `OcrEngine` dan utilitas penanganan PDF. | +| **Lisensi Aspose yang valid** (atau gunakan evaluasi gratis) | Tanpa lisensi Anda akan terkena batas evaluasi 30 hari dan watermark. | +| **PDF yang dipindai** (atau file gambar) yang ingin Anda jadikan dapat dicari | Ini adalah dokumen sumber untuk OCR. | +| **Visual Studio 2022** (atau editor C# apa saja) | Mempermudah debugging, namun IDE apa pun dapat digunakan. | + +Anda dapat menginstal pustaka dengan perintah NuGet berikut: + +```bash +dotnet add package Aspose.OCR +``` + +> **Tips pro:** Jika Anda bekerja pada pipeline CI, tambahkan file lisensi ke artefak build dan muat di runtime untuk menghindari penulisan jalur secara keras. + +--- + +## Lakukan OCR pada PDF – Menyiapkan Aspose.OCR + +Hal pertama yang kita perlukan adalah instance `OcrEngine` yang baru. Anggap saja ini sebagai otak yang akan membaca dokumen Anda. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Mengapa membuat instance baru setiap kali? Mesin menyimpan konfigurasi (seperti pengaturan bahasa) yang dapat berbeda per dokumen. Membuatnya per‑run menjamin keadaan bersih dan menghindari tumpang‑tindih antar pekerjaan. + +--- + +## Cara Membuat PDF yang Dapat Dicari – Mengonfigurasi Kata Sandi (Opsional) + +Jika PDF Anda dilindungi, Anda harus memberi tahu mesin kata sandinya sebelum dapat membaca halaman: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Melewatkan langkah ini pada file yang dilindungi akan memunculkan `PdfPasswordException`. Selalu bungkus dengan try‑catch jika Anda tidak yakin tentang status perlindungan. + +--- + +## Mengonversi PDF yang Dipindai menjadi PDF yang Dapat Dicari – Memuat Sumber + +Aspose.OCR bekerja dengan abstraksi `OcrImage`, yang dapat membungkus PDF, TIFF, JPEG, dll. Berikut cara memuat PDF yang dipindai ke memori: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Di balik layar, `FromFile` mengurai setiap halaman menjadi gambar raster yang dapat diproses mesin OCR. Jika Anda memiliki PDF multi‑halaman, mesin akan secara otomatis iterasi setiap halaman. + +--- + +## Mengenali Teks dari PDF – Melakukan OCR + +Sekarang inti tutorial: memerintahkan mesin untuk mengenali teks dan menghasilkan PDF yang dapat dicari. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` memberi tahu mesin untuk menyematkan lapisan teks tak terlihat di atas gambar hasil pindai. PDF yang dihasilkan tetap mempertahankan kesetiaan visual pemindaian sekaligus menjadi sepenuhnya dapat dicari—tepat apa yang Anda butuhkan untuk audit kepatuhan. + +--- + +## Mengonversi Gambar menjadi PDF yang Dapat Dicari – Menyimpan Hasil + +Akhirnya, tulis data biner ke disk: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Properti `Binary` menyimpan byte PDF mentah. Anda juga dapat langsung mengalirkannya ke respons web jika Anda membangun API. + +--- + +![Diagram yang menunjukkan alur konversi OCR untuk membuat PDF yang dapat dicari](https://example.com/ocr-flow.png "Diagram alur Lakukan OCR pada PDF") + +*Teks alt gambar: Diagram alur Lakukan OCR pada PDF yang menggambarkan bagaimana PDF yang dipindai diubah menjadi PDF yang dapat dicari.* + +--- + +## Kasus Khusus & Tips Praktis + +### 1. File Besar & Manajemen Memori +Jika Anda memproses PDF berukuran lebih dari 100 MB, pertimbangkan menggunakan `OcrEngineSettings.MemoryLimit` untuk membatasi penggunaan memori. Selain itu, proses halaman dalam batch untuk menghindari `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Dukungan Bahasa +Secara default Aspose.OCR mengasumsikan bahasa Inggris. Untuk mengenali bahasa lain, atur properti `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Skenario Multi‑Thread +`OcrEngine` **tidak** thread‑safe. Jika Anda memerlukan pemrosesan paralel, buat mesin terpisah per thread. + +### 4. Debugging Akurasi OCR +Anda dapat mengekstrak teks polos dari `ocrResult` untuk keperluan debugging: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Jika output terlihat berantakan, coba ubah `PreprocessSettings` (misalnya deskew, despeckle) untuk meningkatkan kualitas. + +### 5. Gotchas Lisensi +Saat Anda menjalankan versi evaluasi, Aspose menambahkan watermark pada PDF output. Daftarkan lisensi Anda di awal aplikasi: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Contoh Lengkap yang Siap Jalan – Dari Awal hingga Selesai + +Berikut adalah program lengkap yang siap dijalankan dan mencakup semua tips di atas. Silakan salin‑tempel ke proyek konsol baru. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Output yang diharapkan:** Setelah dijalankan, Anda akan melihat baris konsol yang mengonfirmasi lokasi file. Buka `output.pdf` di penampil PDF apa saja; coba ketik kata yang Anda tahu ada di pemindaian asli. Jika teksnya disorot, Anda telah berhasil **melakukan OCR pada PDF** dan membuat dokumen yang dapat dicari. + +--- + +## Pertanyaan yang Sering Diajukan + +**T: Bisakah saya menggunakan ini untuk mengonversi satu gambar (PNG/JPEG) menjadi PDF yang dapat dicari?** +J: Tentu saja. Ganti `OcrImage.FromFile("input.pdf")` dengan jalur ke file gambar Anda. Mesin akan meraster gambar dan menyematkan lapisan OCR dengan cara yang sama. + +**T: Bagaimana jika PDF saya memiliki halaman yang dipindai dan teks asli?** +J: Mesin akan menumpangkan teks OCR di atas konten yang ada, sehingga teks asli tetap dapat dipilih sementara halaman yang dipindai menjadi dapat dicari. + +**T: Seberapa akurat OCR ini?** +J: Akurasi bergantung pada kualitas sumber. Pemindaian bersih dengan resolusi tinggi (>300 dpi) memberikan akurasi >95 %. Untuk dokumen berisik, aktifkan `PreprocessSettings` (deskew, despeckle) sebelum memanggil `Recognize`. + +--- + +## Langkah Selanjutnya – Memperluas Toolkit OCR Anda + +Sekarang Anda dapat **mengenali teks dari PDF** dan **mengonversi PDF yang dipindai menjadi PDF yang dapat dicari**, pertimbangkan topik lanjutan berikut: + +- **Pemrosesan batch**: Loop melalui folder PDF dan hasilkan versi yang dapat dicari secara otomatis. +- **Ekstraksi teks**: Gunakan `ocrResult.Text` untuk mengisi indeks pencarian (misalnya Elasticsearch). +- **Paket bahasa khusus**: Unduh data bahasa tambahan dari Aspose untuk mendukung skrip Asia. +- **Kepatuhan PDF/A**: Gabungkan Aspose.PDF dengan output OCR untuk membuat PDF siap arsip. + +Masing‑masing topik ini membangun di atas langkah inti yang telah kami bahas, sehingga Anda siap memperluas solusi Anda. + +--- + +## Penutup + +Kami baru saja menunjukkan **cara melakukan OCR pada PDF** menggunakan Aspose.OCR, mengubah PDF yang dipindai menjadi PDF yang sepenuhnya dapat dicari, dan bahkan membahas cara mengonversi gambar biasa menjadi PDF yang dapat dicari. Kode + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber menyertakan contoh kode lengkap dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/indonesian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..ef293064e --- /dev/null +++ b/ocr/indonesian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial OCR subtitle video yang menunjukkan cara mengekstrak frame dari + video dan membaca teks dari file video seperti MP4 menggunakan Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: id +og_description: Pelajari OCR subtitle video dengan Aspose.OCR. Ekstrak frame dari + video, baca teks dari video, dan ekstrak teks dari MP4 dalam beberapa menit. +og_title: OCR Subtitle Video di C# – Panduan Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR Subtitle Video di C# – Panduan Lengkap +url: /id/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Subtitle Video dalam C# – Panduan Lengkap + +Pernah membutuhkan **video subtitle ocr** tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian. Baik Anda sedang mendigitalkan rekaman kuliah, mengambil caption dari video pelatihan, atau hanya penasaran tentang membaca teks dari video, tutorial ini menunjukkan secara tepat cara melakukannya dengan C# dan Aspose.OCR. + +Dalam beberapa menit ke depan kita akan mengekstrak frame dari video, menjalankan OCR pada frame tersebut, dan akhirnya menampilkan teks subtitle frame‑per‑frame. Pada akhir tutorial Anda akan dapat **membaca teks dari video** file—termasuk MP4—tanpa mencari alat pihak ketiga. + +## Apa yang Akan Anda Bangun + +Kami akan membuat aplikasi konsol kecil yang: + +1. Mendekode MP4 (atau format lain yang didukung) menjadi frame `Bitmap` individual. +2. Membatasi wilayah OCR ke pita subtitle sehingga mesin tidak terganggu oleh seluruh gambar. +3. Memproses setiap frame dengan `VideoOcrProcessor` milik Aspose. +4. Mencetak teks subtitle yang dikenali ke konsol. + +Tidak ada embel‑embel, hanya contoh end‑to‑end yang berfungsi yang dapat Anda masukkan ke dalam proyek nyata. + +## Prasyarat + +- **.NET 6.0** atau lebih baru (kode ini juga berfungsi pada .NET Framework 4.7+). +- **Aspose.OCR for .NET** – instal melalui NuGet: `Install-Package Aspose.OCR`. +- Sebuah file video (MP4 sangat cocok). +- Sebuah cara untuk mendekode frame video – demo ini menggunakan metode placeholder, tetapi Anda dapat mengganti dengan FFmpeg, OpenCV, atau perpustakaan apa pun yang mengembalikan objek `Bitmap`. + +> Pro tip: Jika Anda menggunakan Windows, paket `System.Drawing.Common` berfungsi baik untuk `Bitmap`. Pada Linux/macOS Anda memerlukan dependensi native `libgdiplus`. + +## Langkah 1 – Ekstrak Frame dari Video + +The first hurdle is turning a moving picture into still images. The method `GetVideoFrames` below is deliberately left blank; replace it with your favourite decoder. Here’s a quick sketch using FFmpeg‑Core (just to illustrate the shape of the data): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Mengapa ini penting:** Mengekstrak frame memberikan mesin OCR gambar statis untuk diproses, yang secara dramatis meningkatkan akurasi dibandingkan mencoba membaca langsung dari aliran video. + +## Langkah 2 – Siapkan VideoOcrProcessor + +Now that we have a sequence of `Bitmap` objects, we can hand them to Aspose.OCR. The `VideoOcrProcessor` lets us define a **Region of Interest (ROI)** – perfect for subtitles that usually sit at the top or bottom of the frame. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Mengapa membatasi ROI?** Dengan mengabaikan bagian gambar lainnya kita mengurangi noise, mempercepat waktu pemrosesan, dan menghindari hasil positif palsu dari grafik latar belakang. + +## Langkah 3 – Jalankan OCR pada Urutan Frame + +With the processor ready, feeding the frames is a one‑liner. The `Process` method returns an enumerable of `OcrResult` objects, each containing the recognized text for its corresponding frame. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Apa yang terjadi di balik layar?** Aspose.OCR secara internal menormalkan setiap bitmap, menjalankan pengenalan berbasis jaringan saraf, dan kemudian memproses hasilnya untuk memperbaiki tanda baca dan pemisahan baris. + +## Langkah 4 – Tampilkan Teks yang Diekstrak + +Finally, we iterate over the results and print each subtitle line. You could also write them to a SRT file, a database, or feed them into a translation service. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Contoh Lengkap yang Berfungsi + +Putting everything together yields a self‑contained console program: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Output yang diharapkan (contoh)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Jika OCR kesulitan dengan frame tertentu, Anda akan melihat string kosong – itu menjadi petunjuk untuk menyesuaikan ROI atau meningkatkan laju ekstraksi frame. + +## Kesalahan Umum & Cara Memperbaikinya + +| Issue | Why it Happens | Fix | +|-------|----------------|-----| +| **Karakter sampah** | Frame beresolusi rendah atau kompresi berat | Ekstrak frame dengan bitrate lebih tinggi, atau tingkatkan ukuran bitmap sebelum OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **Tidak ada teks yang dikembalikan** | ROI tidak benar‑benar mencakup pita subtitle | Verifikasi koordinat persegi panjang (gunakan alat screenshot untuk mengukurnya). | +| **Bottleneck kinerja** | Memproses setiap frame pada 30 fps terlalu berlebihan | Turunkan sampel menjadi 1‑2 fps untuk kebanyakan aliran subtitle; Anda masih dapat menangkap setiap perubahan subtitle. | +| **FFmpeg tidak ditemukan** | `ffmpeg.exe` tidak ada di `PATH` | Berikan path lengkap di `ProcessStartInfo.FileName` atau instal FFmpeg secara global. | + +## Memperluas Solusi + +- **Export to SRT** – gabungkan timestamp dengan teks OCR dan tulis file SubRip. +- **Multi‑language support** – set `ocrProcessor.Language = OcrLanguage.Spanish` (atau bahasa lain yang didukung). +- **Real‑time processing** – alirkan frame langsung dari streaming live alih‑alih membaca dari disk. + +Semua variasi ini masih berpusat pada ide inti **mengekstrak frame dari video**, **membaca teks dari video**, dan **mengekstrak teks dari mp4**. + +## Kesimpulan + +Kami baru saja melewati alur kerja **video subtitle ocr** lengkap dalam C#. Dengan mengekstrak frame dari video, memfokuskan OCR pada pita subtitle, dan mengiterasi hasilnya, Anda dapat secara andal **membaca teks dari video** file seperti MP4. Kode siap untuk disalin‑tempel, dan desain modular memungkinkan Anda mengganti decoder frame apa pun yang Anda sukai. + +Langkah selanjutnya? Cobalah mengekspor hasil ke file SRT, bereksperimen dengan ukuran ROI yang berbeda, atau mengirim subtitle ke API terjemahan untuk caption multibahasa. Langit adalah batasnya setelah Anda menguasai dasar‑dasar mengekstrak teks dari video. + +Selamat coding, dan semoga subtitle Anda selalu jernih! + +## Apa yang Harus Anda Pelajari Selanjutnya? + +Tutorial berikut mencakup topik yang sangat terkait yang membangun teknik yang ditunjukkan dalam panduan ini. Setiap sumber mencakup contoh kode lengkap yang berfungsi dengan penjelasan langkah‑demi‑langkah untuk membantu Anda menguasai fitur API tambahan dan mengeksplorasi pendekatan implementasi alternatif dalam proyek Anda. + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Ekstrak Teks dari Gambar Menggunakan Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Ekstrak Teks dari Gambar – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/ocr-configuration/_index.md b/ocr/italian/net/ocr-configuration/_index.md index 446a1b5b8..03cb9b0fb 100644 --- a/ocr/italian/net/ocr-configuration/_index.md +++ b/ocr/italian/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Sblocca la potenza del riconoscimento OCR delle immagini in .NET con Aspose.OCR. Sblocca potenti capacità OCR con Aspose.OCR per .NET. Estrai testo da immagini in modo fluido. ### [OCROperation con Lista nel Riconoscimento OCR delle Immagini](./ocr-operation-with-list/) Sblocca il potenziale di Aspose.OCR per .NET. Esegui senza sforzo il riconoscimento OCR delle immagini con le liste. Aumenta la produttività e l'estrazione dei dati nelle tue applicazioni. +### [Ottieni la versione di Aspose OCR in C# – Guida completa](./get-aspose-ocr-version-in-c-complete-guide/) +Scopri come ottenere la versione corrente di Aspose.OCR in C# e verificare l'installazione nella tua applicazione. ### Casi d'uso comuni - **Estrarre testo da immagini** di fatture scannerizzate per la contabilità automatizzata. @@ -100,4 +102,4 @@ R: Sì, l'oggetto `OcrResult` fornisce valori di confidenza che puoi ispezionare {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/italian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..515c80068 --- /dev/null +++ b/ocr/italian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-03 +description: Ottieni la versione di Aspose OCR in C# con un semplice snippet. Scopri + come recuperare la versione della libreria Aspose OCR usando OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: it +og_description: Ottieni rapidamente la versione di Aspose OCR in C#. Questo tutorial + mostra esattamente come recuperare la versione della libreria Aspose OCR utilizzando + OcrEngine GetVersion. +og_title: Ottieni la versione di Aspose OCR in C# – Guida completa +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Ottieni la versione Aspose OCR in C# – Guida completa +url: /it/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ottieni la versione di Aspose OCR in C# – Guida completa + +Ti sei mai chiesto come **ottenere la versione di Aspose OCR** all'interno del tuo progetto .NET? Forse stai risolvendo un'incongruenza, o vuoi semplicemente registrare la build esatta della libreria in esecuzione in produzione. Qualunque sia il motivo, sei nel posto giusto. + +In questo tutorial vedremo un piccolo programma C# autonomo che chiama `OcrEngine.GetVersion()` e stampa il risultato. Alla fine saprai non solo *come* recuperare la versione, ma anche *perché* controllare la versione può evitarti mal di testa quando aggiorni la **libreria Aspose OCR**. + +## Cosa imparerai + +- Aggiungere il pacchetto NuGet Aspose.OCR a un progetto C# +- Utilizzare il metodo `OcrEngine.GetVersion()` (il punto di ingresso **ocrengine getversion**) +- Gestire le possibili eccezioni e verificare l'output +- Estendere lo snippet per scenari reali come il logging o i toggle di funzionalità condizionali + +Non è necessaria alcuna esperienza pregressa con l'OCR—basta una conoscenza di base di C# e Visual Studio (o del tuo IDE preferito). Iniziamo. + +--- + +## Passo 1: Configura il progetto e includi la libreria Aspose OCR + +Prima di poter chiamare qualsiasi API legata all'OCR, devi avere la **libreria Aspose OCR** referenziata nel tuo progetto. + +1. Apri un terminale o la Console di Gestione Pacchetti in Visual Studio. +2. Esegui il comando seguente per installare l'ultima versione stabile: + +```bash +dotnet add package Aspose.OCR +``` + +> **Suggerimento professionale:** Se il tuo target è .NET Framework anziché .NET Core, usa l'interfaccia UI di NuGet Package Manager e scegli la versione che corrisponde al tuo runtime. Il pacchetto include la classe `OcrEngine` che utilizzeremo più avanti. + +### Perché è importante + +Quando installi il pacchetto, la versione dell'assembly sul disco può differire dalla versione riportata dalla libreria a runtime. Interrogare la versione tramite codice garantisce che tu legga la build esatta caricata dal CLR, cosa cruciale per il debug e per gli audit di conformità. + +--- + +## Passo 2: Scrivi il codice minimo per **ottenere la versione di Aspose OCR** + +Crea una nuova console app (`dotnet new console -n OcrVersionDemo`) e sostituisci il file `Program.cs` predefinito con il seguente: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Spiegazione di ciascuna parte** + +- `using Aspose.OCR;` importa lo spazio dei nomi OCR, permettendoci di chiamare `OcrEngine`. +- `OcrEngine.GetVersion()` è il metodo statico **ocrengine getversion** che restituisce una stringa tipo `"24.5.7"`. +- Avvolgere la chiamata in un blocco `try/catch` ti protegge da sorprese a runtime—ad esempio, se le librerie native non vengono trovate sulla macchina di destinazione. +- La stringa interpolata `$"Aspose OCR version: {version}"` stampa una riga chiara e leggibile. + +### Output previsto + +Quando esegui `dotnet run` nella cartella del progetto, dovresti vedere qualcosa di simile a: + +``` +Aspose OCR version: 24.5.7 +``` + +Se la libreria non può essere caricata, il ramo di errore stamperà un messaggio conciso, aiutandoti a individuare rapidamente il problema. + +--- + +## Passo 3: Verifica che la versione corrisponda al tuo pacchetto NuGet + +È facile presumere che la versione NuGet installata sia quella usata a runtime, ma le particolarità dell'ambiente possono interferire. Per ricontrollare: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Eseguendo questo snippet aggiuntivo verrà stampato qualcosa di simile a: + +``` +Assembly file version: 24.5.7.0 +``` + +Se i due valori differiscono, potresti star caricando una DLL più vecchia dalla Global Assembly Cache (GAC) o da una cartella di build precedente. In tal caso, pulisci la soluzione (`dotnet clean`) e ricompila. + +--- + +## Passo 4: Inserisci il controllo della versione nei log di produzione + +La maggior parte delle applicazioni reali non si limita a stampare sulla console; scrivono su un file di log o su un sistema di telemetria. Ecco un rapido esempio che utilizza `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Ora la versione appare nei tuoi log strutturati, rendendo più facile filtrare per `{Version}` in seguito. Questo modello è particolarmente utile quando hai più micro‑servizi, ognuno dei quali può caricare una DLL OCR potenzialmente diversa. + +--- + +## Domande comuni e casi particolari + +### Cosa succede se `GetVersion()` restituisce una stringa vuota? + +Di solito indica un'installazione corrotta o una dipendenza nativa mancante. Re‑installa il pacchetto NuGet e verifica che `Aspose.OCR.Native.dll` (o il binario specifico per la piattaforma) sia presente accanto all'eseguibile. + +### Il metodo funziona su .NET Core 2.0? + +Sì, **Aspose OCR** supporta .NET Standard 2.0 e versioni successive, quindi qualsiasi versione di .NET Core che implementa quello standard può chiamare `OcrEngine.GetVersion()`. Assicurati solo di riferire gli identificatori di runtime corretti (`win-x64`, `linux-x64`, ecc.) se pubblichi un'app auto‑contenuta. + +### Posso recuperare la versione senza un file di licenza? + +Assolutamente. `GetVersion()` **non** richiede una licenza; restituisce semplicemente il numero di build della libreria. Tuttavia, se tenti di eseguire OCR senza una licenza valida, otterrai un'eccezione a runtime. Ecco perché il `try/catch` nel nostro snippet è utile—isolando il controllo della versione dal flusso di esecuzione OCR. + +--- + +## Esempio completo funzionante (pronto per copia‑incolla) + +Di seguito trovi l'intero programma, pronto per essere inserito in un nuovo progetto console. Include il blocco di logging opzionale, così potrai vedere sia l'output console sia i log strutturati in azione. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Eseguilo con `dotnet run` e vedrai due righe che confermano la versione, più una riga di debug se abiliti `LogLevel.Debug`. + +--- + +## Conclusione + +Abbiamo coperto tutto ciò che serve per **ottenere la versione di Aspose OCR** in un ambiente C#—dall'installazione della **libreria Aspose OCR**, alla chiamata del metodo **ocrengine getversion**, alla gestione degli errori, fino all'integrazione del risultato in un logging di livello produzione. Con queste conoscenze potrai verificare in modo affidabile la build OCR esatta usata dalla tua applicazione, evitare bug legati alle versioni e soddisfare i requisiti di conformità senza sforzi. + +Prossimi passi? Prova ad accoppiare questo controllo della versione con una chiamata OCR reale (`OcrEngine` → `RecognizeImage`) e registra sia la versione sia il risultato del riconoscimento. Potresti anche esplorare il pattern **retrieve aspose version** per altri prodotti Aspose (PDF, Slides, Cells) per mantenere sincronizzata l'intera suite. + +Buona programmazione, e che le tue pipeline OCR rimangano affilate! + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/italian/net/ocr-optimization/_index.md index 483493b48..7a934e919 100644 --- a/ocr/italian/net/ocr-optimization/_index.md +++ b/ocr/italian/net/ocr-optimization/_index.md @@ -51,7 +51,7 @@ Sei pronto a liberare tutto il potenziale di Aspose.OCR per .NET? La nostra guid Migliora la precisione dell'OCR con Aspose.OCR per .NET esplorando i [filtri di pre‑elaborazione](./preprocessing-filters-for-image/). Scarica ora e scopri come perfezionare le tue immagini prima del riconoscimento. Questo tutorial garantisce un'integrazione fluida, aumentando precisione ed efficienza. ## Correzione dei Risultati con Controllo Ortografico in Riconoscimento Immagine OCR -Raggiungi una precisione OCR senza pari con [Aspose.OCR per .NET](./result-correction-with-spell-checking/). Il nostro tutorial sulla correzione dei risultati con il controllo ortografico ti consente di personalizzare i dizionari, correggere gli errori di ortografia e garantire un riconoscimento del testo privo di errori senza sforzo. Immergiti in un mondo di precisione con Aspose.OCR. +Raggiungi una precisione OCR senza pari con [Aspose.OCR per .NET](./result-correction-with-spell-checking/). Il nostro tutorial sulla correzione dei risultati con il controllo ortografico ti consente di personalizzare i dizionari, correggere gli errori di ortografia e garantire un riconoscimento del testo privo di errori senza sforzo. Immergiti in un mondo di precisione con Aspose.OCR per .NET. ## Salva Risultato Multipagina come Documento in Riconoscimento Immagine OCR Salva senza sforzo i risultati OCR multipagina come documenti con Aspose.OCR per .NET. La nostra [guida passo‑passo](./save-multipage-result-as-document/) sblocca il pieno potenziale della creazione di documenti. Integra perfettamente Aspose.OCR e trasforma i tuoi risultati OCR in documenti multipagina con facilità. @@ -69,6 +69,8 @@ Esplora Aspose.OCR per .NET. Migliora la precisione dell'OCR con i filtri di pre Migliora la precisione dell'OCR con Aspose.OCR per .NET. Correggi le ortografie, personalizza i dizionari e ottieni un riconoscimento del testo privo di errori senza sforzo. ### [Salva Risultato Multipagina come Documento in Riconoscimento Immagine OCR](./save-multipage-result-as-document/) Sblocca il potenziale di Aspose.OCR per .NET. Salva senza sforzo i risultati OCR multipagina come documenti con questa guida completa passo‑passo. +### [Esempio Aspose OCR C# – Abilita GPU, Imposta Limite di Memoria e Processa Immagini TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Scopri come abilitare l'accelerazione GPU, limitare la memoria e gestire file TIF con Aspose.OCR per .NET. ## Domande Frequenti diff --git a/ocr/italian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/italian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..b977911ff --- /dev/null +++ b/ocr/italian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-03 +description: Esempio Aspose OCR C# che mostra come impostare il limite di memoria + GPU, caricare l’immagine per l’OCR e riconoscere il testo da file TIF con codice + completo e suggerimenti. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: it +og_description: 'Scopri un esempio completo di Aspose OCR in C#: abilita la GPU, imposta + il limite di memoria della GPU, carica un''immagine per l''OCR e riconosci il testo + dai file TIF. Codice completo incluso.' +og_title: Esempio Aspose OCR C# – Accelerazione GPU, Limite di Memoria e Elaborazione + TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Esempio Aspose OCR C# – Abilita GPU, Imposta Limite di Memoria e Processa Immagini + TIF +url: /it/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esempio Aspose OCR C# – Abilita GPU, Imposta Limite di Memoria e Processa Immagini TIF + +Ti sei mai chiesto come estrarre il massimo delle prestazioni dal **esempio Aspose OCR C#** quando lavori con scansioni TIFF di grandi dimensioni? Non sei l’unico. In molti progetti reali—ad esempio la digitalizzazione di archivi o l’estrazione di dati da ricevute ad alta risoluzione—il collo di bottiglia non è l’algoritmo OCR, ma l’utilizzo dell’hardware. + +Ecco la questione: Aspose OCR supporta l’accelerazione GPU, ma devi indicargli esattamente quanta memoria può utilizzare, caricare il tipo di immagine corretto e infine estrarre il testo riconosciuto da un file .tif. Questo tutorial ti guida passo passo, dall’installazione dell’Sdk alla configurazione delle impostazioni GPU, così potrai eseguire l’OCR a velocità fulminea senza saturare la RAM della GPU. + +Inseriremo anche qualche scenario “cosa succede se”—come gestire TIFF multi‑pagina o tornare alla CPU quando non è presente una GPU—perché alla fine avrai una soluzione robusta, non solo un frammento di codice isolato. + +## Cosa Ti Serve + +Prima di iniziare, assicurati di avere quanto segue sulla tua macchina: + +| Prerequisito | Perché è importante | +|--------------|----------------------| +| **.NET 6 SDK** (o successivo) | Aspose OCR mira a .NET Standard 2.0+, quindi qualsiasi versione recente di .NET funziona. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | La libreria principale che fornisce `OcrEngine`, `GpuSettings`, ecc. | +| **CUDA 11+** (NVIDIA) **o ROCm 5+** (AMD) | Necessario per l’accelerazione GPU; l’Sdk verificherà la presenza di un driver compatibile a runtime. | +| Una **GPU con almeno 2 GB VRAM** (imposteremo il limite a 2048 MB) | Senza sufficiente memoria, il motore potrebbe tornare silenziosamente alla CPU. | +| Un’immagine **TIFF ad alta risoluzione** che desideri processare | Aspose OCR può leggere praticamente qualsiasi formato raster, ma il TIF è comune per le scansioni. | +| Visual Studio 2022 (o qualsiasi editor tu preferisca) | Per compilare e fare il debug del progetto C#. | + +Se manca qualcuno di questi elementi, il codice compila comunque, ma non otterrai i guadagni di prestazioni desiderati. + +## Passo 1: Crea il Motore dell’Esempio Aspose OCR C# + +La prima cosa in ogni **esempio Aspose OCR C#** è istanziare il motore OCR. Pensa a `OcrEngine` come al regista di un film—coordina tutto, dal caricamento dell’immagine all’estrazione del testo. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Consiglio:** Se prevedi di elaborare molte immagini in sequenza, mantieni vivo un unico `OcrEngine`. Ricrearlo per ogni immagine aggiunge overhead che può superare di gran lunga il tempo di OCR. + +## Passo 2: Imposta il Limite di Memoria GPU (e Abilita l’Accelerazione) + +Ora arriva la parte che spesso crea problemi: **impostare il limite di memoria GPU**. Per impostazione predefinita Aspose OCR cercherà di usare tutta la VRAM disponibile, il che su una workstation condivisa può privare le altre applicazioni di risorse. L’oggetto `GpuSettings` ti permette di limitare l’allocazione. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Perché impostare un limite di memoria? + +- **Stabilità:** Previene crash per out‑of‑memory quando si elaborano immagini gigantesche. +- **Coesistenza:** Consente ad altre applicazioni intensive per GPU (ad es. modelli TensorFlow) di funzionare contemporaneamente. +- **Predicibilità:** Rende i test di performance ripetibili perché la GPU non inizia a fare swapping. + +Se ometti `MemoryLimitMb`, Aspose allocherebbe quanta memoria ritiene necessaria, il che può andare bene su un server dedicato all’inferenza ma è rischioso su un laptop da sviluppatore. + +## Passo 3: Carica l’Immagine per l’OCR + +Caricare il formato di file corretto è il prossimo passo cruciale. Il metodo `OcrImage.FromFile` rileva automaticamente il tipo di immagine, ma dovresti comunque verificare che il file esista e che sia una variante TIFF supportata (ad es. compressa LZW o CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Gestione dei TIFF multi‑pagina + +Se il tuo TIFF contiene più pagine, Aspose OCR leggerà solo la prima per impostazione predefinita. Per elaborare tutte le pagine, puoi iterare su `image.Pages` (disponibile nelle versioni più recenti dell’Sdk) e fornire ogni pagina al motore separatamente. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Il frammento sopra dimostra un modello **carica immagine per OCR** che funziona sia per file a pagina singola sia per file multi‑pagina. + +## Passo 4: Riconosci il Testo da TIF (o da qualsiasi raster) + +Ora che l’immagine è in memoria, chiediamo ad Aspose di fare la sua magia. Il metodo `Recognize` restituisce un `OcrResult` che contiene il testo plain, i punteggi di confidenza e persino le informazioni di bounding‑box se ti servono. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Perché funziona bene con TIF + +- **Compressione lossless:** Il TIFF spesso conserva i dati pixel grezzi, offrendo al motore OCR la massima fedeltà. +- **Spazi colore multipli:** Aspose gestisce TIFF in scala di grigi, RGB o anche CMYK senza codice di conversione aggiuntivo. + +Se devi modificare i pacchetti lingua (ad es. francese o giapponese), imposta `ocrEngine.Settings.Language = "fr"` prima di chiamare `Recognize`. + +## Passo 5: Visualizza il Testo Riconosciuto + +Infine, stampiamo il testo sulla console. In un’applicazione reale potresti scriverlo in un database, in un file JSON o passare la stringa a una pipeline NLP successiva. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Output previsto + +Eseguendo il programma su una scansione chiara a 300 dpi di una pagina stampata, tipicamente otterrai qualcosa del genere: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Se l’immagine è sfocata o il limite di memoria GPU è troppo basso, potresti vedere caratteri corrotti o un risultato troncato. Ridurre `MemoryLimitMb` al di sotto dell’ingombro dell’immagine (spesso ~1 GB per un TIFF 6000×8000 pixel) può far tornare automaticamente il motore alla CPU. + +## Esempio Completo Funzionante + +Di seguito trovi il programma completo, pronto per l’esecuzione. Copialo in un nuovo progetto Console App, sostituisci `YOUR_DIRECTORY/large_photo.tif` con il percorso del tuo TIFF e premi **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Checklist veloce + +- ✅ **Esempio Aspose OCR C#** compilato senza errori. +- ✅ **GPU abilitata** (`Enable = true`). +- ✅ **Limite di memoria GPU** impostato a 2048 MB. +- ✅ **Immagine caricata** da un file TIF. +- ✅ **Testo riconosciuto** e stampato. + +## Problemi Comuni & Come Evitarli + +| Sintomo | Probabile causa | Soluzione | +|---------|-----------------|-----------| +| `System.DllNotFoundException: cudart64_110.dll` | Runtime CUDA non installato o versione incompatibile. | Installa CUDA 11.x (o 12.x) corrispondente al tuo driver. | +| OCR restituisce stringa vuota | Immagine troppo scura o DPI < 150. | Pre‑elabora con `image.AdjustContrast()` o ricampiona a 300 dpi. | +| Crash per out‑of‑memory sulla GPU | `MemoryLimitMb` troppo basso per l’immagine. | Aumenta il limite o suddividi l’immagine in tasselli con `image.Crop`. | +| Errore `Unsupported image format` | Il TIFF usa una compressione esotica (es. JPEG‑2000). | Converti il TIFF in un formato supportato con ImageMagick prima dell’OCR. | + +## Estendere la Demo + +Ora che hai un **esempio Aspose OCR C#** solido, potresti voler approfondire: + +- **Elaborazione batch:** Scorri una cartella di TIF, scrivi ogni risultato in un file `.txt`. +- **Pacchetti lingua:** `ocrEngine.Settings.Language = "es"` per lo spagnolo, o carica dizionari personalizzati. +- **Bounding box:** Usa `ocrResult.Regions` per ottenere le coordinate di ogni parola—utile per strumenti di redazione. +- **Fallback CPU:** Avvolgi il blocco GPU in un try/catch; in caso di errore, imposta `ocrEngine.Settings.Gpu.Enable = false` e riprova. + +Queste estensioni mantengono intatto il modello di base aggiungendo valore per scenari specifici. + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche illustrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell’API e a esplorare approcci alternativi nei tuoi progetti. + +- [Estrai Testo da Immagine Usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Estrai Testo da Immagine – Ottimizzazione OCR con Aspose.OCR per .NET](/ocr/english/net/ocr-optimization/) +- [Estrai testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/skew-angle-calculation/_index.md b/ocr/italian/net/skew-angle-calculation/_index.md index 93078265e..d92985b4b 100644 --- a/ocr/italian/net/skew-angle-calculation/_index.md +++ b/ocr/italian/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Esplora Aspose.OCR per .NET, una potente soluzione OCR per il riconoscimento acc Scatena la potenza di Aspose.OCR per .NET, una soluzione solida per il riconoscimento delle immagini. Scopri come calcolare gli angoli di inclinazione senza sforzo. ### [Calcola l'angolo di inclinazione dall'URI nel riconoscimento delle immagini OCR](./calculate-skew-angle-from-uri/) Esplora Aspose.OCR per .NET per calcolare facilmente gli angoli di inclinazione nel riconoscimento delle immagini OCR. Migliora i tuoi progetti con precisione ed efficienza. +### [Tutorial documento OCR ruotato – Correzione automatica di inclinazione e rotazione in C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Scopri come correggere automaticamente l'inclinazione e la rotazione di documenti OCR ruotati usando Aspose.OCR per .NET in C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/italian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..425717a86 --- /dev/null +++ b/ocr/italian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial OCR per documenti ruotati che mostra come correggere automaticamente + l'inclinazione e rilevare la rotazione usando Aspose OCR in C#. Impara passo passo + con il codice completo. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: it +og_description: Il tutorial OCR per documenti ruotati ti insegna come correggere automaticamente + l'inclinazione e rilevare la rotazione usando Aspose OCR in C#. Segui la guida completa. +og_title: Tutorial OCR per Documenti Ruotati – Correzione Automatica di Inclinazione + e Rotazione in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Tutorial OCR per Documenti Ruotati – Correzione Automatica di Inclinazione + e Rotazione in C# +url: /it/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial OCR per Documenti Ruotati – Guida Completa per Sviluppatori C# + +Ti è mai capitato di imbattersi in un **ocr rotated document tutorial** quando un modulo scansionato arriva di lato o inclinato? Non sei l'unico. Quelle immagini storte possono rovinare un'estrazione di testo pulita, ma la buona notizia è che Aspose OCR può raddrizzare le cose automaticamente per te. + +In questa guida passo‑passo avvieremo un `OcrEngine`, attiveremo **la correzione automatica dello skew** e **l'individuazione automatica della rotazione**, eseguiremo il motore su un'immagine ruotata e stamperemo il testo pulito. Alla fine saprai esattamente perché ogni impostazione è importante, come regolarla per i casi limite e avrai un programma C# pronto all'uso. + +## Cosa Imparerai + +* Come installare e referenziare **Aspose OCR** in un progetto .NET. +* Perché abilitare `AutoCorrectSkew` e `AutoDetectRotation` è la chiave per un affidabile **ocr rotated document tutorial**. +* Come caricare qualsiasi immagine (JPG, PNG, TIFF) e lasciare che il motore faccia il lavoro pesante. +* Suggerimenti per gestire PDF multi‑pagina, scansioni a bassa risoluzione e pacchetti linguistici personalizzati. + +> **Prerequisiti:** Visual Studio 2022 (o qualsiasi IDE C#), runtime .NET 6+ e una licenza valida di Aspose OCR (o la versione di prova gratuita). Nessuna esperienza pregressa con OCR è necessaria. + +--- + +## Passo 1 – Installa Aspose OCR e Configura il Progetto + +Prima di tutto. Prendi il pacchetto NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Consiglio professionale:** Se usi una licenza di prova, posiziona il file `Aspose.OCR.lic` nella stessa cartella dell'eseguibile, oppure registralo programmaticamente con `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Crea una nuova applicazione console: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Ora hai una base pulita per il nostro **ocr rotated document tutorial**. + +## Passo 2 – Inizializza il Motore OCR + +Il motore è il cuore del processo. Pensalo come un coltellino svizzero per l'estrazione del testo; devi solo dirgli quali funzioni abilitare. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Perché queste impostazioni?** +* `AutoCorrectSkew` analizza la linea di base dei caratteri e ruota l'immagine appena quanto basta per rendere le righe orizzontali. +* `AutoDetectRotation` osserva l'orientamento complessivo (0°, 90°, 180°, 270°) e capovolge la pagina se è sottosopra. Senza di esse, il motore leggerebbe “pɹᴉʍ” invece di “word”. + +## Passo 3 – Carica l'Immagine da Elaborare + +Aspose OCR funziona con qualsiasi formato raster comune. Sostituisci il percorso segnaposto con la posizione reale del tuo modulo ruotato. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Caso limite:** Se ricevi un TIFF multi‑pagina, usa `OcrImage.FromMultiPageTiff(filePath)` e itera su `image.Pages`. + +## Passo 4 – Esegui il Riconoscimento + +Ora il motore compie la magia. Prima raddrizzerà l'immagine (grazie ai flag di skew/rotazione) e poi estrarrà i caratteri. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Se ti serve il supporto linguistico oltre l'inglese, impostalo prima di chiamare `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Passo 5 – Output del Testo Riconosciuto + +Infine, scarica il testo pulito sulla console — o reindirizzalo a un file, a un database, qualunque si adatti al tuo flusso di lavoro. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Output previsto** (supponendo che l'immagine di esempio contenga “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Nota come il testo appare correttamente anche se l'immagine di origine era ruotata di 90° e leggermente inclinata. + +--- + +## Gestione dei Problemi Comuni + +| Problema | Perché accade | Soluzione | +|------|----------------|-----| +| **Output vuoto** | Correzione dello skew disabilitata o immagine troppo scura. | Abilita `AutoCorrectSkew` (già attivo) e aumenta il contrasto con `image.AdjustContrast(1.2)`. | +| **Caratteri spazzatura** | Impostazione della lingua errata. | Imposta `ocrEngine.Settings.Language` per corrispondere alla lingua del documento. | +| **Ritardo di prestazioni su PDF grandi** | Il motore elabora ogni pagina in sequenza. | Usa `Parallel.ForEach` su `image.Pages` per sfruttare CPU multi‑core. | +| **Eccezione di licenza** | Prova scaduta. | Acquista una licenza permanente o rimani entro i limiti della versione di prova (5 pagine per esecuzione). | + +--- + +## Consigli Pro per un Tutorial OCR Rotated Document Robusto + +* **Elaborazione batch:** Avvolgi l'intero flusso in un metodo che accetta un percorso di cartella, itera su ogni immagine e scrive ciascun risultato in un file `.txt`. +* **Pre‑elaborazione:** Talvolta una scansione rumorosa beneficia di `image.Denoise()` prima del riconoscimento. +* **Post‑elaborazione:** Usa espressioni regolari per pulire le tipiche letture errate dell'OCR, ad esempio sostituire “0” con “O” solo quando è circondato da lettere. +* **Logging:** Aspose OCR fornisce `ocrEngine.Logger` – collegalo a un logger su file per catturare avvisi su punteggi di bassa confidenza. + +--- + +## Codice Completo, Pronto‑da‑Eseguire + +Salva quanto segue come `Program.cs` all'interno del tuo progetto console. Include tutti i passaggi, i commenti e un piccolo helper per l'elaborazione batch. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Eseguilo: + +```bash +dotnet run +``` + +Dovresti vedere il testo pulito stampato sulla console, dimostrando che il nostro **ocr rotated document tutorial** funziona end‑to‑end. + +--- + +## Conclusione + +Ora disponi di un **ocr rotated document tutorial** completo che corregge automaticamente lo skew, rileva la rotazione ed estrae testo pulito usando Aspose OCR in C#. La lezione chiave? Abilitare `AutoCorrectSkew` **e** `AutoDetectRotation` trasforma una scansione fortemente inclinata in un output perfettamente leggibile con poche righe di codice. + +Da qui, puoi espandere a lavori batch, integrare pacchetti linguistici o alimentare i risultati in pipeline di analisi successive. Vuoi approfondire la **correzione automatica dello skew**? Dai un'occhiata all'API di pre‑elaborazione immagini di Aspose, o sperimenta soglie personalizzate per scansioni rumorose. + +Hai domande su come gestire PDF, TIFF multi‑pagina o l'integrazione con Azure Functions? Lascia un commento, e buona programmazione! + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell'API e a esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/italian/net/text-recognition/_index.md index 346402ba4..21f2ad21c 100644 --- a/ocr/italian/net/text-recognition/_index.md +++ b/ocr/italian/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Scatena la potenza di Aspose.OCR per .NET. Impara a ottenere risultati OCR in fo Migliora le tue applicazioni .NET con Aspose.OCR per un efficiente riconoscimento del testo delle immagini. Esplora la modalità Rileva aree OCR per risultati precisi. ### [Riconoscere PDF nel riconoscimento immagini OCR](./recognize-pdf/) Sblocca il potenziale dell'OCR in .NET con Aspose.OCR. Estrai testo dai PDF senza sforzo. Scaricalo ora per un'esperienza di integrazione perfetta. +### [Esegui OCR su PDF con Aspose.OCR – Guida completa C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Scopri come eseguire l'OCR su PDF usando Aspose.OCR con esempi e istruzioni complete in C#. ### [Riconosci tabella nel riconoscimento immagini OCR](./recognize-table/) Sblocca il potenziale di Aspose.OCR per .NET con la nostra guida completa sul riconoscimento delle tabelle nel riconoscimento delle immagini OCR. +### [Esegui OCR su immagine con Aspose OCR – Guida Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Scopri come eseguire l'OCR su un'immagine usando Aspose OCR con esempi e istruzioni in lingua hindi. +### [Esegui OCR su immagine e rileva parole errate in C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Scopri come utilizzare Aspose.OCR in C# per eseguire l'OCR su un'immagine e identificare le parole con errori ortografici. +### [Come usare Aspose: Convertire immagine in HTML con OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Scopri come convertire un'immagine in HTML mantenendo il testo riconosciuto con Aspose.OCR in pochi passaggi. +### [OCR dei sottotitoli video in C# – Guida completa](./video-subtitle-ocr-in-c-complete-guide/) +Scopri come eseguire l'OCR sui sottotitoli dei video usando Aspose.OCR in C# con una guida completa passo passo. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/italian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..cb397c613 --- /dev/null +++ b/ocr/italian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Come utilizzare Aspose per convertire un'immagine in HTML ed estrarre + il testo dall'immagine in C#. Impara a generare HTML da un'immagine e a fare OCR + dell'immagine in HTML rapidamente. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: it +og_description: Come utilizzare Aspose per convertire un'immagine in HTML, estrarre + testo dall'immagine e generare HTML dall'immagine con OCR in C#. Segui questa guida + completa. +og_title: 'Come utilizzare Aspose: convertire l''immagine in HTML con OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Come usare Aspose: Convertire immagine in HTML con OCR' +url: /it/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come usare Aspose: Convertire un'immagine in HTML con OCR + +Ti sei mai chiesto **come usare Aspose** per trasformare una foto scansionata in un HTML ordinato? Forse hai una pagina di una rivista, una ricevuta o una nota scritta a mano e hai bisogno che il testo e il layout vengano preservati per la pubblicazione web. La buona notizia è che non devi scrivere un parser personalizzato né combatterti con l'elaborazione di immagini a basso livello—Aspose.OCR fa il lavoro pesante per te. + +In questo tutorial percorreremo un **esempio completo e eseguibile** che mostra come **convertire un'immagine in HTML**, **estrarre testo dall'immagine** e **generare HTML dall'immagine** usando la libreria Aspose OCR in C#. Alla fine avrai una piccola applicazione console che produce un file HTML con il layout originale della pagina intatto, pronto per essere inserito in qualsiasi sito web. + +## Prerequisiti + +- **.NET 6.0 SDK** o versioni successive (il codice funziona sia con .NET Core che con .NET Framework). +- **Visual Studio 2022** (o qualsiasi editor tu preferisca). +- **Aspose.OCR for .NET** – installa tramite NuGet: `dotnet add package Aspose.OCR`. +- Un file immagine (JPEG/PNG) che desideri trasformare, ad esempio `magazine_page.jpg`. + +Non sono necessari file di configurazione aggiuntivi; la libreria include tutto il necessario per l'OCR e la generazione del layout HTML. + +## Passo 1: Configurare il progetto e aggiungere Aspose.OCR + +Per prima cosa, crea un nuovo progetto console e aggiungi il pacchetto Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Suggerimento:** Se stai usando Visual Studio, fai semplicemente clic destro sul progetto → *Gestisci pacchetti NuGet* → cerca **Aspose.OCR** e installalo. Questo passaggio garantisce che tu possa **ocr image to html** senza riferimenti mancanti. + +## Passo 2: Inizializzare il motore OCR + +Il cuore del processo è la classe `OcrEngine`. Pensala come il cervello che legge l'immagine e decide come produrre il risultato. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Qui istanziamo `OcrEngine`. Non è necessario fornire credenziali per la versione gratuita; la libreria utilizzerà i suoi modelli di riconoscimento integrati. + +## Passo 3: Caricare l'immagine sorgente + +Successivamente, indica al motore il file che desideri elaborare. Aspose fornisce il comodo metodo `OcrImage.FromFile` che gestisce la maggior parte dei formati immagine. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Sostituisci `YOUR_DIRECTORY` con il percorso assoluto o relativo dove si trova la tua immagine. Se l'immagine è nella stessa cartella dell'eseguibile, puoi semplicemente usare `"magazine_page.jpg"`. + +## Passo 4: Riconoscere e richiedere HTML con layout + +Questo è il fulcro del tutorial. Passando `OutputFormat.HtmlWithLayout` diciamo ad Aspose di **generare HTML dall'immagine** preservando il posizionamento originale di blocchi di testo, immagini e tabelle. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +La proprietà `recognitionResult.Text` ora contiene un documento HTML completo. Se ti servisse solo testo semplice, potresti usare `OutputFormat.Text`, ma ci concentriamo su **convert image to html** con fedeltà al layout. + +## Passo 5: Salvare il file HTML + +Infine, scrivi la stringa HTML su disco. Questo ti fornisce un file pronto all'uso che puoi aprire in qualsiasi browser. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Eseguendo il programma verrà generato `magazine.html`. Aprilo e vedrai il testo della pagina originale posizionato esattamente come appare nell'immagine sorgente—perfetto per l'archiviazione o la pubblicazione web. + +## Esempio completo funzionante + +Di seguito trovi il programma **completo, pronto per il copia‑incolla**. Nessuna parte è omessa, così potrai compilarlo ed eseguirlo subito dopo aver impostato i percorsi corretti. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Output previsto + +Quando apri `magazine.html` in un browser, dovresti vedere qualcosa di simile (semplificato a scopo illustrativo): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Gli attributi `style` esatti varieranno in base all'immagine originale, ma la struttura garantisce che **extract text from image** e **generate html from image** avvengano in un unico passaggio fluido. + +## Domande comuni e casi particolari + +### E se l'immagine è a bassa risoluzione? + +Aspose.OCR funziona al meglio con immagini che hanno almeno **300 DPI**. Se il tuo file è sfocato, prova a preelaborarlo con una libreria di miglioramento delle immagini (ad es., ImageSharp) prima di passarlo al motore OCR. La bassa qualità può influire sia sull'accuratezza di **extract text from image** sia sulla fedeltà del layout HTML generato. + +### Posso controllare la lingua dell'OCR? + +Sì. Imposta la proprietà `Language` su `OcrEngine` prima di chiamare `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Questo migliora il riconoscimento quando si trattano caratteri non inglesi. + +### Come ottenere testo semplice invece di HTML? + +Se ti serve solo la stringa grezza, sostituisci `OutputFormat.HtmlWithLayout` con `OutputFormat.Text`. Lo stesso `recognitionResult.Text` conterrà solo i caratteri estratti. + +### È possibile incorporare immagini nell'HTML generato? + +Aspose.OCR può incorporare l'immagine originale come URI dati base‑64 quando usi `OutputFormat.HtmlWithLayoutAndImages`. Questo è utile quando vuoi un unico file HTML senza risorse esterne. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Come gestire grandi batch? + +Per l'elaborazione batch, avvolgi la logica in un ciclo `foreach` su una lista di percorsi file. Riutilizzare la stessa istanza di `OcrEngine` riduce l'overhead e accelera la pipeline **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Suggerimenti per codice pronto alla produzione + +- **Dispose resources**: sia `OcrEngine` che `OcrImage` implementano `IDisposable`. Avvolgili in istruzioni `using` per liberare rapidamente la memoria nativa. +- **Error handling**: Cattura `IOException` per problemi legati ai file e `OcrException` per problemi di riconoscimento. +- **Performance**: Se elabori molte immagini, considera di abilitare il **parallelismo** (`Parallel.ForEach`) ma fai attenzione all'uso della CPU—l'OCR è intensivo per la CPU. +- **Logging**: Integra un logger (ad es., Serilog) per catturare i punteggi di fiducia OCR (`recognitionResult.Confidence`) per il monitoraggio della qualità. + +## Conclusione + +Abbiamo appena coperto **come usare Aspose** per **convertire un'immagine in HTML**, **estrarre testo dall'immagine** e **generare HTML dall'immagine** in pochi passaggi semplici. Il campione di codice completo ti mostra come **ocr image to html** preservando il layout, rendendolo una solida base per qualsiasi progetto di digitalizzazione di documenti. + +Da qui potresti: + +- Sperimentare con diverse opzioni `OutputFormat` per soddisfare le tue esigenze. +- Combinare l'output HTML con un framework CSS per uno stile responsivo. +- Inviare il testo estratto a un indice di ricerca o a una pipeline di machine‑learning. + +Provalo, modifica le impostazioni e scopri quanto facilmente Aspose trasforma le immagini in contenuti pronti per il web. Se incontri problemi, lascia un commento—buon coding! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## Cosa dovresti imparare dopo? + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Estrai testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Converti immagine in testo – Esegui OCR su immagine da URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Riconosci testo in immagine con Aspose OCR per più lingue](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/italian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..156efc403 --- /dev/null +++ b/ocr/italian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-03 +description: Esegui OCR su un'immagine ed estrai il testo dall'immagine usando Aspose.OCR. + Scopri come rilevare parole errate e ottenere suggerimenti ortografici in una singola + demo C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: it +og_description: Esegui OCR sull'immagine per estrarre il testo dall'immagine, quindi + rileva le parole errate e ottieni suggerimenti ortografici con Aspose.OCR in C#. +og_title: Esegui OCR su un'immagine e rileva parole errate in C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Esegui OCR su immagine e rileva parole errate in C# +url: /it/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Eseguire OCR su Immagine e Rilevare Parole Sbagliate in C# + +Ti sei mai chiesto come **eseguire OCR su immagine** senza impazzire? Non sei l'unico. Che tu stia digitalizzando vecchie lettere, scannerizzando ricevute o costruendo un flusso di lavoro intelligente per documenti, estrarre testo pulito dalle foto è il primo ostacolo. La buona notizia? Con Aspose.OCR puoi creare una soluzione in pochi minuti, e in più puoi anche **rilevare parole sbagliate** e **ottenere suggerimenti ortografici** nella stessa esecuzione. + +In questo tutorial ti guideremo passo passo attraverso un’app console C# completa e pronta all’uso che **estrae testo da immagine**, esegue un correttore ortografico inglese e stampa ogni errore con utili idee di correzione. Alla fine saprai esattamente **come estrarre testo**, come collegare l’API di spell‑check e quale aspetto avrà l’output previsto sulla console. + +## Cosa Costruirai + +- Caricherai un bitmap (o PNG) che contiene errori tipografici. +- Eseguirai Aspose.OCR per **eseguire OCR su immagine** e otterrai dati di stringa grezzi. +- Inizializzerai il correttore ortografico inglese integrato. +- **Rileverai parole sbagliate** e **otterrai suggerimenti ortografici** per ciascuna. +- Stamperai un rapporto ordinato sulla console. + +Nessun servizio esterno, nessuna chiamata HTTP complicata—solo un singolo pacchetto NuGet e poche righe di codice. + +## Prerequisiti + +- .NET 6.0 SDK o versioni successive (il codice funziona anche su .NET Framework 4.7+). +- Visual Studio 2022 (o qualsiasi editor tu preferisca). +- Pacchetto NuGet Aspose.OCR per .NET (`Aspose.OCR`). +- Un file immagine (`letter_with_typos.png`) posizionato in una cartella a cui il progetto possa fare riferimento. + +Se non hai mai usato Aspose, non preoccuparti—installare il pacchetto è semplice come eseguire: + +```bash +dotnet add package Aspose.OCR +``` + +Ora immergiamoci nell’implementazione. + +## Passo 1: Configurare il Progetto e Installare Aspose.OCR + +Crea un nuovo progetto console e aggiungi la libreria OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Al termine del restore, apri `Program.cs`. Sostituiremo il contenuto predefinito con il codice demo completo più avanti, ma prima spieghiamo perché ogni spazio dei nomi è importante. + +- `Aspose.OCR` – Motore OCR principale e gestione delle immagini. +- `Aspose.OCR.SpellCheck` – Utility di correzione ortografica incluse nella libreria. +- `System` – Classi base standard di .NET (es. `Console`). + +## Passo 2: Caricare l'Immagine ed Eseguire OCR su Immagine + +Il primo lavoro reale è fornire l’immagine al motore OCR. Aspose.OCR legge molti formati (PNG, JPEG, TIFF). Ecco lo snippet che fa il lavoro pesante: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Perché è importante:** `OcrImage.FromFile` astrae i dettagli a livello di pixel, mentre `OcrEngine.Recognize` esegue il modello neurale addestrato che traduce i glifi visivi in caratteri Unicode. La proprietà `ocrResult.Text` ora contiene la stringa grezza—esattamente ciò di cui hai bisogno per **estrarre testo da immagine**. + +> **Consiglio professionale:** Se la tua immagine contiene più lingue, puoi impostare `ocrEngine.Language = OcrLanguage.Multilingual;` prima di chiamare `Recognize`. + +## Passo 3: Inizializzare il Corretti Ortografico Inglese + +Aspose.OCR fornisce un motore di correzione ortografica integrato che comprende l’inglese fin da subito. Inizializzarlo è una riga di codice: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Perché questo passo è cruciale:** L’output OCR può includere caratteri riconosciuti in modo errato (es. “l” vs “1”) o veri errori di battitura dal documento originale. Il correttore ortografico scannerizzerà la stringa, individuerà i token sospetti e suggerirà alternative. + +## Passo 4: Rilevare Parole Sbagliate e Ottenere Suggerimenti Ortografici + +Ora passiamo il testo OCR al correttore: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` è una collezione in cui ogni voce contiene la parola errata e un array di possibili correzioni. + +## Passo 5: Stampare i Risultati + +Infine, iteriamo sulla collezione e stampiamo un rapporto leggibile: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Output Atteso sulla Console + +Supponendo che `letter_with_typos.png` contenga la frase: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +L’esecuzione della demo produrrà qualcosa di simile a: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Nota come ogni errore è accompagnato da una serie di correzioni plausibili—esattamente ciò che ti serve quando costruisci un’interfaccia utente di correzione amichevole. + +## Esempio Completo Funzionante + +Di seguito trovi il programma **completo, pronto da copiare e incollare**. Sostituisci `YOUR_DIRECTORY` con il percorso reale del tuo file immagine. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Casi Limite da Considerare** +> - **Immagine Vuota:** Se il motore OCR restituisce una stringa vuota, `spellChecker.Check` restituirà semplicemente una collezione vuota—nessun crash. +> - **Testo Non Inglese:** Sostituisci `OcrLanguage.English` con `OcrLanguage.French` (o qualsiasi lingua supportata) per **rilevare parole sbagliate** in altre localizzazioni. +> - **Documenti Grandi:** Per PDF multi‑pagina, dovresti iterare su ogni pagina, eseguire OCR, quindi aggregare i risultati prima del controllo ortografico. + +## Panoramica Visiva (Testo Alternativo) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*Il diagramma sopra illustra la pipeline end‑to‑end: immagine → motore OCR → testo grezzo → correttore ortografico → suggerimenti.* + +## Domande Frequenti & Consigli Pro + +| Domanda | Risposta | +|----------|--------| +| **È necessaria una connessione a Internet?** | No. Aspose.OCR funziona interamente in locale; ideale per ambienti offline o sicuri. | +| **Quanto è accurato il correttore ortografico?** | Utilizza un dizionario di circa 150 000 parole inglesi e matching fuzzy, quindi la maggior parte dei typo comuni viene rilevata. | +| **Posso personalizzare il dizionario?** | Sì. `SpellChecker.AddUserDictionary("custom.txt")` ti permette di caricare termini specifici del dominio (es. nomi di prodotto). | +| **Cosa succede se l’immagine è inclinata?** | Il motore OCR rileva automaticamente l’orientamento, ma puoi chiamare manualmente `ocrEngine.ImagePreprocessing.Rotate(angle)` per i casi più ostinati. | +| **C’è un modo per evidenziare i suggerimenti nell’interfaccia?** | Dopo aver ottenuto la collezione `misspellings`, puoi mappare ogni `entry.Word` alla sua posizione in `ocrResult.Text` e sottolinearlo in un RichTextBox o in una vista web. | + +## Conclusione + +Ti abbiamo appena mostrato **come eseguire OCR su immagine**, **estrarre testo da immagine**, e poi **rilevare parole sbagliate** ottenendo **suggerimenti ortografici**—tutto con una concisa app console C#. L’idea di base è semplice: lascia che Aspose.OCR faccia il lavoro pesante di riconoscere i caratteri, poi usa il suo correttore ortografico integrato per pulire l’output. Da qui puoi espandere la demo in un servizio di elaborazione documenti completo, integrarlo con un’API web, o collegarlo a un editor desktop. + +Pronto per il passo successivo? Prova a cambiare lingua in spagnolo, usa un PDF multi‑pagina, o costruisci un piccolo front‑end WPF che permetta agli utenti di cliccare su una parola per accettare un suggerimento. I mattoni di base sono già pronti—basta continuare a sperimentare. + +Se hai incontrato difficoltà o hai idee per estensioni, lascia un commento qui sotto. Buona programmazione! + +## Cosa Dovresti Imparare Dopo + +I tutorial seguenti trattano argomenti strettamente correlati che approfondiscono le tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell’API e a esplorare approcci alternativi nei tuoi progetti. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/italian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..606a20c7f --- /dev/null +++ b/ocr/italian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Esegui OCR su un'immagine usando Aspose OCR in C#. Scopri come caricare + l'immagine per l'OCR ed estrarre testo hindi da un'immagine offline con codice passo‑passo. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: it +og_description: Esegui OCR su un'immagine con Aspose OCR in C#. Questo tutorial mostra + come caricare un'immagine per l'OCR ed estrarre testo in hindi offline, completo + di codice eseguibile. +og_title: Esegui OCR su immagine – Guida OCR Hindi di Aspose +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Esegui OCR su immagine con Aspose OCR – Guida in Hindi +url: /it/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esegui OCR su Immagine con Aspose OCR – Guida Hindi + +Hai mai dovuto **eseguire OCR su immagine** ma ti sei bloccato su come estrarre i caratteri Hindi? Non sei solo—molti sviluppatori incontrano lo stesso ostacolo quando provano per la prima volta a leggere script non latini. La buona notizia è che Aspose OCR lo rende abbastanza semplice, e puoi farlo completamente offline. + +In questa guida **caricheremo l'immagine per OCR**, indicheremo al motore i pacchetti linguistici offline e infine **estrarremo il testo Hindi dall'immagine** senza mai toccare Internet. Alla fine avrai un'app console C# pronta all'uso che legge una ricevuta in Hindi e stampa il testo nella console. + +## Cosa Ti Serve + +- **.NET 6.0** o successivo (il codice funziona anche su .NET Framework 4.7+) +- Pacchetto NuGet **Aspose.OCR for .NET** + `dotnet add package Aspose.OCR` +- Una cartella contenente le **risorse linguistiche offline Hindi** (scaricabili dal portale Aspose) +- Un file immagine con testo in Hindi, ad esempio `receipt_hindi.png` + +Tutto qui—nessun servizio esterno, nessuna chiave API, solo codice lineare. + +## Esegui OCR su Immagine – Implementazione Passo‑per‑Passo + +Di seguito suddividiamo il processo in sette passaggi chiari. Ogni passaggio è spiegato **perché** è importante, non solo **cosa** digitare. + +### Passo 1: Crea l'Istanza del Motore OCR + +Il motore è il cuore di Aspose OCR. Istanziarlo ti dà accesso a tutte le impostazioni che modificherai in seguito. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Perché?** +> Senza un `OcrEngine` non hai alcun oggetto su cui chiamare `Recognize`. È come la “camera” che in seguito scannerizzerà la tua immagine. + +### Passo 2: Indirizza il Motore alle Risorse Offline + +Aspose fornisce pacchetti linguistici che puoi memorizzare localmente. Impostare `ResourcesFolder` indica al motore dove cercare. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Consiglio:** +> Usa un percorso assoluto durante lo sviluppo, poi passa a un percorso relativo o a una impostazione di configurazione per la produzione. + +### Passo 3: Forza la Modalità Offline + +Ti potresti chiedere: “Devo davvero disabilitare la ricerca online?” +Se lavori dietro un firewall o vuoi risultati deterministici, imposta `UseOfflineResources` su `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Suggerimento professionale:** +> Lasciare questa flag a `false` può far scaricare al motore dati aggiuntivi, aumentando la latenza e potenzialmente violando le policy di sicurezza. + +### Passo 4: Seleziona Hindi come Lingua di Riconoscimento + +Qui **estrarremo il testo Hindi dall'immagine** indicando al motore quale lingua aspettarsi. Questo migliora drasticamente la precisione. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Perché aiuta:** +> I motori OCR usano modelli di caratteri specifici per lingua. Bloccandoti su Hindi, eviti che il motore debba indovinare tra decine di script. + +### Passo 5: Carica l'Immagine per OCR + +Ora **carichiamo l'immagine per OCR**. Il metodo `OcrImage.FromFile` legge il bitmap in un formato comprensibile al motore. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Errore comune:** +> Fornire un percorso con slash (`/`) su Windows funziona, ma usare `Path.Combine` rende il tuo codice indipendente dalla piattaforma. + +### Passo 6: Esegui il Riconoscimento + +Con tutto impostato, finalmente **eseguiamo OCR sull'immagine** chiamando `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Cosa succede?** +> Il motore analizza ogni pixel, confronta i pattern con il database dei glifi Hindi e costruisce una stringa di caratteri Unicode. + +### Passo 7: Stampa il Testo Riconosciuto + +L'oggetto risultato contiene una proprietà `Text` che contiene la stringa estratta. Lo scriviamo semplicemente nella console. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Output previsto:** +> Se `receipt_hindi.png` contiene “भुगतान सफल”, la console stamperà esattamente quella riga, preservando i segni diacritici. + +## Carica Immagine per OCR – Preparazione della Risorsa + +Se ti chiedi se è possibile fornire al motore uno stream invece di un file, la risposta è sì. Sostituisci `OcrImage.FromFile` con: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Perché usare uno stream?** +> Gli stream ti permettono di lavorare con immagini archiviate in database, blob cloud o risorse incorporate—perfetto per servizi scalabili. + +## Estrarre Testo Hindi dall'Immagine – Gestione dei Casi Limite + +1. **Pacchetto linguistico mancante** – Se il pacchetto Hindi non viene trovato, `Recognize` lancia un'eccezione. Avvolgi la chiamata in un try/catch e registra un messaggio amichevole. +2. **Immagini a bassa risoluzione** – La precisione OCR scende sotto i 300 dpi. Pre‑elabora l'immagine (ridimensiona, nitida) prima del caricamento. +3. **Documenti multilingua** – Puoi abilitare più lingue: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Queste modifiche garantiscono che la tua routine **esegua OCR su immagine** rimanga robusta in produzione. + +## Esecuzione dell'Esempio Completo + +Salva il file seguente come `Program.cs`, sostituisci i percorsi segnaposto e avvia: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Quando esegui `dotnet run`, dovresti vedere qualcosa del genere: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Se ottieni una stringa vuota, ricontrolla che **ResourcesFolder** punti alla cartella contenente `Hindi.traineddata` e che l'immagine sia sufficientemente chiara. + +## Conclusione + +Abbiamo illustrato come **eseguire OCR su immagine** con Aspose OCR, coprendo tutto, dal **caricare immagine per OCR** all'**estrarre testo Hindi dall'immagine**, in uno scenario completamente offline. Il codice completo e funzionante sopra ti fornisce una solida base, e i consigli su stream, gestione degli errori e supporto multilingua ti aiuteranno ad adattare la soluzione a progetti reali. + +Pronto per il passo successivo? Prova a cambiare lingua in **OcrLanguage.Tamil** o a fornire immagini da uno storage Azure Blob. Puoi anche sperimentare con le impostazioni `ImagePreprocessing` per aumentare la precisione su ricevute rumorose. + +Hai domande o hai incontrato un problema? Lascia un commento—buona programmazione! + +![Perform OCR on image example + + +## Cosa Dovresti Imparare Dopo? + + +I seguenti tutorial coprono argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑per‑passo per aiutarti a padroneggiare funzionalità aggiuntive dell'API e a esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/italian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..5ed85b01e --- /dev/null +++ b/ocr/italian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-06-03 +description: Esegui OCR su PDF e converti PDF scansionati in PDF ricercabili usando + Aspose.OCR. Scopri come riconoscere il testo da PDF e creare PDF ricercabili in + pochi minuti. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: it +og_description: Esegui l'OCR su PDF e crea istantaneamente un PDF ricercabile. Questo + tutorial mostra passo passo come riconoscere il testo da un PDF usando Aspose.OCR. +og_title: Esegui OCR su PDF – Guida completa C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Esegui OCR su PDF con Aspose.OCR – Guida completa C# +url: /it/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Esegui OCR su PDF con Aspose.OCR – Guida Completa C# + +Ti sei mai chiesto **come eseguire OCR su PDF** senza dover combattere con decine di strumenti da riga di comando? Non sei solo. Che tu stia digitalizzando fatture, archiviando vecchi rapporti o semplicemente abbia bisogno di una versione ricercabile di un contratto scansionato, trasformare un PDF statico in qualcosa di effettivamente ricercabile è una svolta. + +In questa guida percorreremo **come creare PDF ricercabili** da PDF scansionati (e anche da semplici immagini) usando Aspose.OCR per .NET. Alla fine sarai in grado di **riconoscere testo da PDF** con poche righe di codice C#, e comprenderai il perché di ogni passaggio così da poter adattare la soluzione ai tuoi progetti. + +> **Quick takeaway:** L’intero processo si riduce a tre cose—inizializzare il motore OCR, fornire la sorgente (PDF o immagine) e salvare l’output PDF ricercabile. Immergiamoci. + +--- + +## Cosa Ti Serve + +| Prerequisito | Perché è importante | +|--------------|---------------------| +| **.NET 6.0+** (o .NET Framework 4.6+) | Aspose.OCR punta a runtime moderni; versioni più vecchie potrebbero non includere gli aggiornamenti API. | +| **Aspose.OCR for .NET** pacchetto NuGet | Fornisce la classe `OcrEngine` e le utility per la gestione dei PDF. | +| **Una licenza Aspose valida** (o usa la valutazione gratuita) | Senza licenza incorrerai nel limite di valutazione di 30 giorni e nei watermark. | +| **Un PDF scansionato** (o un file immagine) che vuoi rendere ricercabile | È il documento sorgente per l’OCR. | +| **Visual Studio 2022** (o qualsiasi editor C#) | Rende il debug più semplice, ma qualsiasi IDE va bene. | + +Puoi installare la libreria con il seguente comando NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Se lavori su una pipeline CI, aggiungi il file di licenza agli artefatti di build e caricalo a runtime per evitare di hard‑codare i percorsi. + +--- + +## Esegui OCR su PDF – Configurazione di Aspose.OCR + +La prima cosa di cui abbiamo bisogno è una nuova istanza di `OcrEngine`. Pensala come il cervello che leggerà il tuo documento. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Perché una nuova istanza ogni volta? Il motore conserva configurazioni (come le impostazioni della lingua) che possono variare per documento. Crearlo per ogni esecuzione garantisce una “lavagna pulita” ed evita interferenze tra job. + +--- + +## Come Creare PDF Ricercabile – Configurazione delle Password (Opzionale) + +Se il tuo PDF è protetto, devi comunicare al motore la password prima che possa leggere le pagine: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Saltare questo passaggio su un file protetto solleverà una `PdfPasswordException`. Avvolgi sempre il codice in un try‑catch se non sei sicuro dello stato di protezione. + +--- + +## Converti PDF Scansionato in PDF Ricercabile – Caricamento della Sorgente + +Aspose.OCR lavora con l'astrazione `OcrImage`, che può avvolgere PDF, TIFF, JPEG, ecc. Ecco come caricare un PDF scansionato in memoria: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +In sottofondo, `FromFile` analizza ogni pagina in immagini raster che il motore OCR può processare. Se hai un PDF multi‑pagina, il motore itererà automaticamente su tutte le pagine. + +--- + +## Riconosci Testo da PDF – Eseguire l'OCR + +Ora il cuore del tutorial: chiedi al motore di riconoscere il testo e produrre un PDF ricercabile. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` indica al motore di inserire uno strato di testo invisibile sopra le immagini scansionate originali. Il PDF risultante mantiene la fedeltà visiva della scansione diventando completamente ricercabile—esattamente ciò che serve per audit di conformità. + +--- + +## Converti Immagine in PDF Ricercabile – Salvataggio del Risultato + +Infine, scrivi i dati binari su disco: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +La proprietà `Binary` contiene i byte grezzi del PDF. Potresti anche trasmetterli direttamente in una risposta web se stai costruendo un’API. + +![Diagramma che mostra il flusso di conversione OCR per creare PDF ricercabile](https://example.com/ocr-flow.png "Diagramma del flusso di esecuzione OCR su PDF") + +*Testo alternativo immagine: Diagramma del flusso di esecuzione OCR su PDF che illustra come un PDF scansionato viene trasformato in un PDF ricercabile.* + +--- + +## Casi Limite & Consigli Pratici + +### 1. File di grandi dimensioni e gestione della memoria +Se elabori PDF più grandi di 100 MB, considera l’uso di `OcrEngineSettings.MemoryLimit` per limitare l’utilizzo di memoria. Inoltre, processa le pagine in batch per evitare `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Supporto Lingua +Per impostazione predefinita Aspose.OCR assume l’inglese. Per riconoscere altre lingue, imposta la proprietà `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Scenari Multi‑Thread +`OcrEngine` **non** è thread‑safe. Se ti serve l’elaborazione parallela, crea un motore separato per ogni thread. + +### 4. Debugging dell'Accuratezza OCR +Puoi estrarre il testo semplice da `ocrResult` per il debugging: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Se l’output appare confuso, sperimenta con `PreprocessSettings` (ad es. deskew, despeckle) per migliorare la qualità. + +### 5. Trappole di Licenza +Quando utilizzi la versione di valutazione, Aspose aggiunge un watermark al PDF di output. Registra la tua licenza all’inizio dell’applicazione: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Esempio Completo – Dall'Inizio alla Fine + +Di seguito trovi il programma completo, pronto per l’esecuzione, che incorpora tutti i consigli sopra. Sentiti libero di copiarlo e incollarlo in un nuovo progetto console. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Output previsto:** Dopo l’esecuzione, vedrai una riga nella console che conferma la posizione del file. Apri `output.pdf` in qualsiasi visualizzatore PDF; prova a digitare una parola che sai comparire nella scansione originale. Se il testo viene evidenziato, hai **eseguito OCR su PDF** e creato un documento ricercabile. + +--- + +## Domande Frequenti + +**D: Posso usare questo per convertire una singola immagine (PNG/JPEG) in un PDF ricercabile?** +R: Assolutamente. Sostituisci `OcrImage.FromFile("input.pdf")` con il percorso del tuo file immagine. Il motore rasterizzerà l’immagine e inserirà lo strato OCR allo stesso modo. + +**D: E se il mio PDF contiene sia pagine scansionate sia testo nativo?** +R: Il motore sovrapporrà il testo OCR sopra il contenuto esistente, quindi il testo nativo rimarrà selezionabile mentre le pagine scansionate diventeranno ricercabili. + +**D: Quanto è accurato l’OCR?** +R: L’accuratezza dipende dalla qualità della sorgente. Scansioni pulite ad alta risoluzione (>300 dpi) offrono >95 % di precisione. Per documenti rumorosi, abilita `PreprocessSettings` (deskew, despeckle) prima di chiamare `Recognize`. + +--- + +## Prossimi Passi – Estendere il Tuo Toolkit OCR + +Ora che sai **riconoscere testo da PDF** e **convertire PDF scansionati in PDF ricercabili**, considera questi argomenti di approfondimento: + +- **Elaborazione batch**: cicla su una cartella di PDF e genera versioni ricercabili automaticamente. +- **Estrazione testo**: usa `ocrResult.Text` per alimentare un indice di ricerca (ad es. Elasticsearch). +- **Pacchetti linguistici personalizzati**: scarica dati linguistici aggiuntivi da Aspose per supportare script asiatici. +- **Conformità PDF/A**: combina Aspose.PDF con l’output OCR per creare PDF pronti per l’archiviazione a lungo termine. + +Ognuno di questi si basa sui passaggi fondamentali che abbiamo trattato, quindi sei pronto a espandere la tua soluzione. + +--- + +## Conclusione + +Ti abbiamo appena mostrato **come eseguire OCR su PDF** usando Aspose.OCR, trasformare PDF scansionati in PDF pienamente ricercabili e persino convertire immagini semplici in PDF ricercabili. Il codice + +## Cosa Dovresti Imparare Dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi con spiegazioni passo‑passo per aiutarti a padroneggiare funzionalità API aggiuntive ed esplorare approcci alternativi nei tuoi progetti. + +- [Riconosci Testo PDF – Operazioni OCR con Aspose.OCR per Java](/ocr/english/java/ocr-operations/) +- [Come fare OCR su PDF in .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) +- [Converti Immagini in PDF C# – Salva Risultato OCR Multipagina](/ocr/english/net/ocr-optimization/save-multipage-result-as-document/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/italian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9137047f0 --- /dev/null +++ b/ocr/italian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial OCR per sottotitoli video che mostra come estrarre fotogrammi + dal video e leggere il testo da file video come MP4 utilizzando Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: it +og_description: Impara l'OCR dei sottotitoli video con Aspose.OCR. Estrai i fotogrammi + dal video, leggi il testo dal video e estrai il testo da MP4 in pochi minuti. +og_title: OCR dei sottotitoli video in C# – Guida passo passo +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR dei sottotitoli video in C# – Guida completa +url: /it/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR dei sottotitoli video in C# – Guida completa + +Hai mai avuto bisogno di **video subtitle ocr** ma non sapevi da dove cominciare? Non sei solo. Che tu stia digitalizzando registrazioni di lezioni, estraendo i sottotitoli da video di formazione, o semplicemente sia curioso di leggere il testo da un video, questo tutorial ti mostra esattamente come farlo con C# e Aspose.OCR. + +Nei prossimi minuti estrarremo i fotogrammi dal video, eseguiremo l'OCR su quei fotogrammi e infine visualizzeremo il testo dei sottotitoli fotogramma‑per‑fotogramma. Alla fine sarai in grado di **leggere il testo da file video**—inclusi MP4—senza dover cercare strumenti di terze parti. + +## Cosa costruiremo + +Creeremo una piccola applicazione console che: + +1. Decodifica un MP4 (o qualsiasi formato supportato) in singoli fotogrammi `Bitmap`. +2. Limita la regione OCR alla banda dei sottotitoli così il motore non è distratto dall’intera immagine. +3. Elabora ogni fotogramma con `VideoOcrProcessor` di Aspose. +4. Stampa il testo dei sottotitoli riconosciuto sulla console. + +Niente fronzoli, solo un esempio end‑to‑end funzionante che puoi inserire in un progetto reale. + +## Prerequisiti + +- **.NET 6.0** o successivo (il codice funziona anche su .NET Framework 4.7+). +- **Aspose.OCR for .NET** – installa via NuGet: `Install-Package Aspose.OCR`. +- Un file video (MP4 funziona benissimo). +- Un modo per decodificare i fotogrammi video – la demo usa un metodo placeholder, ma puoi collegare FFmpeg, OpenCV o qualsiasi libreria che restituisca oggetti `Bitmap`. + +> Pro tip: Se sei su Windows, il pacchetto `System.Drawing.Common` funziona bene per `Bitmap`. Su Linux/macOS avrai bisogno della dipendenza nativa `libgdiplus`. + +## Passo 1 – Estrarre i fotogrammi dal video + +Il primo ostacolo è trasformare un’immagine in movimento in immagini statiche. Il metodo `GetVideoFrames` qui sotto è lasciato intenzionalmente vuoto; sostituiscilo con il decoder che preferisci. Ecco uno schizzo rapido usando FFmpeg‑Core (solo per illustrare la forma dei dati): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Perché è importante:** Estrarre i fotogrammi fornisce al motore OCR un’immagine statica su cui lavorare, migliorando drasticamente l’accuratezza rispetto al tentativo di leggere direttamente dallo stream video. + +## Passo 2 – Configurare il VideoOcrProcessor + +Ora che abbiamo una sequenza di oggetti `Bitmap`, possiamo passarli ad Aspose.OCR. Il `VideoOcrProcessor` ci permette di definire una **Region of Interest (ROI)** – perfetta per i sottotitoli che di solito si trovano in alto o in basso al fotogramma. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Perché limitare la ROI?** Ignorando il resto dell’immagine riduciamo il rumore, diminuiamo i tempi di elaborazione e evitiamo falsi positivi da grafiche di sfondo. + +## Passo 3 – Eseguire l'OCR sulla sequenza di fotogrammi + +Con il processore pronto, alimentare i fotogrammi è una singola riga di codice. Il metodo `Process` restituisce un enumerable di oggetti `OcrResult`, ognuno contenente il testo riconosciuto per il relativo fotogramma. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Cosa succede dietro le quinte?** Aspose.OCR normalizza internamente ogni bitmap, esegue un riconoscitore basato su rete neurale e poi post‑processa l’output per migliorare punteggiatura e interruzioni di riga. + +## Passo 4 – Visualizzare il testo estratto + +Infine, iteriamo sui risultati e stampiamo ogni riga di sottotitolo. Potresti anche scriverle in un file SRT, in un database, o inviarle a un servizio di traduzione. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Esempio completo funzionante + +Mettendo tutto insieme otteniamo un programma console autonomo: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Output previsto (esempio)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Se l'OCR fatica con un fotogramma particolare, vedrai una stringa vuota – è un segnale per regolare la ROI o aumentare la frequenza di estrazione dei fotogrammi. + +## Problemi comuni e come risolverli + +| Problema | Perché accade | Soluzione | +|----------|----------------|-----------| +| **Caratteri spazzatura** | Fotogrammi a bassa risoluzione o compressione elevata | Estrarre i fotogrammi a bitrate più alto, o ingrandire il bitmap prima dell'OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **Nessun testo restituito** | La ROI non copre effettivamente la banda dei sottotitoli | Verificare le coordinate del rettangolo (usa uno strumento di screenshot per misurare). | +| **Collo di bottiglia delle prestazioni** | Elaborare ogni fotogramma a 30 fps è eccessivo | Sottocampionare a 1‑2 fps per la maggior parte dei flussi di sottotitoli; puoi comunque catturare ogni cambiamento di sottotitolo. | +| **FFmpeg non trovato** | `ffmpeg.exe` non è nel `PATH` | Specificare il percorso completo in `ProcessStartInfo.FileName` o installare FFmpeg globalmente. | + +## Estendere la soluzione + +- **Esportare in SRT** – concatenare i timestamp con il testo OCR e scrivere un file SubRip. +- **Supporto multilingua** – impostare `ocrProcessor.Language = OcrLanguage.Spanish` (o qualsiasi lingua supportata). +- **Elaborazione in tempo reale** – inviare i fotogrammi direttamente da uno stream live invece di leggerli da disco. + +Tutte queste varianti ruotano ancora attorno alle idee chiave di **estrarre fotogrammi dal video**, **leggere testo dal video** e **estrarre testo da mp4**. + +## Conclusione + +Abbiamo appena percorso un flusso di lavoro completo di **video subtitle ocr** in C#. Estrarre i fotogrammi dal video, concentrare l'OCR sulla banda dei sottotitoli e iterare sui risultati ti permette di leggere in modo affidabile **testo da file video** come MP4. Il codice è pronto per il copia‑incolla, e il design modulare ti consente di sostituire qualsiasi decoder di fotogrammi tu preferisca. + +Passi successivi? Prova a esportare i risultati in un file SRT, sperimenta con diverse dimensioni della ROI, o invia i sottotitoli a un’API di traduzione per didascalie multilingue. Il cielo è il limite una volta che hai padroneggiato le basi dell’estrazione di testo da video. + +Buon coding, e che i tuoi sottotitoli siano sempre cristallini! + +## Cosa dovresti imparare dopo? + +I tutorial seguenti trattano argomenti strettamente correlati che si basano sulle tecniche dimostrate in questa guida. Ogni risorsa include esempi di codice completi e funzionanti con spiegazioni passo‑passo per aiutarti a padroneggiare ulteriori funzionalità dell’API ed esplorare approcci di implementazione alternativi nei tuoi progetti. + +- [Estrai testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Estrai testo da immagine usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Estrai 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/net/ocr-configuration/_index.md b/ocr/japanese/net/ocr-configuration/_index.md index 841afa3c0..82ef2fe0d 100644 --- a/ocr/japanese/net/ocr-configuration/_index.md +++ b/ocr/japanese/net/ocr-configuration/_index.md @@ -61,6 +61,8 @@ Aspose.OCR で .NET の OCR 画像認識を活用し、フォルダー内の画 Aspose.OCR for .NET の強力な OCR 機能を活用し、画像からシームレスにテキストを抽出する方法を学びます。 ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) Aspose.OCR for .NET の可能性を引き出し、リストを使用した OCR 画像認識を手軽に実行し、アプリケーションの生産性とデータ抽出を向上させます。 +### [C# で Aspose OCR のバージョンを取得する – 完全ガイド](./get-aspose-ocr-version-in-c-complete-guide/) +C# コードで Aspose OCR の現在バージョン情報を取得し、表示する方法をステップバイステップで解説します。 ### 一般的なユースケース - **Extract text images** スキャンした請求書からテキストを抽出し、会計業務を自動化。 @@ -104,4 +106,4 @@ A: はい、`OcrResult` オブジェクトが各単語の信頼度スコアを {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/japanese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..50e51345d --- /dev/null +++ b/ocr/japanese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: シンプルなスニペットで C# から Aspose OCR のバージョンを取得します。OcrEngine.GetVersion を使用して + Aspose OCR ライブラリのバージョンを取得する方法を学びましょう。 +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: ja +og_description: C#でAspose OCRのバージョンをすばやく取得します。このチュートリアルでは、OcrEngine.GetVersion を使用して + Aspose OCR ライブラリのバージョンを取得する方法を正確に示します。 +og_title: C#でAspose OCRのバージョンを取得する – 完全ガイド +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: C#でAspose OCRのバージョンを取得する – 完全ガイド +url: /ja/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で Aspose OCR のバージョンを取得する – 完全ガイド + +.NET プロジェクト内で **Aspose OCR のバージョンを取得** する方法を考えたことはありませんか?バージョン不一致のトラブルシューティングをしているか、あるいは本番環境で実行されている正確なライブラリビルドをログに残したいだけかもしれません。理由は何であれ、ここが正しい場所です。 + +このチュートリアルでは、`OcrEngine.GetVersion()` を呼び出して結果を表示する、非常に小さく自己完結型の C# プログラムを順に解説します。最後まで読むと、バージョンの取得方法だけでなく、**Aspose OCR ライブラリ** のアップグレード時にバージョンを確認することで頭痛を防げる理由も理解できるようになります。 + +## 学べること + +- C# プロジェクトに Aspose.OCR NuGet パッケージを追加する +- `OcrEngine.GetVersion()` メソッドを使用する(**ocrengine getversion** エントリーポイント) +- 発生し得る例外を処理し、出力を検証する +- ロギングや条件付き機能トグルなど、実際のシナリオ向けにスニペットを拡張する + +OCR の事前知識は不要です—C# と Visual Studio(またはお好みの IDE)について基本的に理解していれば十分です。さあ、始めましょう。 + +--- + +## 手順 1: プロジェクトをセットアップし、Aspose OCR ライブラリを取得する + +OCR 関連の API を呼び出す前に、プロジェクトに **Aspose OCR ライブラリ** を参照設定する必要があります。 + +1. Visual Studio のターミナルまたはパッケージ マネージャ コンソールを開きます。 +2. 以下のコマンドを実行して、最新の安定版をインストールします: + +```bash +dotnet add package Aspose.OCR +``` + +> **プロのコツ:** .NET Core ではなく .NET Framework を対象としている場合は、NuGet パッケージ マネージャ UI を使用し、ランタイムに合ったバージョンを選択してください。このパッケージには、後で使用する `OcrEngine` クラスが含まれています。 + +### これが重要な理由 + +パッケージをインストールすると、ディスク上のアセンブリ バージョンが実行時にライブラリが報告するバージョンと異なる場合があります。コードでバージョンを問い合わせることで、CLR がロードした正確なビルドを取得でき、デバッグやコンプライアンス監査において重要です。 + +--- + +## 手順 2: **Aspose OCR のバージョンを取得** する最小コードを書く + +新しいコンソール アプリを作成します(`dotnet new console -n OcrVersionDemo`)し、デフォルトの `Program.cs` を以下の内容に置き換えます: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**各部分の説明** + +- `using Aspose.OCR;` は OCR 名前空間をスコープに持ち込み、`OcrEngine` を呼び出せるようにします。 +- `OcrEngine.GetVersion()` は **ocrengine getversion** 静的メソッドで、例として `"24.5.7"` のような文字列を返します。 +- 呼び出しを `try/catch` ブロックでラップすることで、実行時の予期せぬエラー(例: ターゲット マシンにネイティブ バイナリが見つからない)から保護します。 +- 文字列補間 `$"Aspose OCR version: {version}"` は、明確で人間が読みやすい行を出力します。 + +### 期待される出力 + +プロジェクト フォルダー内で `dotnet run` を実行すると、以下のような出力が表示されます: + +``` +Aspose OCR version: 24.5.7 +``` + +ライブラリがロードできない場合、エラー分岐が簡潔なメッセージを出力し、問題の特定を迅速に支援します。 + +--- + +## 手順 3: バージョンが NuGet パッケージと一致しているか確認する + +インストールした NuGet のバージョンが実行時に使用されていると想定しがちですが、環境固有の問題が介在することがあります。再確認するには: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +この追加スニペットを実行すると、次のような出力が得られます: + +``` +Assembly file version: 24.5.7.0 +``` + +もし 2 つの値が異なる場合、Global Assembly Cache (GAC) や以前のビルド フォルダーから古い DLL がロードされている可能性があります。その場合は、ソリューションをクリーン (`dotnet clean`) して再ビルドしてください。 + +--- + +## 手順 4: バージョンチェックを本番ロギングに組み込む + +実際のアプリケーションの多くはコンソールに出力するだけでなく、ログ ファイルやテレメトリ システムに書き込みます。以下は `Microsoft.Extensions.Logging` を使用した簡単な例です: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +これでバージョンが構造化ログに記録され、後で `{Version}` でフィルタリングしやすくなります。このパターンは、異なる OCR DLL を使用する可能性のある複数のマイクロサービスがある場合に特に便利です。 + +--- + +## よくある質問とエッジケース + +### `GetVersion()` が空文字列を返した場合は? + +これは通常、インストールが破損しているかネイティブ依存関係が欠如していることを示します。NuGet パッケージを再インストールし、`Aspose.OCR.Native.dll`(または該当するプラットフォーム固有のバイナリ)が実行ファイルと同じディレクトリにあることを確認してください。 + +### .NET Core 2.0 でもこのメソッドは動作しますか? + +はい、**Aspose OCR** は .NET Standard 2.0 以降をサポートしているため、その標準を実装している任意の .NET Core バージョンで `OcrEngine.GetVersion()` を呼び出すことができます。自己完結型アプリを公開する場合は、正しいランタイム識別子(`win‑x64`、`linux‑x64` など)を参照していることを確認してください。 + +### ライセンス ファイルなしでバージョンを取得できますか? + +もちろん可能です。`GetVersion()` はライセンスを必要とせず、単にライブラリのビルド番号を返します。ただし、有効なライセンスなしで OCR を実行しようとすると、実行時例外が発生します。そのため、スニペット内の `try/catch` は重要で、バージョンチェックを OCR 実行フローから分離します。 + +--- + +## 完全動作例(コピー&ペースト可能) + +以下は新しいコンソール プロジェクトにそのまま貼り付けられる完全プログラムです。オプションのロギング ブロックも含まれており、コンソール出力と構造化ログの両方を確認できます。 + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +`dotnet run` で実行すると、バージョンを確認する 2 行と、`LogLevel.Debug` を有効にした場合のデバッグ行が表示されます。 + +--- + +## 結論 + +C# 環境で **Aspose OCR のバージョンを取得** するために必要なすべてを網羅しました—**Aspose OCR ライブラリ** のインストール、**ocrengine getversion** メソッドの呼び出し、エラー処理、そして本番レベルのロギングへの埋め込みまで。この知識があれば、アプリケーションが使用している正確な OCR ビルドを確実に検証でき、バージョン関連のバグを回避し、コンプライアンス要件もスムーズに満たせます。 + +次のステップは?このバージョンチェックと実際の OCR 呼び出し(`OcrEngine` → `RecognizeImage`)を組み合わせ、バージョンと認識結果の両方をログに記録してみてください。また、他の Aspose 製品(PDF、Slides、Cells)でも **retrieve aspose version** パターンを調査し、スイート全体を同期させることも検討してください。 + +コーディングを楽しんで、OCR パイプラインが常に鋭く保たれますように! + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を応用した密接に関連するトピックを取り上げています。各リソースには、完全に動作するコード例とステップバイステップの解説が含まれており、追加の API 機能を習得し、プロジェクトで代替実装アプローチを探求するのに役立ちます。 + +- [Aspose.OCR for .NET で OCR 結果を取得する方法](/ocr/english/net/text-recognition/get-recognition-result/) +- [Aspose.OCR を使用した言語選択付き画像テキスト抽出(C#)](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR for .NET でリストを使って画像をバッチ OCR する方法](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/japanese/net/ocr-optimization/_index.md index 37e939040..7cbde4187 100644 --- a/ocr/japanese/net/ocr-optimization/_index.md +++ b/ocr/japanese/net/ocr-optimization/_index.md @@ -72,6 +72,8 @@ Aspose.OCR for .NET を探索し、前処理フィルタで OCR 精度を向上 Aspose.OCR for .NET で OCR 精度を強化します。スペルを修正し、辞書をカスタマイズし、エラーのないテキスト認識を簡単に実現します。 ### [マルチページ結果を文書として保存](./save-multipage-result-as-document/) Aspose.OCR for .NET の可能性を解き放ちます。この包括的なステップバイステップガイドで、マルチページ OCR 結果を文書として簡単に保存できます。 +### [Aspose OCR C# サンプル – GPU を有効化し、メモリ制限を設定、TIF 画像を処理](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +GPU を活用しメモリ上限を設定して、TIF 画像の OCR 処理を高速化する C# サンプルです。 ## よくある質問 diff --git a/ocr/japanese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/japanese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..9554873a8 --- /dev/null +++ b/ocr/japanese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,282 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# の例で、GPU メモリ制限の設定方法、OCR 用画像の読み込み、TIF ファイルからのテキスト認識をフルコードとヒント付きで示しています。 +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: ja +og_description: 完全なAspose OCR C#サンプルを学びましょう:GPUを有効にし、GPUメモリ上限を設定し、OCR用に画像を読み込み、TIFファイルからテキストを認識します。フルコードが含まれています。 +og_title: Aspose OCR C# サンプル – GPU 加速、メモリ制限、TIF 処理 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# サンプル – GPU を有効化、メモリ制限を設定、TIF 画像を処理 +url: /ja/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – GPU を有効化、メモリ制限を設定、TIF 画像を処理 + +大量の TIFF スキャンを扱うとき、**Aspose OCR C# example** のコードから最大のパフォーマンスを引き出す方法を考えたことはありますか? 多くの実務プロジェクト—例えばアーカイブのデジタル化や高解像度レシートからのデータ抽出—では、ボトルネックは OCR アルゴリズムそのものではなく、ハードウェアの活用方法にあります。 + +ポイントは次のとおりです。Aspose OCR は GPU アクセラレーションをサポートしていますが、使用できるメモリ量を明示的に指定し、適切な画像タイプをロードし、最終的に .tif ファイルから認識テキストを取得する必要があります。このチュートリアルでは、SDK のインストールから GPU 設定の調整まで、すべての手順を詳しく解説します。GPU の RAM を使い果たすことなく、超高速 OCR を実現できるようになります。 + +さらに、マルチページ TIFF の扱い方や GPU が存在しない環境で CPU にフォールバックする方法など、いくつかの「もしも」シナリオも紹介します。これにより、単なるワンショットのコードではなく、堅牢なソリューションが手に入ります。 + +## 必要なもの + +作業を始める前に、以下の項目がマシンに揃っていることを確認してください。 + +| 前提条件 | 重要な理由 | +|--------------|----------------| +| **.NET 6 SDK**(またはそれ以降) | Aspose OCR は .NET Standard 2.0+ を対象としているため、最近の .NET バージョンであれば動作します。 | +| **Aspose.OCR NuGet パッケージ** (`Install-Package Aspose.OCR`) | `OcrEngine`、`GpuSettings` などのコアライブラリです。 | +| **CUDA 11+**(NVIDIA) **または ROCm 5+**(AMD) | GPU アクセラレーションに必須です。SDK は実行時に互換性のあるドライバーをチェックします。 | +| **最低 2 GB VRAM を搭載した GPU**(ここでは 2048 MB に上限を設定) | メモリが不足するとエンジンは自動的に CPU にフォールバックします。 | +| **処理したい高解像度 TIFF 画像** | Aspose OCR は事実上すべてのラスタ形式を読み取れますが、スキャン画像では TIF が一般的です。 | +| Visual Studio 2022(またはお好みのエディタ) | C# プロジェクトのビルドとデバッグに使用します。 | + +これらのいずれかが欠けていてもコードはコンパイルできますが、期待するパフォーマンス向上は得られません。 + +## Step 1: Aspose OCR C# Example エンジンの作成 + +すべての **Aspose OCR C# example** の最初のステップは OCR エンジンのインスタンス化です。`OcrEngine` は映画の監督のようなものです—画像の読み込みからテキスト抽出まで全てを調整します。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **プロのコツ:** 連続して多数の画像を処理する場合は、`OcrEngine` を 1 つだけ保持してください。画像ごとにエンジンを再生成すると、OCR 時間をはるかに上回るオーバーヘッドが発生します。 + +## Step 2: GPU メモリ制限の設定(およびアクセラレーションの有効化) + +ここで多くの人が躓くポイント、**GPU メモリ制限の設定** です。デフォルトでは Aspose OCR は利用可能な VRAM をすべて使おうとしますが、共有ワークステーションでは他のアプリケーションがメモリ不足になる恐れがあります。`GpuSettings` オブジェクトを使って割り当て上限を設定できます。 + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### なぜメモリ制限を設定するのか? + +- **安定性:** 巨大画像を処理中のメモリ不足クラッシュを防止します。 +- **共存性:** TensorFlow など GPU を多用する他アプリと同時に動作させられます。 +- **予測可能性:** GPU がスワップしなくなるため、パフォーマンス測定が再現性を持ちます。 + +`MemoryLimitMb` を省略すると、Aspose は必要と判断した分だけメモリを確保します。専用の推論サーバーでは問題ありませんが、開発用ノート PC ではリスクがあります。 + +## Step 3: OCR 用画像のロード + +正しいファイル形式のロードは次に重要なステップです。`OcrImage.FromFile` は自動で画像タイプを判別しますが、ファイルの存在確認と、サポートされている TIFF バリアント(例: LZW 圧縮、CCITT‑G4)であることの検証は行っておくべきです。 + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### マルチページ TIFF の扱い方 + +TIFF に複数ページが含まれている場合、Aspose OCR はデフォルトで最初のページしか読み取りません。すべてのページを処理したいときは、`image.Pages`(新しい SDK バージョンで利用可能)をループし、各ページをエンジンに個別に渡します。 + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +上記スニペットは、シングルページでもマルチページでも機能する **load image for OCR** パターンを示しています。 + +## Step 4: TIF(または任意のラスタ画像)からテキストを認識 + +画像がメモリ上にロードされたら、Aspose に魔法をかけてもらいます。`Recognize` メソッドは `OcrResult` を返し、プレーンテキスト、信頼度スコア、必要に応じてバウンディングボックス情報も取得できます。 + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### TIF でうまく動作する理由 + +- **ロスレス圧縮:** TIFF は生のピクセルデータを保持することが多く、OCR エンジンに最高の忠実度を提供します。 +- **多彩なカラースペース:** Aspose はグレースケール、RGB、さらには CMYK TIFF も追加の変換コードなしで処理できます。 + +言語パック(例: フランス語や日本語)を使用したい場合は、`ocrEngine.Settings.Language = "fr"` のように `Recognize` 呼び出し前に設定してください。 + +## Step 5: 認識結果テキストの表示 + +最後に、テキストをコンソールへ出力します。実際のアプリケーションでは、データベースや JSON ファイルへの書き込み、あるいは下流の NLP パイプラインへの入力として利用することが多いでしょう。 + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### 期待される出力例 + +300 dpi の鮮明な印刷ページを処理した場合、次のような結果が得られます。 + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +画像がぼやけていたり、GPU メモリ制限が低すぎると、文字化けや結果の切れ端が見られることがあります。画像のフットプリント(6000×8000 ピクセルの TIFF で約 1 GB 程度)より `MemoryLimitMb` を下回ると、エンジンは自動的に CPU にフォールバックします。 + +## 完全動作サンプル + +以下はそのまま実行可能なプログラムです。新しいコンソール アプリ プロジェクトに貼り付け、`YOUR_DIRECTORY/large_photo.tif` を自分の TIFF パスに置き換えて **F5** を押してください。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### 確認チェックリスト + +- ✅ **Aspose OCR C# example** がエラーなくコンパイルできる。 +- ✅ **GPU が有効**(`Enable = true`)。 +- ✅ **GPU メモリ制限** が 2048 MB に設定されている。 +- ✅ **画像が TIF ファイル** からロードされている。 +- ✅ **テキストが認識され、コンソールに出力** される。 + +## よくある落とし穴と回避策 + +| 症状 | 考えられる原因 | 対策 | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA ランタイムが未インストール、またはバージョン不一致。 | ドライバーに合わせた CUDA 11.x(または 12.x)をインストール。 | +| OCR が空文字列を返す | 画像が暗すぎる、または DPI が 150 未満。 | `image.AdjustContrast()` でコントラスト調整、または 300 dpi にリサンプリング。 | +| GPU でメモリ不足クラッシュ | `MemoryLimitMb` が画像に対して低すぎる。 | 上限を引き上げるか、`image.Crop` でタイルに分割。 | +| `Unsupported image format` エラー | TIFF が JPEG‑2000 など特殊圧縮を使用。 | ImageMagick などでサポートされている形式に変換してから OCR にかける。 | + +## デモの拡張例 + +堅実な **aspose ocr c# example** が手に入ったので、次のような拡張に挑戦できます。 + +- **バッチ処理:** フォルダ内の TIF を順に走査し、各結果を `.txt` ファイルに書き出す。 +- **言語パック:** `ocrEngine.Settings.Language = "es"` でスペイン語、またはカスタム辞書をロード。 +- **バウンディングボックス:** `ocrResult.Regions` を利用して単語ごとの座標を取得—赤字消去ツールに便利。 +- **CPU フォールバック:** GPU ブロックを try/catch で囲み、失敗時に `ocrEngine.Settings.Gpu.Enable = false` に切り替えて再実行。 + +これらの拡張はコアパターンを保ちつつ、特定のユースケースに合わせた価値を追加します。 + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを基にした、関連性の高いトピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれているので、API の追加機能をマスターしたり、別の実装アプローチを自分のプロジェクトに取り入れたりする際に役立ちます。 + +- [画像からテキストを抽出する Aspose.OCR .NET の使い方](/ocr/english/net/image-and-drawing-recognition/) +- [画像からテキストを抽出 – Aspose.OCR for .NET による OCR 最適化](/ocr/english/net/ocr-optimization/) +- [言語選択付き C# で画像テキスト抽出 – Aspose.OCR の使用例](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/skew-angle-calculation/_index.md b/ocr/japanese/net/skew-angle-calculation/_index.md index 0a9b798ee..b967fba8c 100644 --- a/ocr/japanese/net/skew-angle-calculation/_index.md +++ b/ocr/japanese/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ C# アプリケーションで正確なテキスト認識を実現する強力 画像認識のための堅牢なソリューションである Aspose.OCR for .NET のパワーを解き放ちます。スキュー角度を簡単に計算する方法を学びましょう。 ### [OCR画像認識でURIからスキュー角度を計算](./calculate-skew-angle-from-uri/) Aspose.OCR for .NET を探索して、OCR 画像認識でスキュー角度を簡単に計算します。プロジェクトを正確かつ効率的に強化します。 +### [OCR 回転ドキュメント チュートリアル – 自動スキューと回転修正(C#)](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +C# で回転した画像のスキューと回転を自動的に補正し、正確な OCR 認識を実現する方法を学びます。 {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/japanese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..57a374e7e --- /dev/null +++ b/ocr/japanese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,262 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR を使用した C# の回転文書 OCR チュートリアルです。歪みの自動補正と回転検出の方法を示し、フルコードでステップバイステップに学べます。 +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: ja +og_description: OCR回転文書チュートリアルでは、Aspose OCRを使用してC#で歪みを自動的に補正し、回転を検出する方法を学べます。完全なガイドをご覧ください。 +og_title: OCR 回転文書チュートリアル – C#で自動傾き補正と回転修正 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR回転文書チュートリアル – C#で自動傾き補正と回転修正 +url: /ja/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 回転文書チュートリアル – C# 開発者向け完全ガイド + +スキャンしたフォームが横向きや斜めになっているときに **ocr rotated document tutorial** に出くわしたことはありませんか? あなたは一人ではありません。そのような歪んだ画像はクリーンなテキスト抽出を台無しにしますが、良いニュースは Aspose OCR が自動的に画像をまっすぐにしてくれることです。 + +このステップバイステップガイドでは `OcrEngine` を起動し、**automatic skew correction** と **auto detect rotation** を有効にして、回転した画像にエンジンを適用し、クリーンなテキストを出力します。最後まで読むと、各設定がなぜ重要なのか、エッジケースへの調整方法、そしてすぐに実行できる C# プログラムが手に入ります。 + +## 学べること + +* .NET プロジェクトで **Aspose OCR** をインストールし参照する方法。 +* `AutoCorrectSkew` と `AutoDetectRotation` を有効にすることが、信頼性の高い **ocr rotated document tutorial** の鍵である理由。 +* 任意の画像(JPG、PNG、TIFF)をロードし、エンジンに処理させる方法。 +* マルチページ PDF、低解像度スキャン、カスタム言語パックの取り扱いに関するヒント。 + +> **Prerequisites:** Visual Studio 2022(または任意の C# IDE)、.NET 6+ ランタイム、そして有効な Aspose OCR ライセンス(または無料トライアル)。OCR の事前知識は不要です。 + +## Step 1 – Install Aspose OCR and Set Up the Project + +まずは NuGet パッケージを取得します: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** トライアルライセンスを使用している場合は、`Aspose.OCR.lic` ファイルを実行ファイルと同じフォルダーに配置するか、`License license = new License(); license.SetLicense("Aspose.OCR.lic");` でプログラムから登録してください。 + +新しいコンソールアプリを作成します: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +これで **ocr rotated document tutorial** 用のクリーンな環境が整いました。 + +## Step 2 – Initialize the OCR Engine + +エンジンはプロセスの中心です。テキスト抽出のためのスイスアーミーナイフと考えてください。必要な機能を有効に指示すだけです。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Why these settings?** +* `AutoCorrectSkew` は文字のベースラインを解析し、行が水平になるように画像を適切に回転させます。 +* `AutoDetectRotation` は全体の向き(0°、90°、180°、270°)を判定し、逆さまの場合はページを反転させます。これらが無いと、エンジンは “pɹᴉʍ” のように読んでしまいます。 + +## Step 3 – Load the Image You Want to Process + +Aspose OCR は一般的なラスタ形式すべてに対応しています。プレースホルダーのパスを、回転したフォームの実際の場所に置き換えてください。 + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** マルチページ TIFF を受け取った場合は `OcrImage.FromMultiPageTiff(filePath)` を使用し、`image.Pages` をループしてください。 + +## Step 4 – Run the Recognition + +エンジンが魔法をかけます。まず画像を(スキュー/回転フラグのおかげで)まっすぐにし、次に文字を抽出します。 + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +英語以外の言語サポートが必要な場合は、`Recognize` を呼び出す前に設定してください: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Step 5 – Output the Recognized Text + +最後に、クリーンなテキストをコンソールに出力するか、ファイルやデータベースへパイプしてください。 + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Expected output**(サンプル画像に “Invoice #1234” が含まれていると仮定): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +元画像が 90° 回転し、少しスキューしていても、テキストが正しく表示されることに注目してください。 + +## Handling Common Pitfalls + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Blank output** | Skew correction disabled or image too dark. | Enable `AutoCorrectSkew` (already on) and increase image contrast via `image.AdjustContrast(1.2)`. | +| **Garbage characters** | Wrong language setting. | Set `ocrEngine.Settings.Language` to match the document language. | +| **Performance lag on large PDFs** | Engine processes each page sequentially. | Use `Parallel.ForEach` on `image.Pages` to leverage multi‑core CPUs. | +| **License exception** | Trial expired. | Acquire a permanent license or stay within the trial limits (5 pages per run). | + +## Pro Tips for a Robust OCR Rotated Document Tutorial + +* **Batch processing:** フロー全体をフォルダー パスを受け取り、すべての画像をループし、結果を `.txt` ファイルに書き出すメソッドでラップします。 +* **Pre‑processing:** ノイズが多いスキャンは認識前に `image.Denoise()` を適用すると効果的です。 +* **Post‑processing:** 正規表現を使って一般的な OCR 誤認を修正します。例: 文字に囲まれた “0” を “O” に置換。 +* **Logging:** Aspose OCR は `ocrEngine.Logger` を提供しています。ファイルロガーに接続して、低信頼度スコアに関する警告を記録しましょう。 + +## Complete, Ready‑to‑Run Code + +以下を `Program.cs` としてコンソールプロジェクト内に保存してください。すべての手順、コメント、バッチ処理用の小さなヘルパーが含まれています。 + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +実行します: + +```bash +dotnet run +``` + +コンソールにクリーンなテキストが表示され、**ocr rotated document tutorial** がエンドツーエンドで機能することが確認できます。 + +## Conclusion + +これで **ocr rotated document tutorial** が完成し、Aspose OCR を使ってスキュー補正と回転検出を自動化し、C# でクリーンなテキストを抽出できるようになりました。重要なポイントは、`AutoCorrectSkew` と `AutoDetectRotation` を有効にすることで、傾いたスキャンでも数行のコードで完璧に読める出力が得られることです。 + +ここからはバッチジョブに拡張したり、言語パックを統合したり、結果を下流の分析パイプラインに流し込んだりできます。**automatic skew correction** をさらに深掘りしたい場合は、Aspose の画像前処理 API を確認するか、ノイズが多いスキャン用にカスタム閾値を試してみてください。 + +PDF、マルチページ TIFF の取り扱いや Azure Functions との統合に関する質問があればコメントで教えてください。ハッピーコーディング! + +## What Should You Learn Next? + +以下のチュートリアルは、本ガイドで示したテクニックを基にした関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能を習得したり、代替実装アプローチを自分のプロジェクトに取り入れたりするのに役立ちます。 + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/japanese/net/text-recognition/_index.md index 5738b2ecf..35ae811aa 100644 --- a/ocr/japanese/net/text-recognition/_index.md +++ b/ocr/japanese/net/text-recognition/_index.md @@ -35,7 +35,7 @@ OCR 結果を JSON 形式で簡単に取得する方法を学び、Aspose.OCR fo ## OCR画像認識でPDFを認識する -Aspose.OCR を使用して、.NET での OCR の可能性を解き放ちます。 PDF からテキストを簡単に抽出し、アプリケーションにシームレスに統合します。このチュートリアルでは、PDF 内のテキストを認識し、シームレスで効率的な統合エクスペリエンスを保証するための包括的なガイドを提供します。 +Aspose.OCR を使用して、.NET での OCR の可能性を解き放ちます。 PDF からテキストを簡単に抽出します。今すぐダウンロードして、シームレスな統合エクスペリエンスを体験してください。 ## OCR画像認識でのテーブルの認識 @@ -53,11 +53,22 @@ Aspose.OCR for .NET のパワーを解放します。 OCR 結果を JSON 形式 Aspose.OCR を使用して .NET アプリケーションを強化し、画像テキストを効率的に認識します。正確な結果を得るには、OCR 領域検出モードを調べてください。 ### [OCR画像認識でPDFを認識する](./recognize-pdf/) Aspose.OCR を使用して、.NET での OCR の可能性を解き放ちます。 PDF からテキストを簡単に抽出します。今すぐダウンロードして、シームレスな統合エクスペリエンスを体験してください。 +### [Aspose OCRでPDFのOCRを実行する – 完全C#ガイド](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Aspose.OCR を使用して PDF からテキストを抽出し、C# で完全なガイドに従って実装方法を学びます。 ### [OCR画像認識でのテーブルの認識](./recognize-table/) -OCR 画像認識におけるテーブルの認識に関する包括的なガイドを使用して、Aspose.OCR for .NET の可能性を解き放ちます。 +OCR 画像認識におけるテーブルの認識に関する包括的なガイドを使用して、Aspose.OCR for .NET の可能性を解放ちます。 +### [Aspose OCRで画像のOCRを実行する – ヒンディー語ガイド](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Aspose OCR を使用して画像からテキストを抽出し、ヒンディー語のガイドに従って実装方法を学びます。 +### [Aspose の使用方法:OCR で画像を HTML に変換する](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Aspose.OCR を利用して画像を HTML に変換し、テキスト抽出結果をウェブページ形式で取得する手順を解説します。 +### [画像の OCR を実行し、C# で誤字単語を検出する](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Aspose.OCR を使用して画像からテキストを抽出し、C# でスペルチェックを行い、誤字を検出する手順を解説します。 +### [C# でのビデオ字幕 OCR – 完全ガイド](./video-subtitle-ocr-in-c-complete-guide/) +Aspose.OCR を使用して動画の字幕を OCR し、C# で抽出する方法をステップバイステップで解説します。 + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/japanese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..54efcea8c --- /dev/null +++ b/ocr/japanese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: Aspose を使用して画像を HTML に変換し、C# で画像からテキストを抽出する方法。画像から HTML を生成し、画像の OCR + を HTML にすばやく行う方法を学びましょう。 +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: ja +og_description: Asposeを使用して画像をHTMLに変換し、画像からテキストを抽出し、OCRで画像からHTMLを生成する方法(C#)。この完全ガイドに従ってください。 +og_title: Asposeの使い方:画像をOCRでHTMLに変換する +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: Aspose の使い方:画像を OCR で HTML に変換する +url: /ja/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose の使い方: OCR で画像を HTML に変換する方法 + +スキャンした画像をきれいな HTML に変換する方法を **Aspose の使い方** と疑問に思ったことはありませんか? 雑誌のページやレシート、手書きのメモなどがあり、テキストとレイアウトをウェブ公開用に保持したい場合です。良いニュースは、カスタムパーサーを書いたり低レベルの画像処理に苦労したりする必要がないことです—Aspose.OCR がその重い作業を代わりに行ってくれます。 + +このチュートリアルでは、**完全で実行可能なサンプル**を順に解説し、C# の Aspose OCR ライブラリを使用して **画像を HTML に変換**、**画像からテキストを抽出**、**画像から HTML を生成** の方法を示します。最後まで実行すれば、元のページレイアウトを保持した HTML ファイルを生成する小さなコンソールアプリが完成し、任意のウェブサイトにすぐに組み込めます。 + +## 前提条件 + +- **.NET 6.0 SDK** 以降(コードは .NET Core と .NET Framework の両方で動作します)。 +- **Visual Studio 2022**(またはお好みのエディタ)。 +- **Aspose.OCR for .NET** – NuGet でインストール: `dotnet add package Aspose.OCR`。 +- 変換したい画像ファイル(JPEG/PNG)、例: `magazine_page.jpg`。 + +追加の設定ファイルは不要です。ライブラリには OCR と HTML レイアウト生成に必要なものがすべて含まれています。 + +## 手順 1: プロジェクトのセットアップと Aspose.OCR の追加 + +まず、新しいコンソールプロジェクトを作成し、Aspose OCR パッケージを追加します。 + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Visual Studio を使用している場合は、プロジェクトを右クリック → *Manage NuGet Packages* → **Aspose.OCR** を検索してインストールするだけです。この手順により、**ocr image to html** が欠落した参照なしで実行できるようになります。 + +## 手順 2: OCR エンジンの初期化 + +プロセスの核心は `OcrEngine` クラスです。画像を読み取り、結果の出力方法を決定する脳のようなものと考えてください。 + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +ここでは `OcrEngine` をインスタンス化しています。無料版では認証情報を渡す必要はなく、ライブラリは組み込みの認識モデルを使用します。 + +## 手順 3: ソース画像の読み込み + +次に、処理したいファイルをエンジンに指定します。Aspose はほとんどの画像形式を処理できる便利な `OcrImage.FromFile` メソッドを提供しています。 + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +`YOUR_DIRECTORY` を画像が保存されている絶対パスまたは相対パスに置き換えてください。画像が実行ファイルと同じフォルダーにある場合は、単に `"magazine_page.jpg"` を使用できます。 + +## 手順 4: 認識とレイアウト付き HTML の要求 + +これがチュートリアルの核心です。`OutputFormat.HtmlWithLayout` を渡すことで、テキストブロック、画像、テーブルの元の位置を保持しながら **画像から HTML を生成** するよう Aspose に指示します。 + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text` プロパティには完全な HTML ドキュメントが格納されます。プレーンテキストだけが必要な場合は `OutputFormat.Text` を使用できますが、ここではレイアウト忠実度を保った **convert image to html** に焦点を当てています。 + +## 手順 5: HTML ファイルの保存 + +最後に、HTML 文字列をディスクに書き込みます。これで任意のブラウザで開けるすぐに使えるファイルが得られます。 + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +プログラムを実行すると `magazine.html` が生成されます。これを開くと、元画像に現れた通りにテキストが正確に配置されているのが確認でき、アーカイブやウェブ公開に最適です。 + +## 完全な動作例 + +以下は **complete, copy‑paste‑ready**(完全でコピー&ペースト可能)なプログラムです。抜け落ちた部分はなく、正しいパスを設定すればすぐにコンパイルして実行できます。 + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### 期待される出力 + +`magazine.html` をブラウザで開くと、以下のような(簡略化した)表示が見られるはずです: + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +正確な `style` 属性は元画像により異なりますが、構造は **extract text from image** と **generate html from image** が単一のシームレスなステップで実行されることを保証します。 + +## よくある質問とエッジケース + +### 画像が低解像度の場合は? + +Aspose.OCR は少なくとも **300 DPI** の画像で最適に動作します。ファイルがぼやけている場合は、OCR エンジンに渡す前に画像強化ライブラリ(例: ImageSharp)で前処理を試みてください。低品質は **extract text from image** の精度と生成された HTML レイアウトの忠実度の両方に影響します。 + +### OCR の言語を制御できますか? + +はい。`Recognize` を呼び出す前に `OcrEngine` の `Language` プロパティを設定します。 + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +非英語文字を扱う際の認識精度が向上します。 + +### HTML の代わりにプレーンテキストを取得するには? + +生の文字列だけが必要な場合は、`OutputFormat.HtmlWithLayout` を `OutputFormat.Text` に置き換えてください。同じ `recognitionResult.Text` には抽出された文字だけが含まれます。 + +### 生成された HTML に画像を埋め込む方法はありますか? + +`OutputFormat.HtmlWithLayoutAndImages` を使用すると、元画像を base‑64 データ URI として埋め込むことができます。外部アセットなしで単一の HTML ファイルにしたい場合に便利です。 + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### 大量バッチ処理はどうすれば? + +バッチ処理の場合は、ファイルパスのリストに対して `foreach` ループでロジックをラップします。同じ `OcrEngine` インスタンスを再利用することでオーバーヘッドが減り、**convert image to html** パイプラインが高速化します。 + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## 本番向けコードのヒント + +- **Dispose resources**: `OcrEngine` と `OcrImage` はどちらも `IDisposable` を実装しています。`using` 文でラップしてネイティブメモリを速やかに解放しましょう。 +- **Error handling**: ファイル関連の問題には `IOException`、認識の問題には `OcrException` をキャッチします。 +- **Performance**: 多数の画像を処理する場合は **parallelism**(`Parallel.ForEach`)を有効にすることを検討してください。ただし CPU 使用率に注意が必要です—OCR は CPU 集中型です。 +- **Logging**: ロガー(例: Serilog)を統合し、品質監視のために OCR の信頼度スコア(`recognitionResult.Confidence`)を記録します。 + +## 結論 + +ここでは **how to use Aspose** を使って **convert image to HTML**、**extract text from image**、**generate HTML from image** を数ステップで実現する方法を解説しました。完全なコードサンプルはレイアウトを保持したまま **ocr image to html** を行う方法を示しており、あらゆる文書デジタル化プロジェクトの堅実な基盤となります。 + +ここからは次のようなことが考えられます: + +- ニーズに合わせてさまざまな `OutputFormat` オプションを試す。 +- HTML 出力を CSS フレームワークと組み合わせてレスポンシブなスタイリングを行う。 +- 抽出したテキストを検索インデックスや機械学習パイプラインに投入する。 + +ぜひ試して設定を調整し、Aspose が画像をいかに簡単にウェブ対応コンテンツに変換するかをご体感ください。問題があればコメントを残してください—ハッピーコーディング! + +![画像から HTML レイアウトへの OCR パイプラインを示す図 – Aspose の使い方](/images/ocr-pipeline.png "Aspose の使い方") + +--- + + +## 次に学ぶべきことは? + +以下のチュートリアルは、本ガイドで示した手法を基にした密接に関連するトピックをカバーしています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、追加の API 機能を習得し、独自プロジェクトで代替実装アプローチを検討するのに役立ちます。 + +- [Aspose.OCR を使用した言語選択付き C# 画像テキスト抽出](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [画像からテキストへ変換 – URL から画像に対して OCR を実行](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [複数言語に対応した 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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/japanese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..24f84dfa5 --- /dev/null +++ b/ocr/japanese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR を使用して画像の OCR を実行し、画像からテキストを抽出します。単一の C# デモで、綴りミスを検出し、スペルの候補を取得する方法を学びます。 +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: ja +og_description: 画像に OCR を実行してテキストを抽出し、スペルミスを検出して Aspose.OCR を使用した C# でスペル候補を取得します。 +og_title: 画像でOCRを実行し、C#で誤字を検出する +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: 画像でOCRを実行し、C#でスペルミス単語を検出する +url: /ja/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 画像でOCRを実行し、C#でスペルミス単語を検出する + +Ever wondered how to **perform OCR on image** files without pulling your hair out? You're not the only one. Whether you're digitizing old letters, scanning receipts, or building a smart document workflow, extracting clean text from pictures is the first hurdle. The good news? With Aspose.OCR you can spin up a solution in minutes, and the bonus is you can also **detect misspelled words** and **get spelling suggestions** in the same run. + +このチュートリアルでは、**extracts text from image** を行い、英語のスペルチェッカーを実行し、各エラーを便利な修正案とともに出力する、完全に実行可能な C# コンソール アプリを順を追って解説します。最後まで読むと、**how to extract text** の方法、spell‑check API の呼び出し方、期待されるコンソール出力のイメージがすべて把握できます。 + +## What You’ll Build + +- Load a bitmap (or PNG) that contains typographical errors. +- Run Aspose.OCR to **perform OCR on image** and obtain raw string data. +- Initialise the built‑in English spell‑checker. +- **Detect misspelled words** and **get spelling suggestions** for each. +- Print a tidy report to the console. + +外部サービスは不要、面倒な HTTP 呼び出しも不要です。NuGet パッケージ 1 つと数行のコードだけで完結します。 + +## Prerequisites + +- .NET 6.0 SDK or later (the code also works on .NET Framework 4.7+). +- Visual Studio 2022 (or any editor you like). +- Aspose.OCR for .NET NuGet package (`Aspose.OCR`). +- An image file (`letter_with_typos.png`) placed somewhere you can reference it from the project. + +If you’ve never used Aspose before, don’t worry—installing the package is as easy as running: + +```bash +dotnet add package Aspose.OCR +``` + +Now let’s dive into the implementation. + +## Step 1: Set Up the Project and Install Aspose.OCR + +Create a new console project and pull in the OCR library: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +After the restore finishes, open `Program.cs`. We’ll replace the default content with the full demo code later, but first let’s talk about why each namespace matters. + +- `Aspose.OCR` – Core OCR engine and image handling. +- `Aspose.OCR.SpellCheck` – Spell‑checking utilities that ship with the library. +- `System` – Standard .NET base classes (e.g., `Console`). + +## Step 2: Load the Image and Perform OCR on Image + +The first real work is feeding the image to the OCR engine. Aspose.OCR reads many formats (PNG, JPEG, TIFF). Here’s the snippet that does the heavy lifting: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Why this matters:** `OcrImage.FromFile` abstracts away pixel‑level details, while `OcrEngine.Recognize` runs the trained neural model that translates visual glyphs into Unicode characters. The `ocrResult.Text` property now holds the raw string—exactly what you need to **extract text from image**. +> +> **Pro tip:** If your image contains multiple languages, you can set `ocrEngine.Language = OcrLanguage.Multilingual;` before calling `Recognize`. + +## Step 3: Initialise the English Spell‑Checker + +Aspose.OCR ships with a built‑in spell‑checking engine that understands English out of the box. Initialising it is a one‑liner: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Why this step is crucial:** The OCR output may include mis‑recognised characters (e.g., “l” vs “1”) or genuine typos from the source document. The spell‑checker will scan the string, locate suspicious tokens, and suggest alternatives. + +## Step 4: Detect Misspelled Words and Get Spelling Suggestions + +Now we feed the OCR text into the checker: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` is a collection where each entry contains the erroneous word and an array of possible corrections. + +## Step 5: Output the Results + +Finally, we iterate over the collection and print a human‑readable report: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Expected Console Output + +Assuming `letter_with_typos.png` contains the sentence: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Running the demo will produce something like: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Notice how each typo is paired with a handful of plausible fixes—exactly what you need when building a user‑friendly correction UI. + +## Full Working Example + +Below is the **complete, copy‑paste‑ready** program. Replace `YOUR_DIRECTORY` with the actual path to your image file. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Edge Cases to Consider** +> - **Empty Image:** If the OCR engine returns an empty string, `spellChecker.Check` will simply return an empty collection—no crash. +> - **Non‑English Text:** Swap `OcrLanguage.English` with `OcrLanguage.French` (or any supported language) to **detect misspelled words** in other locales. +> - **Large Documents:** For multi‑page PDFs, you’d loop over each page, perform OCR, then aggregate the results before spell‑checking. + +## Visual Overview (Image Alt Text) + +![画像でOCRを実行し、画像からテキストを抽出し、スペルミス単語を検出してスペル提案を行うフローを示す図](perform-ocr-on-image-flow.png) + +*The diagram above illustrates the end‑to‑end pipeline: image → OCR engine → raw text → spell‑checker → suggestions.* + +## Common Questions & Pro Tips + +| Question | Answer | +|----------|--------| +| **Do I need an internet connection?** | No. Aspose.OCR runs entirely locally; perfect for offline or secure environments. | +| **How accurate is the spell‑checker?** | It uses a dictionary of ~150k English words and fuzzy matching, so most common typos are caught. | +| **Can I customize the dictionary?** | Yes. `SpellChecker.AddUserDictionary("custom.txt")` lets you load domain‑specific terms (e.g., product names). | +| **What if the image is skewed?** | The OCR engine auto‑detects orientation, but you can manually call `ocrEngine.ImagePreprocessing.Rotate(angle)` for stubborn cases. | +| **Is there a way to highlight suggestions in UI?** | After you have the `misspellings` collection, you can map each `entry.Word` back to its position in `ocrResult.Text` and underline it in a RichTextBox or web view. | + +## Conclusion + +We’ve just shown you **how to perform OCR on image**, **extract text from image**, and then **detect misspelled words** while **getting spelling suggestions**—all with a concise C# console app. The core idea is simple: let Aspose.OCR do the heavy lifting of recognizing characters, then let its built‑in spell‑checker clean up the output. From here you can expand the demo into a full‑blown document processing service, integrate it with a web API, or plug it into a desktop editor. + +Ready for the next step? Try swapping the language to Spanish, feed a multi‑page PDF, or build a small WPF front‑end that lets users click a word to accept a suggestion. The building blocks are already in place—just keep experimenting. + +If you ran into any hiccups or have ideas for extensions, drop a comment below. Happy coding! + +## What Should You Learn Next? + +The following tutorials cover closely related topics that build on the techniques demonstrated in this guide. Each resource includes complete working code examples with step‑by‑step explanations to help you master additional API features and explore alternative implementation approaches in your own projects. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/japanese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..0756a11c0 --- /dev/null +++ b/ocr/japanese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-03 +description: C#で Aspose OCR を使用して画像の OCR を実行します。OCR 用に画像を読み込む方法と、オフラインでヒンディー語テキストを抽出する手順をステップバイステップのコードで学びましょう。 +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: ja +og_description: C#でAspose OCRを使用して画像のOCRを実行します。このチュートリアルでは、OCR用に画像を読み込み、オフラインでヒンディー語テキストを抽出する方法を、実行可能なコードとともに示します。 +og_title: 画像でOCRを実行 – Aspose OCR ヒンディー語ガイド +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Aspose OCRで画像のOCRを実行する – ヒンディー語ガイド +url: /ja/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCRで画像のOCRを実行 – ヒンディー語ガイド + +画像ファイルに対して **OCR を実行** したいが、ヒンディー文字を取得する方法が分からないことはありませんか? 初めてラテン文字以外のスクリプトを読み取ろうとする開発者は多く、この壁にぶつかります。良いニュースは、Aspose OCR を使えば非常に簡単に、しかも完全にオフラインで実行できることです。 + +このガイドでは **画像を OCR 用に読み込む** 方法、オフライン言語パックをエンジンに指定する手順、そしてインターネットに接続せずに **ヒンディー語テキスト画像** データを抽出する方法を解説します。最後には、ヒンディー語のレシートを読み取り、コンソールにテキストを出力する C# コンソールアプリが完成します。 + +## 必要なもの + +- **.NET 6.0** 以上(コードは .NET Framework 4.7+ でも動作します) +- **Aspose.OCR for .NET** NuGet パッケージ + `dotnet add package Aspose.OCR` +- **オフライン ヒンディー語リソース** が格納されたフォルダー(Aspose ポータルからダウンロード) +- ヒンディー語テキストが含まれる画像ファイル(例: `receipt_hindi.png`) + +以上だけです。外部サービスや API キーは不要で、シンプルなコードだけで完結します。 + +## 画像の OCR を実行 – 手順別実装 + +以下の 7 ステップに分けて解説します。各ステップでは **何を** 行うかだけでなく、**なぜ** それが重要かも説明します。 + +### Step 1: OCR エンジン インスタンスの作成 + +エンジンは Aspose OCR の中心です。インスタンス化することで、後で調整するすべての設定にアクセスできます。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Why?** +> `OcrEngine` がなければ `Recognize` を呼び出す対象がありません。これは後で画像をスキャンする「カメラ」のようなものです。 + +### Step 2: エンジンにオフラインリソースを指示 + +Aspose にはローカルに保存できる言語パックが同梱されています。`ResourcesFolder` にパスを設定すると、エンジンはそこからリソースを取得します。 + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tip:** +> 開発時は絶対パスを使用し、本番環境では相対パスまたは設定項目に置き換えると良いでしょう。 + +### Step 3: オフラインモードを強制 + +「オンライン検索を無効にすべきか?」と疑問に思うかもしれません。 +ファイアウォール内で作業する場合や、結果を確定させたい場合は `UseOfflineResources` を `true` に設定します。 + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> このフラグを `false` のままにすると、エンジンが追加データをダウンロードしようとし、レイテンシが増加し、セキュリティポリシーに抵触する可能性があります。 + +### Step 4: 認識言語としてヒンディー語を選択 + +ここでエンジンに **ヒンディー語テキスト画像** を認識させるために、対象言語を指定します。これにより精度が大幅に向上します。 + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Why it helps:** +> OCR エンジンは言語固有の文字モデルを使用します。ヒンディー語にロックすることで、エンジンが多数のスクリプトの中から推測する必要がなくなります。 + +### Step 5: OCR 用に画像を読み込む + +いよいよ **画像を OCR 用に読み込む** ステップです。`OcrImage.FromFile` メソッドはビットマップをエンジンが理解できる形式に変換します。 + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Common pitfall:** +> Windows でスラッシュ区切りのパスでも動作しますが、`Path.Combine` を使用するとプラットフォームに依存しないコードになります。 + +### Step 6: 認識を実行 + +すべての設定が整ったら、`Recognize` を呼び出して **画像の OCR を実行** します。 + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **What’s happening?** +> エンジンは各ピクセルを走査し、ヒンディー語のグリフデータベースと照合して Unicode 文字列を構築します。 + +### Step 7: 認識結果の出力 + +結果オブジェクトの `Text` プロパティに抽出された文字列が格納されます。これをコンソールに書き出すだけです。 + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Expected output:** +> `receipt_hindi.png` に “भुगतान सफल” が含まれていれば、コンソールはその行をそのまま表示し、結合文字も保持します。 + +## OCR 用に画像を読み込む – リソースの準備 + +エンジンにファイルではなくストリームを渡したい場合は、以下のように置き換えます。 + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Why use a stream?** +> ストリームを使うと、データベース、クラウドブロブ、埋め込みリソースに保存された画像を直接処理でき、スケーラブルなサービスに最適です。 + +## ヒンディー語テキスト画像 – エッジケースの対処 + +1. **言語パックが見つからない** – ヒンディー語パックが無いと `Recognize` が例外をスローします。try/catch で囲み、分かりやすいメッセージをログに残しましょう。 +2. **低解像度画像** – OCR の精度は 300 dpi 未満で低下します。読み込む前に画像をリサイズ・シャープ化して前処理してください。 +3. **混在言語ドキュメント** – 複数言語を有効化できます: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +これらの調整により、**画像の OCR を実行** するコードは本番環境でも堅牢に動作します。 + +## 完全なサンプルの実行 + +以下のファイルを `Program.cs` として保存し、プレースホルダーのパスを置き換えてから実行してください。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +`dotnet run` を実行すると、次のような出力が得られます: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +空文字列が出力された場合は、**ResourcesFolder** が `Hindi.traineddata` を含むフォルダーを指しているか、画像が十分に鮮明かを再確認してください。 + +## まとめ + +Aspose OCR を使って **画像の OCR を実行** する方法を、**画像を OCR 用に読み込む** から **ヒンディー語テキスト画像** の抽出まで、完全にオフラインで行う手順を解説しました。上記の実行可能コードは堅実な出発点となり、ストリーム利用、エラーハンドリング、マルチ言語対応のヒントは実務プロジェクトへの応用を助けます。 + +次のステップに進みませんか? 言語を **OcrLanguage.Tamil** に変更したり、Azure Blob Storage から画像を取得したりしてみましょう。また、`ImagePreprocessing` 設定を調整してノイズの多いレシートの精度を向上させることも可能です。 + +質問や問題があればコメントで教えてください—ハッピーコーディング! + +![Perform OCR on image example + + +## 次に学ぶべきこと + + +以下のチュートリアルは、本ガイドで示したテクニックを応用した関連トピックを扱っています。各リソースには、ステップバイステップの解説と完全な動作コード例が含まれており、API の追加機能をマスターしたり、代替実装アプローチを自分のプロジェクトに取り入れたりするのに役立ちます。 + +- [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/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/japanese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..58b656e6d --- /dev/null +++ b/ocr/japanese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR を使用して PDF の OCR を実行し、スキャンされた PDF を検索可能な PDF に変換します。PDF からテキストを認識し、数分で検索可能な + PDF を作成する方法を学びましょう。 +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: ja +og_description: PDFにOCRを実行し、すぐに検索可能なPDFを作成します。このチュートリアルでは、Aspose.OCRを使用してPDFからテキストを認識する方法をステップバイステップで示します。 +og_title: PDFでOCRを実行する – 完全なC#ガイド +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Aspose.OCRでPDFのOCRを実行する – 完全なC#ガイド +url: /ja/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.OCR を使用した PDF の OCR 実行 – 完全 C# ガイド + +PDF ファイルに **OCR を実行する方法** を、何十ものコマンドラインツールと格闘せずに知りたくありませんか? あなたは一人ではありません。請求書のデジタル化、古いレポートのアーカイブ、あるいはスキャンした契約書の検索可能なバージョンが必要なとき、静的な PDF を実際に検索できる形に変えることは大きな変化です。 + +このガイドでは、Aspose.OCR for .NET を使用して、スキャンした PDF(さらには単純な画像)から **検索可能な PDF** を作成する手順を解説します。最後まで読めば、数行の C# コードで **PDF からテキストを認識** できるようになり、各ステップの背景を理解できるので、独自のプロジェクトに応用できます。 + +> **クイック要点:** このプロセスは 3 つのことに集約されます—OCR エンジンの初期化、ソース(PDF または画像)の投入、検索可能な PDF の保存。さっそく見ていきましょう。 + +--- + +## 必要なもの + +開始する前に、以下を用意してください。 + +| 前提条件 | 理由 | +|--------------|----------------| +| **.NET 6.0+**(または .NET Framework 4.6+) | Aspose.OCR は最新ランタイムを対象としており、古いバージョンでは API の更新が欠ける可能性があります。 | +| **Aspose.OCR for .NET** NuGet パッケージ | `OcrEngine` クラスと PDF 処理ユーティリティを提供します。 | +| **有効な Aspose ライセンス**(または無料評価版) | ライセンスがないと 30 日間の評価制限と透かしが適用されます。 | +| **検索可能にしたいスキャン PDF**(または画像ファイル) | OCR の対象となるソースドキュメントです。 | +| **Visual Studio 2022**(または任意の C# エディタ) | デバッグが楽になりますが、任意の IDE でも構いません。 | + +ライブラリは次の NuGet コマンドでインストールできます。 + +```bash +dotnet add package Aspose.OCR +``` + +> **プロのコツ:** CI パイプラインで作業する場合は、ビルド成果物にライセンスファイルを含め、実行時にロードしてパスをハードコーディングしないようにしましょう。 + +--- + +## PDF で OCR を実行 – Aspose.OCR のセットアップ + +最初に必要なのは新しい `OcrEngine` インスタンスです。これはドキュメントを読み取る「脳」のようなものです。 + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +なぜ毎回新しいインスタンスが必要かというと、エンジンは言語設定などの構成情報を保持しており、ドキュメントごとに異なる場合があります。実行ごとにインスタンス化することでクリーンな状態が保証され、ジョブ間の干渉を防げます。 + +--- + +## 検索可能 PDF の作成 – パスワード設定(任意) + +PDF が保護されている場合、ページを読み取る前にエンジンにパスワードを伝える必要があります。 + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +保護されたファイルでこの手順を省略すると `PdfPasswordException` がスローされます。保護状態が不明な場合は必ず try‑catch で囲んでください。 + +--- + +## スキャン PDF を検索可能 PDF に変換 – ソースの読み込み + +Aspose.OCR は `OcrImage` 抽象化を使用し、PDF、TIFF、JPEG などをラップできます。スキャン PDF をメモリに読み込む方法は次のとおりです。 + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +内部では `FromFile` が各ページをラスタ画像に変換し、OCR エンジンが処理できる形にします。マルチページ PDF でもエンジンは自動的にすべてのページを走査します。 + +--- + +## PDF からテキストを認識 – OCR の実行 + +チュートリアルの核心です。エンジンにテキスト認識を指示し、検索可能 PDF を出力させます。 + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` を指定すると、エンジンは元のスキャン画像の上に見えないテキスト層を埋め込みます。結果の PDF はスキャンのビジュアル fidelity を保ちつつ、完全に検索可能になります—コンプライアンス監査に最適です。 + +--- + +## 画像を検索可能 PDF に変換 – 結果の保存 + +最後にバイナリデータをディスクに書き出します。 + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary` プロパティには生の PDF バイト列が格納されています。API を構築している場合は、これを直接 Web 応答のストリームに送ることも可能です。 + +--- + +![検索可能 PDF を作成する OCR 変換フローを示す図](https://example.com/ocr-flow.png "PDF で OCR を実行するフローダイアグラム") + +*画像代替テキスト: PDF で OCR を実行するフローダイアグラム。スキャン PDF が検索可能 PDF に変換される様子を示しています。* + +--- + +## エッジケースと実践的なヒント + +### 1. 大容量ファイルとメモリ管理 +100 MB を超える PDF を処理する場合は、`OcrEngineSettings.MemoryLimit` を使用してメモリ使用量を上限設定してください。さらに、ページをバッチ処理することで `OutOfMemoryException` を回避できます。 + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. 言語サポート +デフォルトでは Aspose.OCR は英語を想定しています。他言語を認識させるには `Language` プロパティを設定します。 + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. マルチスレッドシナリオ +`OcrEngine` は **スレッドセーフではありません**。並列処理が必要な場合は、スレッドごとに別々のエンジンを作成してください。 + +### 4. OCR 精度のデバッグ +`ocrResult` からプレーンテキストを抽出してデバッグできます。 + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +出力が文字化けしている場合は、`PreprocessSettings`(例: デスキュー、デスペックル)を調整して品質向上を試みてください。 + +### 5. ライセンスに関する注意点 +評価版を使用すると、Aspose は出力 PDF に透かしを追加します。アプリケーション起動時に早めにライセンスを登録しましょう。 + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## 完全動作サンプル – 最初から最後まで + +以下は、上記のすべてのポイントを組み込んだ、すぐに実行可能なコンソールアプリのコードです。新しいコンソールプロジェクトにコピー&ペーストして使用してください。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**期待される出力:** 実行後、コンソールにファイルの場所が表示されます。`output.pdf` を任意の PDF ビューアで開き、元のスキャンに含まれる単語を入力してみてください。文字がハイライトされれば、**PDF で OCR を実行し、検索可能なドキュメントを作成**できたことになります。 + +--- + +## よくある質問 + +**Q: 単一画像(PNG/JPEG)を検索可能 PDF に変換できますか?** +A: もちろん可能です。`OcrImage.FromFile("input.pdf")` を画像ファイルへのパスに置き換えるだけです。エンジンは画像をラスタ化し、同様に OCR 層を埋め込みます。 + +**Q: PDF にスキャンページとネイティブテキストの両方が混在している場合は?** +A: エンジンは既存のコンテンツ上に OCR テキストを重ねるため、ネイティブテキストは選択可能なまま、スキャンページは検索可能になります。 + +**Q: OCR の精度はどの程度ですか?** +A: 精度は元データの品質に依存します。高解像度(>300 dpi)のクリーンなスキャンであれば 95 % 以上の精度が期待できます。ノイズが多い文書では、`PreprocessSettings`(デスキュー、デスペックル)を有効にしてから `Recognize` を呼び出すと改善します。 + +--- + +## 次のステップ – OCR ツールキットの拡張 + +**PDF からテキストを認識**し、**スキャン PDF を検索可能 PDF に変換**できるようになったので、以下のトピックに挑戦してみてください。 + +- **バッチ処理**: フォルダ内の PDF をループし、自動で検索可能バージョンを生成。 +- **テキスト抽出**: `ocrResult.Text` を利用して検索インデックス(例: Elasticsearch)に投入。 +- **カスタム言語パック**: Aspose から追加の言語データをダウンロードし、アジア系文字をサポート。 +- **PDF/A 準拠**: Aspose.PDF と OCR 出力を組み合わせ、アーカイブ向け PDF を作成。 + +これらは本稿で扱った基本手順を基盤にしているため、すぐに実装に移せます。 + +--- + +## まとめ + +本稿では **Aspose.OCR を使用して PDF に OCR を実行**し、スキャン PDF を完全に検索可能な PDF に変換する方法を示しました。また、画像から検索可能 PDF への変換手順もカバーしました。コード + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示したテクニックを基にした、密接に関連するトピックを扱っています。各リソースには、ステップバイステップの説明と完全なコード例が含まれており、API の追加機能を習得したり、独自プロジェクトで代替実装を検討したりするのに役立ちます。 + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/japanese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..ed194c2f9 --- /dev/null +++ b/ocr/japanese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR を使用して、動画からフレームを抽出し、MP4 などの動画ファイルからテキストを読み取る方法を示すビデオ字幕 OCR + チュートリアル。 +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: ja +og_description: Aspose.OCRで動画字幕のOCRを学びましょう。動画からフレームを抽出し、動画内のテキストを読み取り、MP4からテキストを数分で抽出します。 +og_title: C#で動画字幕OCR – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: C#でのビデオ字幕OCR – 完全ガイド +url: /ja/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# におけるビデオ字幕 OCR 完全ガイド + +ビデオ字幕 OCR が必要だったが、どこから始めればいいかわからなかったことはありませんか? あなたは一人ではありません。講義録画をデジタル化したり、トレーニングビデオからキャプションを抽出したり、単にビデオからテキストを読むことに興味があるだけでも、このチュートリアルでは C# と Aspose.OCR を使って正確にやり方を示します。 + +次の数分でビデオからフレームを抽出し、これらのフレームに OCR を実行し、最終的に字幕テキストをフレームごとに表示します。最後まで読めば、**ビデオからテキストを読む**(MP4 を含む)ことが、サードパーティツールを探さずにできるようになります。 + +## 作成するもの + +小さなコンソールアプリを作ります。このアプリは: + +1. MP4(またはサポートされている任意の形式)を個々の `Bitmap` フレームにデコードします。 +2. OCR の対象領域を字幕バンドに限定し、エンジンが画像全体に惑わされないようにします。 +3. 各フレームを Aspose の `VideoOcrProcessor` で処理します。 +4. 認識された字幕テキストをコンソールに出力します。 + +余計な説明は省き、実際にプロジェクトに組み込めるエンドツーエンドのサンプルを提供します。 + +## 前提条件 + +- **.NET 6.0** 以上(コードは .NET Framework 4.7+ でも動作します)。 +- **Aspose.OCR for .NET** – NuGet でインストール: `Install-Package Aspose.OCR`。 +- ビデオファイル(MP4 が最適)。 +- ビデオフレームをデコードする手段 – デモではプレースホルダー メソッドを使用していますが、FFmpeg、OpenCV、または `Bitmap` オブジェクトを返す任意のライブラリを組み込めます。 + +> **プロのコツ:** Windows 環境では `System.Drawing.Common` パッケージが `Bitmap` に対して問題なく動作します。Linux/macOS ではネイティブの `libgdiplus` 依存関係が必要です。 + +## Step 1 – ビデオからフレームを抽出 + +最初のハードルは、動く映像を静止画像に変換することです。以下の `GetVideoFrames` メソッドは意図的に空欄にしていますので、お好みのデコーダで置き換えてください。以下は FFmpeg‑Core を使った簡易スケッチ例です(データ構造の形を示すだけです): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **なぜ重要か:** フレームを抽出することで OCR エンジンは静止画像を処理でき、ビデオストリームから直接読む場合に比べて精度が大幅に向上します。 + +## Step 2 – VideoOcrProcessor の設定 + +`Bitmap` オブジェクトのシーケンスが手に入ったら、Aspose.OCR に渡します。`VideoOcrProcessor` では **Region of Interest (ROI)** を定義でき、字幕が通常フレームの上部または下部にある場合に最適です。 + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **ROI を限定する理由:** 画像の残りの部分を無視することでノイズが減り、処理時間が短縮され、背景グラフィックによる誤検出を防げます。 + +## Step 3 – フレームシーケンスに対して OCR を実行 + +プロセッサの準備ができたら、フレームの投入はワンライナーです。`Process` メソッドは `OcrResult` オブジェクトの列挙可能オブジェクトを返し、各フレームに対応する認識テキストが含まれます。 + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **内部で何が起きているか:** Aspose.OCR は各ビットマップを正規化し、ニューラルネットワークベースの認識器で処理し、最後に句読点や改行を改善するポストプロセスを行います。 + +## Step 4 – 抽出したテキストを表示 + +最後に結果をイテレートして各字幕行を出力します。SRT ファイルへの書き出しやデータベース保存、翻訳サービスへの送信などにも応用できます。 + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### 完全動作サンプル + +すべてを組み合わせると、自己完結型のコンソールプログラムが完成します: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**期待される出力(サンプル)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +特定のフレームで OCR がうまくいかない場合は空文字列が出力されます。これは ROI を調整するか、フレーム抽出レートを上げるサインです。 + +## Common Pitfalls & How to Fix Them + +| 問題 | 発生理由 | 対策 | +|------|----------|------| +| **文字化け** | 解像度が低いフレームや過度の圧縮 | ビットレートを上げてフレームを抽出するか、OCR 前にビットマップを拡大 (`Bitmap.Clone(new Size(...), ...)`) | +| **テキストが返らない** | ROI が字幕バンドをカバーしていない | 矩形座標を確認(スクリーンショットツールで測定) | +| **パフォーマンスがボトルネック** | 30 fps すべてを処理している | 多くの字幕ストリームでは 1‑2 fps にダウンサンプリングすれば十分 | +| **FFmpeg が見つからない** | `ffmpeg.exe` が `PATH` に無い | `ProcessStartInfo.FileName` にフルパスを指定するか、FFmpeg をシステム全体にインストールする | + +## Extending the Solution + +- **SRT へエクスポート** – タイムスタンプと OCR テキストを結合し、SubRip ファイルを書き出す。 +- **多言語対応** – `ocrProcessor.Language = OcrLanguage.Spanish`(またはサポートされている任意の言語)を設定。 +- **リアルタイム処理** – ディスクから読む代わりにライブストリームからフレームを直接パイプする。 + +これらのバリエーションもすべて、**ビデオからフレームを抽出する**、**ビデオからテキストを読む**、**mp4 からテキストを抽出する** というコアアイデアに基づいています。 + +## Conclusion + +本稿では C# における **ビデオ字幕 OCR** ワークフローを完全に解説しました。ビデオからフレームを抽出し、字幕バンドに OCR を限定し、結果をイテレートすることで、MP4 などのビデオファイルから確実に **テキストを読む** ことができます。コードはコピー&ペースト可能で、モジュラー設計により好きなフレームデコーダに差し替えられます。 + +次のステップは? 結果を SRT ファイルにエクスポートしたり、ROI のサイズを変えて実験したり、字幕を翻訳 API に送って多言語キャプションを作成したりしてみてください。テキスト抽出の基本をマスターすれば、可能性は無限です。 + +Happy coding, and may your subtitles always be crystal‑clear! + +## 次に学ぶべきこと + +以下のチュートリアルは、本ガイドで示した手法を応用した関連トピックを扱っています。各リソースには完全な動作コード例とステップバイステップの解説が含まれており、API の追加機能を習得したり、別の実装アプローチを自分のプロジェクトで試したりするのに役立ちます。 + +- [Aspose.OCR を使用した言語選択付き画像テキスト抽出(C#)](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR .NET を使用した画像からのテキスト抽出](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/korean/net/ocr-configuration/_index.md index 5340ef148..b4e3187ec 100644 --- a/ocr/korean/net/ocr-configuration/_index.md +++ b/ocr/korean/net/ocr-configuration/_index.md @@ -60,7 +60,9 @@ Aspose.OCR을 사용해 .NET에서 폴더에 저장된 이미지에서 텍스트 ### [언어 선택과 함께하는 OCR 이미지 인식 작업](./ocr-operation-with-language-selection/) Aspose.OCR for .NET으로 강력한 OCR 기능을 활용해 이미지에서 텍스트를 원활히 추출하는 방법을 소개합니다. ### [리스트와 함께하는 OCR 이미지 인식 작업](./ocr-operation-with-list/) -Aspose.OCR for .NET을 이용해 리스트 기반 OCR 이미지 인식을 손쉽게 수행하고, 애플리케이션의 생산성과 데이터 추출 효율을 높이는 방법을 제공합니다. +Aspose.OCR for .NET을 이용해 리스트 기반 OCR 이미지 인식을 손쉽게 수행하고, 애플리케이션의 생산성과 데이터 추출 효율을 높이는 방법을 제공합니다. +### [C#에서 Aspose OCR 버전 가져오기 – 완전 가이드](./get-aspose-ocr-version-in-c-complete-guide/) +C# 코드에서 현재 사용 중인 Aspose OCR 라이브러리 버전을 확인하는 방법을 단계별로 안내합니다. ### 일반적인 사용 사례 - **스캔된 청구서 이미지**에서 텍스트를 추출해 자동 회계 처리. @@ -101,4 +103,4 @@ A: 네, `OcrResult` 객체가 신뢰도 값을 제공하므로 프로그래밍 {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/korean/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a8505812a --- /dev/null +++ b/ocr/korean/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: 간단한 코드 조각으로 C#에서 Aspose OCR 버전을 가져옵니다. OcrEngine GetVersion을 사용하여 Aspose + OCR 라이브러리 버전을 검색하는 방법을 배워보세요. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: ko +og_description: C#에서 Aspose OCR 버전을 빠르게 가져옵니다. 이 튜토리얼에서는 OcrEngine GetVersion을 사용해 + Aspose OCR 라이브러리 버전을 정확히 검색하는 방법을 보여줍니다. +og_title: C#에서 Aspose OCR 버전 받기 – 완전 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: C#에서 Aspose OCR 버전 가져오기 – 완전 가이드 +url: /ko/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 Aspose OCR 버전 가져오기 – 완전 가이드 + +.NET 프로젝트 안에서 **Aspose OCR 버전**을 가져오는 방법이 궁금하셨나요? 버전 불일치를 해결하거나, 프로덕션에서 실행 중인 정확한 라이브러리 빌드를 로그에 남기고 싶을 때도 있겠죠. 어떤 이유든, 여기서 답을 찾으실 수 있습니다. + +이 튜토리얼에서는 `OcrEngine.GetVersion()`을 호출하고 결과를 출력하는 작고 독립적인 C# 프로그램을 단계별로 살펴봅니다. 끝까지 읽으시면 버전을 **어떻게** 가져오는지뿐만 아니라, **왜** 버전 확인이 Aspose OCR 라이브러리를 업그레이드할 때 큰 도움이 되는지도 알게 됩니다. + +## 배울 내용 + +- C# 프로젝트에 Aspose.OCR NuGet 패키지를 추가하기 +- `OcrEngine.GetVersion()` 메서드(**ocrengine getversion** 진입점) 사용하기 +- 발생 가능한 예외 처리 및 출력 확인하기 +- 로깅이나 조건부 기능 토글 등 실제 시나리오에 코드 스니펫 확장하기 + +OCR에 대한 사전 경험은 필요하지 않습니다—C#과 Visual Studio(또는 선호하는 IDE)만 기본적으로 알면 됩니다. 시작해볼까요. + +--- + +## Step 1: 프로젝트 설정 및 Aspose OCR 라이브러리 가져오기 + +OCR 관련 API를 호출하기 전에 **Aspose OCR 라이브러리**를 프로젝트에 참조해야 합니다. + +1. Visual Studio에서 터미널이나 패키지 관리자 콘솔을 엽니다. +2. 다음 명령을 실행하여 최신 안정 버전을 설치합니다: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** .NET Core 대신 .NET Framework를 대상으로 하는 경우, NuGet 패키지 관리자 UI를 사용하고 런타임에 맞는 버전을 선택하세요. 이 패키지에는 나중에 사용할 `OcrEngine` 클래스가 포함되어 있습니다. + +### 왜 중요한가요 + +패키지를 설치하면 디스크에 있는 어셈블리 버전이 런타임에 라이브러리가 보고하는 버전과 다를 수 있습니다. 코드로 버전을 조회하면 CLR이 실제 로드한 정확한 빌드를 확인할 수 있어 디버깅 및 규정 준수 감사에 필수적입니다. + +--- + +## Step 2: **Aspose OCR 버전**을 가져오는 최소 코드 작성 + +새 콘솔 앱(`dotnet new console -n OcrVersionDemo`)을 만들고 기본 `Program.cs`를 다음 내용으로 교체합니다: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**각 부분에 대한 설명** + +- `using Aspose.OCR;`는 OCR 네임스페이스를 가져와 `OcrEngine`을 사용할 수 있게 합니다. +- `OcrEngine.GetVersion()`은 **ocrengine getversion** 정적 메서드로, `"24.5.7"`과 같은 문자열을 반환합니다. +- `try/catch` 블록으로 감싸면 런타임에서 발생할 수 있는 예외—예를 들어 네이티브 바이너리를 찾지 못했을 때—를 안전하게 처리할 수 있습니다. +- 보간 문자열 `$"Aspose OCR version: {version}"`은 사람이 읽기 쉬운 형태로 출력합니다. + +### 예상 출력 + +프로젝트 폴더에서 `dotnet run`을 실행하면 다음과 유사한 결과가 표시됩니다: + +``` +Aspose OCR version: 24.5.7 +``` + +라이브러리를 로드하지 못하면 오류 분기에서 간결한 메시지가 출력되어 문제를 빠르게 파악할 수 있습니다. + +--- + +## Step 3: NuGet 패키지와 버전 일치 여부 확인 + +설치한 NuGet 버전이 런타임에 실제 사용되는 버전이라고 가정하기 쉽지만, 환경에 따라 차이가 발생할 수 있습니다. 다시 한 번 확인하려면: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +위 추가 스니펫을 실행하면 다음과 같은 출력이 나타납니다: + +``` +Assembly file version: 24.5.7.0 +``` + +두 값이 다르면 이전 빌드 폴더나 GAC(Global Assembly Cache)에서 오래된 DLL을 로드하고 있는 것입니다. 이 경우 `dotnet clean`으로 솔루션을 정리하고 다시 빌드하세요. + +--- + +## Step 4: 프로덕션 로깅에 버전 체크 삽입하기 + +실제 애플리케이션은 콘솔에만 출력하지 않고 로그 파일이나 텔레메트리 시스템에 기록합니다. `Microsoft.Extensions.Logging`을 활용한 간단한 예시는 다음과 같습니다: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +이제 구조화된 로그에 버전이 포함되어 `{Version}`으로 쉽게 필터링할 수 있습니다. 여러 마이크로서비스가 서로 다른 OCR DLL을 사용할 때 특히 유용합니다. + +--- + +## Common Questions & Edge Cases + +### `GetVersion()`이 빈 문자열을 반환한다면? + +보통 설치가 손상되었거나 네이티브 종속성이 누락된 경우입니다. NuGet 패키지를 재설치하고 `Aspose.OCR.Native.dll`(또는 해당 플랫폼 전용 바이너리)이 실행 파일과 같은 디렉터리에 있는지 확인하세요. + +### .NET Core 2.0에서도 메서드가 동작하나요? + +네, **Aspose OCR**은 .NET Standard 2.0 이상을 지원하므로 해당 표준을 구현한 모든 .NET Core 버전에서 `OcrEngine.GetVersion()`을 호출할 수 있습니다. 자체 포함 앱을 배포할 경우 올바른 런타임 식별자(`win-x64`, `linux-x64` 등)를 지정하는 것을 잊지 마세요. + +### 라이선스 파일 없이 버전을 가져올 수 있나요? + +물론입니다. `GetVersion()`은 **라이선스가 필요하지 않으며** 단순히 라이브러리 빌드 번호만 반환합니다. 다만, 유효한 라이선스 없이 OCR을 수행하면 런타임 예외가 발생합니다. 따라서 스니펫의 `try/catch`는 버전 확인을 OCR 실행 흐름과 분리하는 데 유용합니다. + +--- + +## Full Working Example (Copy‑Paste Ready) + +아래는 새 콘솔 프로젝트에 바로 넣어 사용할 수 있는 전체 프로그램입니다. 선택적인 로깅 블록도 포함돼 있어 콘솔 출력과 구조화 로그를 동시에 확인할 수 있습니다. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +`dotnet run`으로 실행하면 버전을 확인하는 두 줄과, `LogLevel.Debug`를 활성화했을 때 나타나는 디버그 라인이 출력됩니다. + +--- + +## Conclusion + +C# 환경에서 **Aspose OCR 버전**을 가져오는 방법—**Aspose OCR 라이브러리** 설치, **ocrengine getversion** 메서드 호출, 오류 처리, 프로덕션 수준 로깅 삽입—을 모두 다뤘습니다. 이제 애플리케이션이 사용하는 정확한 OCR 빌드를 신뢰성 있게 검증하고, 버전 관련 버그를 예방하며, 규정 준수 요구사항도 손쉽게 충족할 수 있습니다. + +다음 단계는 이 버전 체크를 실제 OCR 호출(`OcrEngine` → `RecognizeImage`)과 결합해 버전과 인식 결과를 함께 로그에 남기는 것입니다. 또한 **retrieve aspose version** 패턴을 다른 Aspose 제품(PDF, Slides, Cells)에도 적용해 전체 제품군을 일관되게 관리해 보세요. + +행복한 코딩 되시고, OCR 파이프라인이 언제나 날카롭게 유지되길 바랍니다! + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 배운 기술을 확장하는 내용으로, 완전한 코드 예제와 단계별 설명을 제공하여 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 돕습니다. + +- [Aspose.OCR for .NET에서 OCR 결과 가져오기](/ocr/english/net/text-recognition/get-recognition-result/) +- [Aspose.OCR을 사용한 언어 선택 이미지 텍스트 추출 C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR for .NET에서 List를 이용한 이미지 배치 OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/korean/net/ocr-optimization/_index.md index 68a12ee39..c278c6b5b 100644 --- a/ocr/korean/net/ocr-optimization/_index.md +++ b/ocr/korean/net/ocr-optimization/_index.md @@ -68,6 +68,8 @@ Aspose.OCR for .NET를 탐색하세요. 전처리 필터로 OCR 정확도를 높 Aspose.OCR for .NET로 OCR 정확도를 향상시키세요. 철자를 교정하고, 사전을 사용자 정의하며, 오류 없는 텍스트 인식을 손쉽게 달성합니다. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) Aspose.OCR for .NET의 잠재력을 활용하세요. 이 포괄적인 단계별 가이드를 통해 다중 페이지 OCR 결과를 문서로 손쉽게 저장합니다. +### [Aspose OCR C# 예제 – GPU 활성화, 메모리 제한 설정 및 TIF 이미지 처리](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +GPU를 활용하고 메모리 제한을 설정하여 TIF 이미지를 효율적으로 처리하는 Aspose OCR C# 예제입니다. ## 자주 묻는 질문 @@ -75,7 +77,7 @@ Aspose.OCR for .NET의 잠재력을 활용하세요. 이 포괄적인 단계별 A: 예, Aspose.OCR은 다양한 언어를 지원하며 혼합 언어 콘텐츠를 인식하도록 구성할 수 있습니다. **Q: 전처리가 정확도를 어떻게 향상시키나요?** -A: 이진화, 잡음 제거, 기울기 보정과 같은 필터가 이미지를 정화하여 노이즈를 줄이고 텍스트를 정렬함으로써 인식률을 높입니다. +A: 이진화, 잡음 제거, 기울기 보정과 같은 필터가 이미지를 정화하여 노이즈를 줄이고 텍스트를 정렬함으로써 인식률을 높습니다. **Q: 한 번에 처리할 수 있는 페이지 수에 제한이 있나요?** A: 명확한 제한은 없으며, 성능은 시스템 리소스에 따라 달라집니다. 매우 큰 배치의 경우 페이지를 여러 구간으로 나누어 처리하는 것을 고려하세요. diff --git a/ocr/korean/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/korean/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..d0717f200 --- /dev/null +++ b/ocr/korean/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-03 +description: GPU 메모리 제한을 설정하고, OCR을 위해 이미지를 로드하며, TIF 파일에서 텍스트를 인식하는 전체 코드와 팁을 포함한 + Aspose OCR C# 예제. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: ko +og_description: '전체 Aspose OCR C# 예제를 배우세요: GPU 활성화, GPU 메모리 제한 설정, OCR용 이미지 로드 및 + TIF 파일에서 텍스트 인식. 전체 코드 포함.' +og_title: Aspose OCR C# 예제 – GPU 가속, 메모리 제한 및 TIF 처리 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# 예제 – GPU 활성화, 메모리 제한 설정 및 TIF 이미지 처리 +url: /ko/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – GPU 활성화, 메모리 제한 설정 및 TIF 이미지 처리 + +대용량 TIFF 스캔을 다룰 때 **Aspose OCR C# example** 코드에서 최고의 성능을 끌어내는 방법이 궁금하셨나요? 여러분만 그런 것이 아닙니다. 실제 프로젝트—예를 들어 아카이브 디지털화나 고해상도 영수증에서 데이터 추출—에서 병목 현상은 OCR 알고리즘 자체가 아니라 하드웨어 활용도입니다. + +Aspose OCR은 GPU 가속을 지원하지만, 사용 가능한 메모리를 명시하고, 올바른 이미지 타입을 로드한 뒤, .tif 파일에서 인식된 텍스트를 추출해야 합니다. 이 튜토리얼은 SDK 설치부터 GPU 설정 조정까지 모든 단계를 차근차근 안내하여, GPU RAM을 초과하지 않으면서도 OCR을 초고속으로 실행할 수 있게 도와줍니다. + +또한 다중 페이지 TIFF 처리나 GPU가 없을 때 CPU로 폴백하는 등 몇 가지 “what if” 시나리오도 다루어, 일회성 스니펫이 아닌 견고한 솔루션을 만들 수 있도록 합니다. + +## 필요 사항 + +시작하기 전에 아래 항목들이 머신에 준비되어 있는지 확인하세요: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6 SDK** (or later) | Aspose OCR은 .NET Standard 2.0+을 타깃으로 하므로 최신 .NET 버전이면 모두 동작합니다. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | `OcrEngine`, `GpuSettings` 등을 제공하는 핵심 라이브러리입니다. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | GPU 가속에 필수이며, 런타임에 호환 드라이버를 확인합니다. | +| **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | 메모리가 부족하면 엔진이 조용히 CPU로 폴백할 수 있습니다. | +| **high‑resolution TIFF** image you want to process | Aspose OCR은 거의 모든 래스터 포맷을 읽을 수 있지만, 스캔에는 TIF가 일반적입니다. | +| Visual Studio 2022 (or any editor you like) | C# 프로젝트를 빌드하고 디버깅하기 위해 필요합니다. | + +위 항목 중 하나라도 누락되면 코드는 컴파일되지만, 기대하는 성능 향상을 확인할 수 없습니다. + +## Step 1: Create the Aspose OCR C# Example Engine + +모든 **Aspose OCR C# example**의 첫 단계는 OCR 엔진을 인스턴스화하는 것입니다. `OcrEngine`을 영화 감독에 비유하면, 이미지 로드부터 텍스트 추출까지 모든 과정을 조율합니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** 여러 이미지를 연속으로 처리할 경우, 단일 `OcrEngine`을 계속 유지하세요. 이미지당 엔진을 재생성하면 OCR 시간보다 훨씬 큰 오버헤드가 발생합니다. + +## Step 2: Set GPU Memory Limit (and Enable Acceleration) + +많은 사람들이 놓치는 부분, 바로 **GPU 메모리 제한 설정**입니다. 기본적으로 Aspose OCR은 사용 가능한 모든 VRAM을 사용하려고 하는데, 공유 워크스테이션에서는 다른 애플리케이션이 메모리 부족에 빠질 수 있습니다. `GpuSettings` 객체를 사용해 할당량을 제한할 수 있습니다. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### 왜 메모리 제한을 설정해야 할까요? + +- **Stability:** 거대한 이미지를 처리할 때 메모리 부족으로 인한 크래시를 방지합니다. +- **Co‑existence:** TensorFlow 모델 등 다른 GPU 집약형 애플리케이션과 동시에 실행할 수 있게 합니다. +- **Predictability:** GPU가 스와핑을 시작하지 않으므로 성능 테스트가 재현 가능해집니다. + +`MemoryLimitMb`를 생략하면 Aspose는 필요하다고 판단되는 만큼 메모리를 할당합니다. 전용 추론 서버에서는 괜찮지만, 개발자 노트북에서는 위험할 수 있습니다. + +## Step 3: Load Image for OCR + +올바른 파일 포맷을 로드하는 것이 다음 핵심 단계입니다. `OcrImage.FromFile` 메서드는 이미지 타입을 자동으로 감지하지만, 파일 존재 여부와 지원되는 TIFF 변형(LZW‑compressed 또는 CCITT‑G4 등)을 확인하는 것이 좋습니다. + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### 다중 페이지 TIFF 처리 + +TIFF에 여러 페이지가 포함돼 있다면, Aspose OCR은 기본적으로 첫 페이지만 읽습니다. 모든 페이지를 처리하려면 `image.Pages`(신버전 SDK에서 제공)를 순회하면서 각 페이지를 엔진에 개별적으로 전달하면 됩니다. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +위 스니펫은 단일 페이지와 다중 페이지 파일 모두에 적용 가능한 **load image for OCR** 패턴을 보여줍니다. + +## Step 4: Recognize Text from TIF (or any raster) + +이미지가 메모리에 로드되었으니 이제 Aspose에게 마법을 부여하도록 요청합니다. `Recognize` 메서드는 `OcrResult`를 반환하며, 여기에는 순수 텍스트, 신뢰도 점수, 필요 시 바운딩 박스 정보가 포함됩니다. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### 왜 TIF와 잘 맞는가? + +- **Lossless compression:** TIFF는 원시 픽셀 데이터를 저장하는 경우가 많아 OCR 엔진에 가장 높은 충실도를 제공합니다. +- **Multiple color spaces:** Aspose는 그레이스케일, RGB, 심지어 CMYK TIFF도 별도 변환 코드 없이 처리합니다. + +언어 팩을 바꾸고 싶다면 `ocrEngine.Settings.Language = "fr"`와 같이 `Recognize` 호출 전에 설정하면 됩니다. + +## Step 5: Display the Recognized Text + +마지막으로 콘솔에 텍스트를 출력합니다. 실제 애플리케이션에서는 데이터베이스, JSON 파일에 저장하거나 downstream NLP 파이프라인에 전달할 수 있습니다. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Expected output + +300 dpi로 스캔한 깨끗한 인쇄 페이지를 실행했을 때 일반적으로 다음과 같은 결과가 나타납니다: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +이미지가 흐리거나 GPU 메모리 제한이 너무 낮으면 깨진 문자나 결과가 잘릴 수 있습니다. `MemoryLimitMb`를 이미지 크기(예: 6000×8000 픽셀 TIFF는 약 1 GB)보다 낮게 설정하면 엔진이 자동으로 CPU로 폴백합니다. + +## Full Working Example + +아래는 완전한 실행 가능한 프로그램입니다. 새 Console App 프로젝트에 복사·붙여넣기하고, `YOUR_DIRECTORY/large_photo.tif`를 자신의 TIFF 경로로 바꾼 뒤 **F5**를 눌러 실행하세요. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Quick checklist + +- ✅ **Aspose OCR C# example** compiled without errors. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** set to 2048 MB. +- ✅ **Image loaded** from a TIF file. +- ✅ **Text recognized** and printed. + +## Common Pitfalls & How to Avoid Them + +| Symptom | Likely cause | Fix | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA runtime not installed or version mismatch. | Install CUDA 11.x (or 12.x) matching your driver. | +| OCR returns empty string | Image is too dark or DPI < 150. | Pre‑process with `image.AdjustContrast()` or resample to 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` too low for the image. | Raise the limit or split the image into tiles via `image.Crop`. | +| `Unsupported image format` error | TIFF uses an exotic compression (e.g., JPEG‑2000). | Convert the TIFF to a supported format with ImageMagick before OCR. | + +## Extending the Demo + +이제 견고한 **aspose ocr c# example**을 갖췄으니, 다음과 같은 확장을 고려해 보세요: + +- **Batch processing:** 폴더에 있는 TIF들을 순회하면서 각 결과를 `.txt` 파일에 기록합니다. +- **Language packs:** `ocrEngine.Settings.Language = "es"`와 같이 스페인어를 지정하거나, 커스텀 사전을 로드합니다. +- **Bounding boxes:** `ocrResult.Regions`를 사용해 각 단어의 좌표를 얻을 수 있어, 자동 검열 도구에 유용합니다. +- **CPU fallback:** GPU 블록을 try/catch로 감싸고, 실패 시 `ocrEngine.Settings.Gpu.Enable = false`로 전환 후 재시도합니다. + +이러한 확장은 핵심 패턴을 유지하면서 특정 요구에 맞는 가치를 추가합니다. + +## What Should You Learn Next? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하여, 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용할 수 있도록 도와줍니다. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/korean/net/skew-angle-calculation/_index.md b/ocr/korean/net/skew-angle-calculation/_index.md index 28e7eaca7..918c777e9 100644 --- a/ocr/korean/net/skew-angle-calculation/_index.md +++ b/ocr/korean/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ C# 애플리케이션에서 정확한 텍스트 인식을 위한 강력한 OCR 이미지 인식을 위한 강력한 솔루션인 .NET용 Aspose.OCR의 강력한 기능을 활용해 보세요. 경사각을 쉽게 계산하는 방법을 알아보세요. ### [OCR 이미지 인식의 URI에서 기울기 각도 계산](./calculate-skew-angle-from-uri/) .NET용 Aspose.OCR을 탐색하여 OCR 이미지 인식의 기울어짐 각도를 쉽게 계산하세요. 정확성과 효율성으로 프로젝트를 향상시키세요. +### [OCR 회전 문서 튜토리얼 – C#에서 자동 기울기 및 회전 수정](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +C#에서 회전된 문서의 자동 기울기 보정 및 회전 수정을 수행하는 방법을 알아보세요. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/korean/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..5554929f9 --- /dev/null +++ b/ocr/korean/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR을 사용하여 C#에서 기울기를 자동 보정하고 회전을 감지하는 방법을 보여주는 OCR 회전 문서 튜토리얼입니다. + 전체 코드를 포함한 단계별 학습을 제공합니다. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: ko +og_description: OCR 회전 문서 튜토리얼에서는 Aspose OCR을 사용해 C#에서 기울기를 자동으로 보정하고 회전을 감지하는 방법을 + 알려드립니다. 전체 가이드를 확인하세요. +og_title: OCR 회전 문서 튜토리얼 – C#에서 자동 기울기 및 회전 보정 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR 회전된 문서 튜토리얼 – C# 자동 기울기 보정 및 회전 수정 +url: /ko/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 회전된 문서 튜토리얼 – C# 개발자를 위한 전체 가이드 + +스캔한 양식이 옆으로 기울어지거나 비스듬히 들어올 때 **ocr rotated document tutorial**을 보신 적 있나요? 혼자가 아닙니다. 그런 왜곡된 이미지는 깔끔한 텍스트 추출을 방해할 수 있지만, 좋은 소식은 Aspose OCR이 자동으로 이미지를 바로잡아 준다는 것입니다. + +이 단계별 가이드에서는 `OcrEngine`을 생성하고 **automatic skew correction**과 **auto detect rotation**을 활성화한 뒤, 회전된 이미지에 엔진을 적용하고 정제된 텍스트를 출력합니다. 끝까지 진행하면 각 설정이 왜 중요한지, 엣지 케이스에 어떻게 조정하는지 정확히 알게 되며 바로 실행 가능한 C# 프로그램을 얻게 됩니다. + +## 배울 내용 + +* .NET 프로젝트에서 **Aspose OCR**을 설치하고 참조하는 방법. +* `AutoCorrectSkew`와 `AutoDetectRotation`을 활성화하는 것이 신뢰할 수 있는 **ocr rotated document tutorial**의 핵심인 이유. +* JPG, PNG, TIFF 등 모든 이미지 형식을 로드하고 엔진이 무거운 작업을 수행하도록 하는 방법. +* 다중 페이지 PDF, 저해상도 스캔, 사용자 정의 언어 팩을 처리하기 위한 팁. + +> **Prerequisites:** Visual Studio 2022(또는 any C# IDE), .NET 6+ 런타임, 그리고 유효한 Aspose OCR 라이선스(또는 무료 체험). 사전 OCR 경험은 필요하지 않습니다. + +--- + +## 1단계 – Aspose OCR 설치 및 프로젝트 설정 + +먼저 NuGet 패키지를 가져옵니다: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** 체험판 라이선스를 사용하는 경우 `Aspose.OCR.lic` 파일을 실행 파일과 같은 폴더에 두거나, `License license = new License(); license.SetLicense("Aspose.OCR.lic");`와 같이 프로그래밍 방식으로 등록합니다. + +새 콘솔 앱을 생성합니다: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +이제 우리의 **ocr rotated document tutorial**을 위한 깨끗한 시작점이 준비되었습니다. + +## 2단계 – OCR 엔진 초기화 + +엔진은 전체 프로세스의 핵심입니다. 텍스트 추출을 위한 스위스 군용 나이프와 같으며, 어떤 기능을 켤지 알려주기만 하면 됩니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**왜 이러한 설정을 사용하는가?** +* `AutoCorrectSkew`는 문자 베이스라인을 분석하고 라인을 수평으로 만들 정도로 이미지를 회전합니다. +* `AutoDetectRotation`은 전체 방향(0°, 90°, 180°, 270°)을 확인하고 페이지가 뒤집혀 있으면 바로 잡습니다. 이 두 옵션이 없으면 엔진이 “pɹᴉʍ”처럼 뒤집힌 텍스트를 읽게 됩니다. + +## 3단계 – 처리할 이미지 로드 + +Aspose OCR은 일반적인 래스터 형식이면 모두 지원합니다. 자리표시자 경로를 실제 회전된 양식 파일 위치로 교체하세요. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** 다중 페이지 TIFF를 받았다면 `OcrImage.FromMultiPageTiff(filePath)`를 사용하고 `image.Pages`를 순회하세요. + +## 4단계 – 인식 실행 + +이제 엔진이 마법을 부립니다. 먼저 이미지가 (우리의 skew/rotation 플래그 덕분에) 바로 잡히고, 그 다음 문자들을 추출합니다. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +영어 외의 언어가 필요하면 `Recognize`를 호출하기 전에 다음과 같이 설정합니다: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## 5단계 – 인식된 텍스트 출력 + +마지막으로 정제된 텍스트를 콘솔에 출력하거나 파일, 데이터베이스 등 워크플로에 맞는 곳으로 파이프합니다. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Expected output** (샘플 이미지에 “Invoice #1234”가 포함되어 있다고 가정): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +원본 이미지가 90° 회전되고 약간 기울어 있었음에도 텍스트가 올바르게 표시되는 것을 확인하세요. + +--- + +## 일반적인 문제 처리 + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Blank output** | Skew correction disabled or image too dark. | Enable `AutoCorrectSkew` (already on) and increase image contrast via `image.AdjustContrast(1.2)`. | +| **Garbage characters** | Wrong language setting. | Set `ocrEngine.Settings.Language` to match the document language. | +| **Performance lag on large PDFs** | Engine processes each page sequentially. | Use `Parallel.ForEach` on `image.Pages` to leverage multi‑core CPUs. | +| **License exception** | Trial expired. | Acquire a permanent license or stay within the trial limits (5 pages per run). | + +## 견고한 OCR 회전된 문서 튜토리얼을 위한 전문가 팁 + +* **Batch processing:** 전체 흐름을 폴더 경로를 매개변수로 받아 모든 이미지를 순회하고 각 결과를 `.txt` 파일에 기록하는 메서드로 감싸세요. +* **Pre‑processing:** 잡음이 많은 스캔은 인식 전에 `image.Denoise()`를 적용하면 도움이 됩니다. +* **Post‑processing:** 정규식을 사용해 흔히 발생하는 OCR 오인식을 정리하세요. 예를 들어 문자 사이에만 있는 “0”을 “O”로 교체합니다. +* **Logging:** Aspose OCR은 `ocrEngine.Logger`를 제공하므로 파일 로거에 연결해 낮은 신뢰도 점수에 대한 경고를 캡처하세요. + +## 완전한 실행 가능한 코드 + +다음 코드를 콘솔 프로젝트의 `Program.cs` 파일에 저장하세요. 모든 단계, 주석 및 배치 처리를 위한 작은 헬퍼가 포함되어 있습니다. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +실행: + +```bash +dotnet run +``` + +콘솔에 정제된 텍스트가 출력되는 것을 확인할 수 있으며, 이를 통해 우리의 **ocr rotated document tutorial**이 엔드‑투‑엔드로 정상 작동함을 증명합니다. + +## 결론 + +이제 **ocr rotated document tutorial**을 완성했으며, Aspose OCR을 사용해 자동으로 스키를 교정하고 회전을 감지해 깔끔한 텍스트를 추출할 수 있습니다. 핵심 포인트는 `AutoCorrectSkew` **및** `AutoDetectRotation`을 활성화하면 기울어진 스캔을 몇 줄의 코드만으로 완벽하게 읽을 수 있다는 점입니다. + +이후에는 배치 작업으로 확장하거나 언어 팩을 통합하고, 결과를 다운스트림 분석 파이프라인에 전달할 수 있습니다. **automatic skew correction**을 더 깊이 탐구하고 싶다면 Aspose의 이미지 전처리 API를 살펴보거나 노이즈가 많은 스캔에 대한 사용자 정의 임계값을 실험해 보세요. + +PDF, 다중 페이지 TIFF 처리 또는 Azure Functions와의 통합에 대한 질문이 있으면 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +## 다음에 배울 내용은? + +다음 튜토리얼은 이 가이드에서 다룬 기술을 기반으로 하여 관련 주제를 자세히 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공하므로 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/korean/net/text-recognition/_index.md index 1a906a77b..e6b4b0f8d 100644 --- a/ocr/korean/net/text-recognition/_index.md +++ b/ocr/korean/net/text-recognition/_index.md @@ -37,6 +37,9 @@ JSON 형식의 OCR 결과를 쉽게 얻는 방법을 배워 .NET용 Aspose.OCR Aspose.OCR을 사용하여 .NET에서 OCR의 잠재력을 활용해 보세요. PDF에서 텍스트를 손쉽게 추출하고 애플리케이션에 원활하게 통합하세요. 이 튜토리얼은 PDF의 텍스트 인식에 대한 포괄적인 가이드를 제공하여 원활하고 효율적인 통합 경험을 보장합니다. +### [Aspose OCR로 PDF에서 OCR 수행 – 완전 C# 가이드](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Aspose.OCR와 C#을 활용해 PDF에서 텍스트를 정확히 추출하고 통합하는 단계별 완전 가이드입니다. + ## OCR 이미지 인식에서 테이블 인식 .NET용 Aspose.OCR을 사용하여 OCR 이미지 인식에서 테이블 인식의 복잡성을 탐색하세요. 우리의 포괄적인 가이드는 Aspose.OCR의 잠재력을 최대한 활용하여 애플리케이션에서 정확하고 효율적인 테이블 인식을 보장할 수 있도록 지원합니다. 업계 최고의 OCR 솔루션으로 프로젝트의 수준을 높이세요. @@ -55,9 +58,18 @@ Aspose.OCR을 사용하여 .NET에서 OCR의 잠재력을 활용해 보세요. P Aspose.OCR을 사용하여 .NET에서 OCR의 잠재력을 활용해 보세요. PDF에서 텍스트를 쉽게 추출할 수 있습니다. 원활한 통합 경험을 위해 지금 다운로드하세요. ### [OCR 이미지 인식에서 테이블 인식](./recognize-table/) OCR 이미지 인식의 테이블 인식에 대한 포괄적인 가이드를 통해 .NET용 Aspose.OCR의 잠재력을 활용해 보세요. +### [Aspose OCR로 이미지 OCR 수행 – 힌디어 가이드](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Aspose OCR을 사용하여 이미지에서 힌디어 텍스트를 인식하는 방법을 단계별로 안내합니다. +### [Aspose 사용 방법: OCR을 사용하여 이미지를 HTML로 변환](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Aspose.OCR을 활용해 이미지를 HTML 형식으로 변환하는 단계별 가이드를 제공합니다. +### [C#에서 이미지 OCR 수행 및 맞춤법 오류 감지](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +C#와 Aspose.OCR을 사용해 이미지에서 텍스트를 추출하고, 맞춤법 오류를 감지하는 단계별 가이드입니다. +### [C#에서 비디오 자막 OCR – 완전 가이드](./video-subtitle-ocr-in-c-complete-guide/) +C#와 Aspose.OCR을 활용해 비디오 파일에서 자막을 추출하고 OCR 처리하는 단계별 완전 가이드입니다. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/korean/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..f1c66da7a --- /dev/null +++ b/ocr/korean/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Aspose를 사용하여 이미지를 HTML로 변환하고 C#에서 이미지에서 텍스트를 추출하는 방법. 이미지를 HTML로 생성하고 + OCR을 통해 이미지를 빠르게 HTML로 변환하는 방법을 배워보세요. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: ko +og_description: Aspose를 사용하여 이미지를 HTML로 변환하고, 이미지에서 텍스트를 추출하며, OCR을 통해 C#에서 이미지로부터 + HTML을 생성하는 방법. 이 완전한 가이드를 따라보세요. +og_title: 'Aspose 사용 방법: OCR을 사용하여 이미지를 HTML로 변환' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Aspose 사용법: OCR을 이용해 이미지를 HTML로 변환' +url: /ko/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose 사용 방법: OCR을 이용해 이미지를 HTML로 변환하기 + +스캔한 사진을 깔끔한 HTML로 변환하는 **Aspose 사용 방법**이 궁금하셨나요? 잡지 페이지, 영수증, 손글씨 메모 등 텍스트와 레이아웃을 웹 게시용으로 보존해야 할 경우가 있을 겁니다. 좋은 소식은 직접 파서를 작성하거나 저수준 이미지 처리를 할 필요가 없다는 것입니다—Aspose.OCR이 모든 작업을 대신 수행합니다. + +이 튜토리얼에서는 **완전하고 실행 가능한 예제**를 통해 C#에서 Aspose OCR 라이브러리를 사용해 **이미지를 HTML로 변환**, **이미지에서 텍스트 추출**, 그리고 **이미지에서 HTML 생성**하는 방법을 단계별로 살펴보겠습니다. 최종적으로 원본 페이지 레이아웃이 그대로 유지된 HTML 파일을 생성하는 작은 콘솔 앱을 만들 수 있게 됩니다. 이 파일은 어떤 웹사이트에도 바로 삽입할 수 있습니다. + +## 사전 요구 사항 + +시작하기 전에, 다음이 시스템에 설치되어 있는지 확인하세요: + +- **.NET 6.0 SDK** 이상 (코드는 .NET Core와 .NET Framework 모두에서 동작합니다). +- **Visual Studio 2022** (또는 원하는 편집기). +- **Aspose.OCR for .NET** – NuGet을 통해 설치: `dotnet add package Aspose.OCR`. +- 변환하려는 이미지 파일(JPEG/PNG), 예: `magazine_page.jpg`. + +추가 설정 파일은 필요하지 않습니다; 라이브러리는 OCR 및 HTML 레이아웃 생성을 위해 필요한 모든 것을 포함하고 있습니다. + +## Step 1: 프로젝트 설정 및 Aspose.OCR 추가 + +먼저, 새로운 콘솔 프로젝트를 만들고 Aspose OCR 패키지를 추가합니다. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Visual Studio를 사용한다면 프로젝트를 마우스 오른쪽 버튼으로 클릭 → *Manage NuGet Packages* → **Aspose.OCR**을 검색하고 설치하면 됩니다. 이 단계로 **ocr image to html**에 필요한 모든 참조가 확보됩니다. + +## Step 2: OCR 엔진 초기화 + +프로세스의 핵심은 `OcrEngine` 클래스입니다. 사진을 읽고 결과를 어떻게 출력할지 결정하는 두뇌라고 생각하면 됩니다. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +여기서 `OcrEngine`을 인스턴스화합니다. 무료 버전에서는 자격 증명을 전달할 필요가 없으며, 라이브러리가 내장된 인식 모델을 사용합니다. + +## Step 3: 원본 이미지 로드 + +다음으로, 엔진이 처리할 파일을 지정합니다. Aspose는 대부분의 이미지 형식을 지원하는 편리한 `OcrImage.FromFile` 메서드를 제공합니다. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +`YOUR_DIRECTORY`를 이미지가 위치한 절대 경로나 상대 경로로 교체하세요. 이미지가 실행 파일과 같은 폴더에 있다면 `"magazine_page.jpg"`만 사용하면 됩니다. + +## Step 4: 레이아웃을 포함한 HTML 요청 및 인식 + +이 단계가 튜토리얼의 핵심입니다. `OutputFormat.HtmlWithLayout`을 전달함으로써 Aspose에게 텍스트 블록, 이미지, 표의 원래 위치를 유지하면서 **이미지에서 HTML 생성**을 지시합니다. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text` 속성에는 이제 전체 HTML 문서가 들어 있습니다. 순수 텍스트만 필요하다면 `OutputFormat.Text`를 사용할 수 있지만, 여기서는 레이아웃 정확성을 유지한 **convert image to html**에 초점을 맞춥니다. + +## Step 5: HTML 파일 저장 + +마지막으로 HTML 문자열을 디스크에 저장합니다. 이렇게 하면 어떤 브라우저에서도 열 수 있는 즉시 사용 가능한 파일이 생성됩니다. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +프로그램을 실행하면 `magazine.html`이 생성됩니다. 이를 열면 원본 이미지에 나타난 대로 텍스트가 정확히 배치된 것을 확인할 수 있습니다—아카이빙이나 웹 게시에 최적입니다. + +## 전체 작업 예제 + +아래는 **완전하고 복사‑붙여넣기 바로 사용 가능한** 프로그램입니다. 누락된 부분이 없으므로 올바른 경로만 설정하면 바로 컴파일하고 실행할 수 있습니다. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### 예상 출력 + +`magazine.html`을 브라우저에서 열면 (예시를 단순화한) 다음과 같은 화면이 표시됩니다: + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +정확한 `style` 속성은 원본 이미지에 따라 달라지지만, 구조적으로 **extract text from image**와 **generate html from image**가 하나의 원활한 단계에서 수행된다는 점은 보장됩니다. + +## 일반적인 질문 및 예외 상황 + +### 이미지 해상도가 낮으면 어떻게 하나요? + +Aspose.OCR은 최소 **300 DPI** 이상의 이미지에서 가장 좋은 성능을 발휘합니다. 파일이 흐릿하면 OCR 엔진에 전달하기 전에 이미지 향상 라이브러리(예: ImageSharp)로 전처리해 보세요. 저품질은 **extract text from image** 정확도와 생성된 HTML 레이아웃의 충실도 모두에 영향을 줄 수 있습니다. + +### OCR 언어를 제어할 수 있나요? + +예. `Recognize`를 호출하기 전에 `OcrEngine`의 `Language` 속성을 설정하면 됩니다: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +비영어 문자를 처리할 때 인식률이 향상됩니다. + +### HTML 대신 순수 텍스트를 얻으려면? + +원시 문자열만 필요하면 `OutputFormat.HtmlWithLayout`을 `OutputFormat.Text`로 교체하면 됩니다. 동일한 `recognitionResult.Text`에 추출된 문자만 포함됩니다. + +### 생성된 HTML에 이미지를 삽입할 수 있나요? + +`OutputFormat.HtmlWithLayoutAndImages`를 사용하면 Aspose.OCR이 원본 이미지를 base‑64 데이터 URI로 삽입할 수 있습니다. 외부 자산 없이 하나의 HTML 파일만 필요할 때 유용합니다. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### 대량 배치를 처리하려면 어떻게 하나요? + +배치 처리를 위해서는 파일 경로 목록에 대해 `foreach` 루프로 로직을 감싸면 됩니다. 동일한 `OcrEngine` 인스턴스를 재사용하면 오버헤드가 감소하고 **convert image to html** 파이프라인이 빨라집니다. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## 프로덕션 수준 코드 팁 + +- **리소스 해제**: `OcrEngine`과 `OcrImage` 모두 `IDisposable`을 구현합니다. `using` 구문으로 감싸서 네이티브 메모리를 즉시 해제하세요. +- **오류 처리**: 파일 관련 문제는 `IOException`을, 인식 문제는 `OcrException`을 잡아 처리합니다. +- **성능**: 많은 이미지를 처리한다면 **병렬 처리**(`Parallel.ForEach`)를 활성화하는 것을 고려하되, CPU 사용량에 유의하세요—OCR은 CPU 집약적 작업입니다. +- **로깅**: 로거(예: Serilog)를 통합해 OCR 신뢰도 점수(`recognitionResult.Confidence`)를 기록하면 품질 모니터링에 도움이 됩니다. + +## 결론 + +우리는 이제 **Aspose 사용 방법**을 통해 **이미지를 HTML로 변환**, **이미지에서 텍스트 추출**, 그리고 **이미지에서 HTML 생성**을 몇 단계만에 수행하는 방법을 살펴보았습니다. 전체 코드 샘플은 레이아웃을 유지하면서 **ocr image to html**을 수행하는 방법을 보여주며, 모든 문서 디지털화 프로젝트의 견고한 기반이 됩니다. + +다음과 같은 작업을 시도해 볼 수 있습니다: + +- 필요에 맞게 다양한 `OutputFormat` 옵션을 실험해 보세요. +- HTML 출력물을 CSS 프레임워크와 결합해 반응형 스타일을 적용하세요. +- 추출된 텍스트를 검색 인덱스나 머신러닝 파이프라인에 전달하세요. + +한 번 시도해 보고 설정을 조정해 보면 Aspose가 사진을 웹 준비 콘텐츠로 얼마나 손쉽게 변환하는지 확인할 수 있습니다. 문제가 발생하면 댓글을 남겨 주세요—행복한 코딩 되세요! + +![이미지에서 HTML 레이아웃으로 변환되는 OCR 파이프라인 다이어그램 – Aspose 사용 방법](/images/ocr-pipeline.png "Aspose 사용 방법") + +--- + +## 다음에 배워야 할 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 리소스는 단계별 설명과 함께 완전한 작동 코드 예제를 제공하여 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색할 수 있도록 돕습니다. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/korean/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..d4bd0a66d --- /dev/null +++ b/ocr/korean/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,239 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR를 사용하여 이미지에서 OCR을 수행하고 텍스트를 추출합니다. 하나의 C# 데모에서 철자 오류를 감지하고 + 맞춤법 제안을 얻는 방법을 배워보세요. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: ko +og_description: 이미지에서 텍스트를 추출하기 위해 OCR을 수행하고, 맞춤법이 틀린 단어를 감지한 뒤 Aspose.OCR을 사용해 C#에서 + 맞춤법 제안을 얻습니다. +og_title: 이미지에서 OCR을 수행하고 C#로 맞춤법이 틀린 단어 감지 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: 이미지에서 OCR을 수행하고 C#에서 맞춤법 오류 단어를 감지하기 +url: /ko/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 OCR 수행 및 C#에서 맞춤법 오류 감지 + +이미지 파일에서 **perform OCR on image** 하는 것이 머리카락을 뽑을 정도로 어려운 일이라고 생각해 본 적 있나요? 당신만 그런 것이 아닙니다. 오래된 편지를 디지털화하거나 영수증을 스캔하거나 스마트 문서 워크플로를 구축하든, 사진에서 깨끗한 텍스트를 추출하는 것이 첫 번째 장벽입니다. 좋은 소식은? Aspose.OCR을 사용하면 몇 분 안에 솔루션을 만들 수 있으며, 추가로 **detect misspelled words**와 **get spelling suggestions**도 같은 실행에서 할 수 있습니다. + +이 튜토리얼에서는 **extracts text from image**를 수행하고 영어 맞춤법 검사기를 실행하며 각 오류를 편리한 교정 아이디어와 함께 출력하는 완전한 실행 가능한 C# 콘솔 앱을 단계별로 살펴보겠습니다. 마지막까지 하면 **how to extract text**(텍스트 추출 방법), 맞춤법 검사 API 연결 방법, 그리고 예상되는 콘솔 출력 형태를 정확히 알게 됩니다. + +## 만들게 될 것 + +- 오타가 포함된 비트맵(또는 PNG)을 로드합니다. +- Aspose.OCR을 실행하여 **perform OCR on image** 하고 원시 문자열 데이터를 얻습니다. +- 내장된 영어 맞춤법 검사기를 초기화합니다. +- **detect misspelled words**와 **get spelling suggestions**를 각각 수행합니다. +- 콘솔에 깔끔한 보고서를 출력합니다. + +외부 서비스나 복잡한 HTTP 호출이 필요 없습니다—단일 NuGet 패키지와 몇 줄의 코드만 있으면 됩니다. + +## 사전 요구 사항 + +- .NET 6.0 SDK 또는 그 이후 버전(코드는 .NET Framework 4.7+에서도 작동합니다). +- Visual Studio 2022(또는 원하는 편집기). +- Aspose.OCR for .NET NuGet 패키지 (`Aspose.OCR`). +- 프로젝트에서 참조할 수 있는 위치에 이미지 파일(`letter_with_typos.png`)을 배치합니다. + +Aspose를 한 번도 사용해 본 적이 없더라도 걱정하지 마세요—패키지 설치는 다음과 같이 간단합니다: + +```bash +dotnet add package Aspose.OCR +``` + +## 단계 1: 프로젝트 설정 및 Aspose.OCR 설치 + +새 콘솔 프로젝트를 만들고 OCR 라이브러리를 가져옵니다: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +복원이 완료되면 `Program.cs`를 엽니다. 나중에 기본 내용을 전체 데모 코드로 교체할 예정이지만, 먼저 각 네임스페이스가 왜 필요한지 살펴보겠습니다. + +- `Aspose.OCR` – 핵심 OCR 엔진 및 이미지 처리. +- `Aspose.OCR.SpellCheck` – 라이브러리와 함께 제공되는 맞춤법 검사 유틸리티. +- `System` – 표준 .NET 기본 클래스(예: `Console`). + +## 단계 2: 이미지 로드 및 Perform OCR on Image 수행 + +첫 번째 실제 작업은 이미지를 OCR 엔진에 전달하는 것입니다. Aspose.OCR은 다양한 형식(PNG, JPEG, TIFF)을 읽습니다. 다음은 핵심 작업을 수행하는 코드 스니펫입니다: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **왜 중요한가:** `OcrImage.FromFile`은 픽셀 수준의 세부 정보를 추상화하고, `OcrEngine.Recognize`는 시각 글리프를 유니코드 문자로 변환하는 학습된 신경 모델을 실행합니다. 이제 `ocrResult.Text` 속성에 원시 문자열이 들어 있으며, 바로 **extract text from image**에 필요한 내용입니다. + +> **팁:** 이미지에 여러 언어가 포함된 경우 `Recognize`를 호출하기 전에 `ocrEngine.Language = OcrLanguage.Multilingual;` 로 설정할 수 있습니다. + +## 단계 3: 영어 맞춤법 검사기 초기화 + +Aspose.OCR은 기본 제공되는 맞춤법 검사 엔진을 포함하고 있으며, 바로 영어를 인식합니다. 초기화는 한 줄로 가능합니다: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **왜 이 단계가 중요한가:** OCR 출력에는 잘못 인식된 문자(예: “l” vs “1”)나 원본 문서의 실제 오타가 포함될 수 있습니다. 맞춤법 검사기는 문자열을 스캔하여 의심스러운 토큰을 찾아 대안을 제시합니다. + +## 단계 4: 맞춤법 오류 감지 및 맞춤법 제안 받기 + +이제 OCR 텍스트를 검사기에 전달합니다: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings`은 각 항목에 오류가 있는 단어와 가능한 교정 후보 배열을 포함하는 컬렉션입니다. + +## 단계 5: 결과 출력 + +마지막으로 컬렉션을 순회하면서 사람이 읽기 쉬운 보고서를 출력합니다: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### 예상 콘솔 출력 + +만약 `letter_with_typos.png`에 다음 문장이 포함되어 있다고 가정하면: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +데모를 실행하면 다음과 같은 출력이 생성됩니다: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +각 오타마다 몇 가지 가능한 교정이 짝을 이루는 것을 확인할 수 있습니다—사용자 친화적인 교정 UI를 구축할 때 정확히 필요한 기능입니다. + +## 전체 작업 예제 + +아래는 **완전한 복사‑붙여넣기 가능한** 프로그램입니다. `YOUR_DIRECTORY`를 이미지 파일의 실제 경로로 교체하십시오. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **고려해야 할 엣지 케이스** +> - **Empty Image:** OCR 엔진이 빈 문자열을 반환하면 `spellChecker.Check`는 단순히 빈 컬렉션을 반환합니다—크래시가 발생하지 않습니다. +> - **Non‑English Text:** `OcrLanguage.English`를 `OcrLanguage.French`(또는 지원되는 다른 언어)로 교체하여 다른 로케일에서 **detect misspelled words**를 수행할 수 있습니다. +> - **Large Documents:** 다중 페이지 PDF의 경우 각 페이지를 순회하면서 OCR을 수행하고, 결과를 집계한 뒤 맞춤법 검사를 진행합니다. + +## 시각적 개요 (이미지 Alt 텍스트) + +![이미지에서 OCR 수행, 이미지에서 텍스트 추출, 그리고 맞춤법 오류 감지 및 맞춤법 제안 흐름을 보여주는 다이어그램](perform-ocr-on-image-flow.png) + +*위 다이어그램은 이미지 → OCR 엔진 → 원시 텍스트 → 맞춤법 검사기 → 제안이라는 엔드‑투‑엔드 파이프라인을 보여줍니다.* + +## 일반적인 질문 및 팁 + +| Question | Answer | +|----------|--------| +| **인터넷 연결이 필요합니까?** | 아니요. Aspose.OCR은 완전히 로컬에서 실행되므로 오프라인이나 보안이 중요한 환경에 적합합니다. | +| **맞춤법 검사기의 정확도는 어느 정도인가요?** | 약 15만 개의 영어 단어 사전과 퍼지 매칭을 사용하므로 대부분의 일반적인 오타를 잡아냅니다. | +| **사전을 사용자 정의할 수 있나요?** | 예. `SpellChecker.AddUserDictionary("custom.txt")`를 사용하면 도메인별 용어(예: 제품명)를 로드할 수 있습니다. | +| **이미지가 기울어져 있으면 어떻게 하나요?** | OCR 엔진이 자동으로 방향을 감지하지만, 어려운 경우 `ocrEngine.ImagePreprocessing.Rotate(angle)`를 수동으로 호출할 수 있습니다. | +| **UI에서 제안을 강조 표시할 방법이 있나요?** | `misspellings` 컬렉션을 확보한 후, 각 `entry.Word`를 `ocrResult.Text` 내 위치와 매핑하여 RichTextBox나 웹 뷰에서 밑줄을 그릴 수 있습니다. | + +## 결론 + +우리는 방금 **how to perform OCR on image**, **extract text from image**, 그리고 **detect misspelled words**와 **getting spelling suggestions**를 수행하는 방법을 보여주었습니다—모두 간결한 C# 콘솔 앱으로 구현했습니다. 핵심 아이디어는 간단합니다: Aspose.OCR이 문자 인식이라는 무거운 작업을 수행하도록 하고, 내장된 맞춤법 검사기가 출력 결과를 정리합니다. 이제 이 데모를 전체 문서 처리 서비스로 확장하거나, 웹 API와 통합하거나, 데스크톱 편집기에 연결할 수 있습니다. + +다음 단계가 준비되셨나요? 언어를 스페인어로 바꾸어 보거나, 다중 페이지 PDF를 처리하거나, 사용자가 단어를 클릭해 제안을 수락할 수 있는 작은 WPF 프런트엔드를 구축해 보세요. 기본 블록은 이미 준비되어 있으니, 계속 실험해 보세요. + +문제가 발생하거나 확장 아이디어가 있으면 아래에 댓글을 남겨 주세요. 즐거운 코딩 되세요! + +## 다음에 배울 내용은? + +다음 튜토리얼은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 완전한 코드 예제와 단계별 설명이 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [Aspose.OCR을 사용한 언어 선택이 가능한 이미지 텍스트 추출 C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR .NET을 사용한 이미지에서 텍스트 추출](/ocr/english/net/image-and-drawing-recognition/) +- [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/korean/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/korean/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..5fef017ea --- /dev/null +++ b/ocr/korean/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,269 @@ +--- +category: general +date: 2026-06-03 +description: C#에서 Aspose OCR을 사용하여 이미지에 대한 OCR을 수행합니다. OCR을 위해 이미지를 로드하고 오프라인으로 힌디어 + 텍스트를 추출하는 방법을 단계별 코드와 함께 배워보세요. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: ko +og_description: C#에서 Aspose OCR을 사용해 이미지에 OCR을 수행합니다. 이 튜토리얼은 OCR을 위해 이미지를 로드하고 오프라인으로 + 힌디어 텍스트를 추출하는 방법을 보여주며, 실행 가능한 코드까지 포함합니다. +og_title: 이미지에서 OCR 수행 – Aspose OCR 힌디어 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Aspose OCR로 이미지에서 OCR 수행 – 힌디어 가이드 +url: /ko/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR으로 이미지에서 OCR 수행 – 힌디어 가이드 + +이미지 파일에서 **perform OCR on image**를 해야 하는데 힌디어 문자를 추출하는 방법을 몰라 고민한 적 있나요? 당신만 그런 것이 아닙니다—많은 개발자들이 비라틴 스크립트를 처음 읽을 때 이 장벽에 부딪힙니다. 좋은 소식은 Aspose OCR을 사용하면 매우 간단하게 처리할 수 있으며, 완전히 오프라인에서도 수행할 수 있다는 점입니다. + +이 가이드에서는 **load image for OCR**를 수행하고, 엔진에 오프라인 언어 팩을 지정한 뒤, 최종적으로 **extract Hindi text image** 데이터를 인터넷에 접속하지 않고 추출하는 방법을 다룹니다. 끝까지 따라오면 힌디어 영수증을 읽어 콘솔에 텍스트를 출력하는 실행 가능한 C# 콘솔 앱을 얻을 수 있습니다. + +## 필요 사항 + +- **.NET 6.0** 이상 (코드는 .NET Framework 4.7+에서도 동작합니다) +- **Aspose.OCR for .NET** NuGet 패키지 + `dotnet add package Aspose.OCR` +- **offline Hindi language resources**가 들어있는 폴더 (Aspose 포털에서 다운로드) +- 힌디어 텍스트가 포함된 이미지 파일, 예: `receipt_hindi.png` + +그것뿐입니다—외부 서비스도 없고, API 키도 없으며, 단순한 코드만 있죠. + +## 이미지에서 OCR 수행 – 단계별 구현 + +아래에서는 과정을 일곱 단계로 나누어 설명합니다. 각 단계는 **왜** 중요한지, 단순히 **무엇을** 입력해야 하는지가 아니라 그 이유를 설명합니다. + +### 단계 1: OCR 엔진 인스턴스 생성 + +엔진은 Aspose OCR의 핵심입니다. 인스턴스를 생성하면 이후에 조정할 모든 설정에 접근할 수 있습니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **왜?** +> `OcrEngine`이 없으면 `Recognize`를 호출할 객체가 없습니다. 이를 나중에 사진을 스캔할 “카메라”라고 생각하면 됩니다. + +### 단계 2: 엔진을 오프라인 리소스로 지정 + +Aspose는 로컬에 저장할 수 있는 언어 팩을 제공합니다. `ResourcesFolder`를 설정하면 엔진이 해당 위치를 찾게 됩니다. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **팁:** +> 개발 중에는 절대 경로를 사용하고, 프로덕션에서는 상대 경로나 설정값으로 전환하세요. + +### 단계 3: 오프라인 모드 강제 + +‘온라인 조회를 비활성화해야 할까?’ 라고 생각할 수 있습니다. 방화벽 뒤에서 작업하거나 결정적인 결과를 원한다면 `UseOfflineResources`를 `true`로 설정하세요. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **전문가 팁:** +> 이 플래그를 `false`로 두면 엔진이 추가 데이터를 다운로드하게 되어 지연이 발생하고 보안 정책을 위반할 수 있습니다. + +### 단계 4: 인식 언어를 힌디어로 선택 + +여기서는 엔진에 예상 언어를 알려 **extract Hindi text image**를 수행합니다. 이는 정확도를 크게 향상시킵니다. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **왜 도움이 되나요:** +> OCR 엔진은 언어별 문자 모델을 사용합니다. 힌디어로 고정하면 엔진이 수십 개의 스크립트 중에서 추측하는 일을 방지할 수 있습니다. + +### 단계 5: OCR을 위한 이미지 로드 + +이제 실제로 **load image for OCR**를 수행합니다. `OcrImage.FromFile` 메서드는 비트맵을 엔진이 이해할 수 있는 형식으로 읽어들입니다. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **흔한 실수:** +> Windows에서 슬래시(`/`)를 사용해도 동작하지만, `Path.Combine`을 사용하면 코드가 플랫폼에 구애받지 않게 됩니다. + +### 단계 6: 인식 실행 + +모든 설정이 완료되면 `Recognize`를 호출하여 최종적으로 **perform OCR on image**를 수행합니다. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **무슨 일이 일어나나요?** +> 엔진은 각 픽셀을 스캔하고, 힌디어 글리프 데이터베이스와 패턴을 매칭하여 유니코드 문자 문자열을 생성합니다. + +### 단계 7: 인식된 텍스트 출력 + +결과 객체에는 추출된 문자열을 담고 있는 `Text` 속성이 있습니다. 이를 콘솔에 출력하면 됩니다. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **예상 출력:** +> `receipt_hindi.png`에 “भुगतान सफल”이 포함되어 있으면 콘솔에 해당 라인이 정확히 출력되며, 구분 기호도 보존됩니다. + +## OCR을 위한 이미지 로드 – 리소스 준비 + +엔진에 파일 대신 스트림을 제공할 수 있는지 궁금하다면, 답은 ‘예’입니다. `OcrImage.FromFile`을 다음과 같이 교체하세요: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **왜 스트림을 사용하나요?** +> 스트림을 사용하면 데이터베이스, 클라우드 블롭, 임베디드 리소스 등에 저장된 이미지를 처리할 수 있어 확장 가능한 서비스에 적합합니다. + +## 힌디어 텍스트 이미지 추출 – 엣지 케이스 처리 + +1. **Missing language pack** – 힌디어 팩을 찾을 수 없으면 `Recognize`가 예외를 발생시킵니다. 호출을 try/catch로 감싸고 친절한 메시지를 로그에 남기세요. +2. **Low‑resolution images** – OCR 정확도가 300 dpi 이하에서 떨어집니다. 로드하기 전에 이미지를 전처리(크기 조정, 선명화)하세요. +3. **Mixed‑language documents** – 여러 언어를 활성화할 수 있습니다: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +이러한 조정으로 **perform OCR on image** 루틴이 프로덕션 환경에서도 견고하게 동작합니다. + +## 전체 예제 실행 + +`Program.cs` 파일로 저장하고, 자리표시자 경로를 교체한 뒤 실행하세요: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +`dotnet run`을 실행하면 다음과 같은 출력이 나타납니다: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +빈 문자열이 출력되면 **ResourcesFolder**가 `Hindi.traineddata`가 들어있는 폴더를 가리키는지, 이미지가 충분히 선명한지 다시 확인하세요. + +## 결론 + +우리는 Aspose OCR을 사용해 **perform OCR on image** 파일을 처리하는 방법을 단계별로 살펴보았습니다. **load image for OCR**부터 **extract Hindi text image**까지 완전 오프라인 시나리오를 다루었습니다. 위의 완전하고 실행 가능한 코드는 탄탄한 기반을 제공하며, 스트림 사용, 오류 처리, 다중 언어 지원에 대한 팁은 실제 프로젝트에 솔루션을 적용하는 데 도움이 될 것입니다. + +다음 단계가 준비되셨나요? 언어를 **OcrLanguage.Tamil**로 바꾸거나 Azure Blob 스토리지에서 이미지를 공급해 보세요. 또한 `ImagePreprocessing` 설정을 실험하여 잡음이 많은 영수증의 정확도를 높일 수 있습니다. + +질문이 있거나 문제가 발생했나요? 댓글을 남겨 주세요—행복한 코딩 되세요! + +![Perform OCR on image example + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하는 밀접한 관련 주제를 다룹니다. 각 자료에는 단계별 설명과 함께 완전한 동작 코드 예제가 포함되어 있어 추가 API 기능을 마스터하고 프로젝트에서 대체 구현 방식을 탐색하는 데 도움이 됩니다. + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/korean/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..beb4af5a7 --- /dev/null +++ b/ocr/korean/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR를 사용하여 PDF에 OCR을 수행하고 스캔된 PDF를 검색 가능한 PDF로 변환합니다. PDF에서 텍스트를 + 인식하고 몇 분 안에 검색 가능한 PDF를 만드는 방법을 배워보세요. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: ko +og_description: PDF에 OCR을 수행하고 즉시 검색 가능한 PDF를 만듭니다. 이 튜토리얼에서는 Aspose.OCR을 사용하여 PDF에서 + 텍스트를 인식하는 방법을 단계별로 보여줍니다. +og_title: PDF에서 OCR 수행 – 완전한 C# 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Aspose.OCR를 사용하여 PDF에서 OCR 수행 – 완전한 C# 가이드 +url: /ko/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# PDF에서 Aspose.OCR을 사용한 OCR 수행 – 완전한 C# 가이드 + +정말 **PDF에서 OCR을 수행하는 방법**을 수십 개의 명령줄 도구와 씨름하지 않고도 궁금하지 않으셨나요? 당신만 그런 것이 아닙니다. 청구서를 디지털화하거나 오래된 보고서를 보관하거나 스캔된 계약서의 검색 가능한 버전이 필요할 때, 정적인 PDF를 실제로 검색할 수 있는 형태로 바꾸는 것은 게임 체인저입니다. + +이 가이드에서는 Aspose.OCR for .NET을 사용하여 스캔된 PDF(및 일반 이미지)에서 **검색 가능한 PDF** 파일을 만드는 방법을 단계별로 살펴보겠습니다. 끝까지 읽으면 몇 줄의 C# 코드만으로 **PDF에서 텍스트를 인식**할 수 있게 되고, 각 단계 뒤에 숨은 이유를 이해하여 자신의 프로젝트에 맞게 솔루션을 적용할 수 있게 됩니다. + +> **핵심 요약:** 전체 과정은 세 가지로 요약됩니다—OCR 엔진 초기화, 소스(PDF 또는 이미지) 제공, 검색 가능한 PDF 출력 저장. 이제 시작해봅시다. + +--- + +## 준비물 + +시작하기 전에 다음이 준비되어 있는지 확인하세요: + +| 전제 조건 | 이유 | +|--------------|----------------| +| **.NET 6.0+** (또는 .NET Framework 4.6+) | Aspose.OCR은 최신 런타임을 대상으로 하며, 오래된 버전에서는 API 업데이트가 누락될 수 있습니다. | +| **Aspose.OCR for .NET** NuGet 패키지 | `OcrEngine` 클래스와 PDF 처리 유틸리티를 제공합니다. | +| **유효한 Aspose 라이선스** (또는 무료 평가판) | 라이선스가 없으면 30일 평가 제한 및 워터마크가 적용됩니다. | +| **검색 가능하게 만들고 싶은 스캔된 PDF** (또는 이미지 파일) | OCR을 수행할 원본 문서입니다. | +| **Visual Studio 2022** (또는 기타 C# 편집기) | 디버깅이 쉬워지지만, 어떤 IDE든 상관없습니다. | + +다음 NuGet 명령으로 라이브러리를 설치할 수 있습니다: + +```bash +dotnet add package Aspose.OCR +``` + +> **프로 팁:** CI 파이프라인에서 작업한다면, 라이선스 파일을 빌드 아티팩트에 추가하고 런타임에 로드하여 경로를 하드코딩하는 것을 피하세요. + +--- + +## PDF에서 OCR 수행 – Aspose.OCR 설정 + +먼저 새로운 `OcrEngine` 인스턴스를 만들어야 합니다. 이는 문서를 읽어줄 두뇌와 같습니다. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +왜 매번 새로운 인스턴스를 만들까요? 엔진은 언어 설정과 같은 구성을 보관하고 있으며, 문서마다 다를 수 있습니다. 실행마다 인스턴스를 생성하면 깨끗한 상태를 보장하고 작업 간 교차 영향을 방지합니다. + +--- + +## 검색 가능한 PDF 만들기 – 비밀번호 설정 (선택 사항) + +PDF가 보호되어 있다면, 페이지를 읽기 전에 엔진에 비밀번호를 알려줘야 합니다: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +보호된 파일에 이 단계를 생략하면 `PdfPasswordException`이 발생합니다. 보호 상태가 확실하지 않다면 항상 try‑catch로 감싸세요. + +--- + +## 스캔된 PDF를 검색 가능한 PDF로 변환 – 소스 로드 + +Aspose.OCR은 `OcrImage` 추상화를 사용하며, PDF, TIFF, JPEG 등을 래핑할 수 있습니다. 스캔된 PDF를 메모리로 불러오는 방법은 다음과 같습니다: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +`FromFile`은 각 페이지를 OCR 엔진이 처리할 수 있는 래스터 이미지로 파싱합니다. 다중 페이지 PDF인 경우 엔진이 자동으로 모든 페이지를 순회합니다. + +--- + +## PDF에서 텍스트 인식 – OCR 수행 + +이제 튜토리얼의 핵심 단계: 엔진에 텍스트 인식을 요청하고 검색 가능한 PDF를 출력합니다. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf`는 엔진에게 원본 스캔 이미지 위에 보이지 않는 텍스트 레이어를 삽입하도록 지시합니다. 결과 PDF는 스캔 이미지의 시각적 품질을 유지하면서 완전히 검색 가능해집니다—감사 감사에 딱 맞는 형태입니다. + +--- + +## 이미지에서 검색 가능한 PDF로 변환 – 결과 저장 + +마지막으로 바이너리 데이터를 디스크에 기록합니다: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary` 속성은 원시 PDF 바이트를 보유합니다. API를 구축 중이라면 웹 응답 스트림으로 직접 전달할 수도 있습니다. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*이미지 대체 텍스트: 스캔된 PDF가 검색 가능한 PDF로 변환되는 과정을 보여주는 OCR 변환 흐름도.* + +--- + +## 엣지 케이스 및 실용 팁 + +### 1. 대용량 파일 및 메모리 관리 +100 MB를 초과하는 PDF를 처리한다면 `OcrEngineSettings.MemoryLimit`을 사용해 메모리 사용량을 제한하세요. 또한 페이지를 배치 단위로 처리해 `OutOfMemoryException`을 방지합니다. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. 언어 지원 +기본적으로 Aspose.OCR은 영어를 가정합니다. 다른 언어를 인식하려면 `Language` 속성을 설정하세요: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. 다중 스레드 시나리오 +`OcrEngine`은 **스레드 안전하지** 않습니다. 병렬 처리가 필요하면 스레드당 별도의 엔진을 생성하세요. + +### 4. OCR 정확도 디버깅 +디버깅을 위해 `ocrResult`에서 순수 텍스트를 추출할 수 있습니다: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +출력이 깨져 보이면 `PreprocessSettings`(예: 디스큐, 디스펙클)를 실험해 품질을 개선하세요. + +### 5. 라이선스 함정 +평가 버전을 실행하면 Aspose가 출력 PDF에 워터마크를 추가합니다. 애플리케이션 시작 시 라이선스를 먼저 등록하세요: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## 전체 작업 예제 – 시작부터 끝까지 + +아래는 위에서 설명한 모든 팁을 포함한 완전한 실행 가능한 프로그램입니다. 새 콘솔 프로젝트에 복사‑붙여넣기만 하면 됩니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**예상 출력:** 실행 후 콘솔에 파일 위치를 확인하는 메시지가 표시됩니다. `output.pdf`를 PDF 뷰어에서 열고 원본 스캔에 존재하는 단어를 입력해 보세요. 텍스트가 강조 표시되면 **PDF에서 OCR을 수행**하고 검색 가능한 문서를 성공적으로 만든 것입니다. + +--- + +## 자주 묻는 질문 + +**Q: 단일 이미지(PNG/JPEG)를 검색 가능한 PDF로 변환할 수 있나요?** +A: 물론 가능합니다. `OcrImage.FromFile("input.pdf")`를 이미지 파일 경로로 바꾸면 됩니다. 엔진은 이미지를 래스터화하고 동일하게 OCR 레이어를 삽입합니다. + +**Q: PDF에 스캔된 페이지와 원본 텍스트가 모두 포함되어 있으면 어떻게 되나요?** +A: 엔진은 기존 콘텐츠 위에 OCR 텍스트를 오버레이하므로 원본 텍스트는 선택 가능하고 스캔된 페이지는 검색 가능해집니다. + +**Q: OCR 정확도는 어느 정도인가요?** +A: 정확도는 원본 품질에 좌우됩니다. 깨끗하고 고해상도(>300 dpi) 스캔은 95 % 이상의 정확도를 제공합니다. 잡음이 많은 문서는 `PreprocessSettings`(디스큐, 디스펙클)를 활성화해 정확도를 높일 수 있습니다. + +--- + +## 다음 단계 – OCR 툴킷 확장 + +이제 **PDF에서 텍스트를 인식**하고 **스캔된 PDF를 검색 가능한 PDF로 변환**하는 방법을 알았으니, 다음 주제들을 고려해 보세요: + +- **배치 처리**: 폴더에 있는 여러 PDF를 자동으로 검색 가능한 버전으로 변환하는 루프 작성. +- **텍스트 추출**: `ocrResult.Text`를 사용해 검색 인덱스(예: Elasticsearch)에 전달. +- **맞춤 언어 팩**: Aspose에서 추가 언어 데이터를 다운로드해 아시아 스크립트를 지원. +- **PDF/A 준수**: Aspose.PDF와 OCR 출력을 결합해 보관용 PDF를 생성. + +이러한 주제들은 우리가 다룬 핵심 단계를 기반으로 하므로, 솔루션을 확장하는 데 큰 도움이 될 것입니다. + +--- + +## 마무리 + +우리는 **Aspose.OCR을 사용해 PDF 파일에서 OCR을 수행**하고, 스캔된 PDF를 완전한 검색 가능한 PDF로 변환하는 방법을 보여주었습니다. 또한 일반 이미지를 검색 가능한 PDF로 변환하는 방법도 다루었습니다. 이제 코드를 활용해 다양한 시나리오에 적용해 보세요. + +## 다음에 배워야 할 내용은? + +다음 튜토리얼들은 이 가이드에서 시연한 기술을 기반으로 하여 관련 주제를 깊이 있게 다룹니다. 각 리소스는 완전한 코드 예제와 단계별 설명을 제공하므로, 추가 API 기능을 마스터하고 프로젝트에 다양한 구현 방식을 적용하는 데 도움이 됩니다. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/korean/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..d0a331fa8 --- /dev/null +++ b/ocr/korean/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR을 사용하여 비디오에서 프레임을 추출하고 MP4와 같은 비디오 파일에서 텍스트를 읽는 방법을 보여주는 비디오 + 자막 OCR 튜토리얼. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: ko +og_description: Aspose.OCR로 비디오 자막 OCR을 배우세요. 비디오에서 프레임을 추출하고, 비디오 텍스트를 읽으며, MP4에서 + 텍스트를 몇 분 안에 추출합니다. +og_title: C#로 비디오 자막 OCR – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: C#를 이용한 비디오 자막 OCR – 완전 가이드 +url: /ko/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 비디오 자막 OCR – 완전 가이드 + +비디오 자막 OCR이 필요했지만 어디서 시작해야 할지 몰랐던 적이 있나요? 당신만 그런 것이 아닙니다. 강의 녹화를 디지털화하거나, 교육 비디오에서 캡션을 추출하거나, 비디오에서 텍스트를 읽는 것에 호기심이 있든, 이 튜토리얼은 C#과 Aspose.OCR을 사용해 정확히 어떻게 하는지 보여줍니다. + +다음 몇 분 안에 비디오에서 프레임을 추출하고, 그 프레임에 OCR을 실행한 뒤, 자막 텍스트를 프레임별로 표시합니다. 끝까지 따라오면 MP4를 포함한 **비디오 파일에서 텍스트를 읽는** 방법을 서드파티 도구 없이도 구현할 수 있습니다. + +## 만들게 될 것 + +작은 콘솔 앱을 만들 것입니다: + +1. MP4(또는 지원되는 형식)를 개별 `Bitmap` 프레임으로 디코딩합니다. +2. OCR 영역을 자막 밴드로 제한해 엔진이 전체 화면에 방해받지 않게 합니다. +3. 각 프레임을 Aspose의 `VideoOcrProcessor`로 처리합니다. +4. 인식된 자막 텍스트를 콘솔에 출력합니다. + +불필요한 설명 없이 실제 프로젝트에 바로 넣을 수 있는 엔드‑투‑엔드 예제입니다. + +## 사전 요구 사항 + +- **.NET 6.0** 이상(코드는 .NET Framework 4.7+에서도 동작합니다). +- **Aspose.OCR for .NET** – NuGet으로 설치: `Install-Package Aspose.OCR`. +- 비디오 파일(MP4 권장). +- 비디오 프레임을 디코딩할 방법 – 데모에서는 자리표시자 메서드를 사용하지만, FFmpeg, OpenCV 등 `Bitmap` 객체를 반환하는 라이브러리를 연결하면 됩니다. + +> **프로 팁:** Windows에서는 `System.Drawing.Common` 패키지가 `Bitmap`에 잘 동작합니다. Linux/macOS에서는 네이티브 `libgdiplus` 의존성이 필요합니다. + +## 1단계 – 비디오에서 프레임 추출 + +첫 번째 장벽은 움직이는 영상을 정지 이미지로 바꾸는 것입니다. 아래 `GetVideoFrames` 메서드는 의도적으로 비워두었습니다; 좋아하는 디코더로 교체하세요. 여기서는 FFmpeg‑Core를 사용한 간단한 스케치를 보여줍니다(데이터 형태를 보여주기 위함). + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **왜 중요한가:** 프레임을 추출하면 OCR 엔진이 정적인 이미지를 대상으로 작업하게 되어, 비디오 스트림에서 직접 읽는 것보다 정확도가 크게 향상됩니다. + +## 2단계 – VideoOcrProcessor 설정 + +이제 `Bitmap` 객체 시퀀스가 준비되었으니 Aspose.OCR에 전달할 수 있습니다. `VideoOcrProcessor`는 **관심 영역(ROI)**을 정의할 수 있게 해 주며, 이는 보통 프레임 상단이나 하단에 위치하는 자막에 적합합니다. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **ROI를 제한하는 이유:** 나머지 화면을 무시함으로써 노이즈를 줄이고 처리 시간을 단축하며, 배경 그래픽으로 인한 오탐지를 방지합니다. + +## 3단계 – 프레임 시퀀스에 OCR 실행 + +프로세서가 준비되면 프레임을 전달하는 코드는 한 줄이면 됩니다. `Process` 메서드는 각 프레임에 대응하는 `OcrResult` 객체 열거형을 반환하며, 여기에는 인식된 텍스트가 들어 있습니다. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **내부 동작:** Aspose.OCR은 각 비트맵을 정규화하고, 신경망 기반 인식기를 실행한 뒤, 구두점 및 줄 바꿈을 개선하도록 후처리합니다. + +## 4단계 – 추출된 텍스트 표시 + +마지막으로 결과를 순회하면서 각 자막 라인을 출력합니다. SRT 파일, 데이터베이스에 저장하거나 번역 서비스에 전달할 수도 있습니다. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### 전체 작동 예제 + +모든 코드를 합치면 독립 실행형 콘솔 프로그램이 됩니다: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**예상 출력(샘플)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +특정 프레임에서 OCR이 제대로 동작하지 않으면 빈 문자열이 반환됩니다—이는 ROI를 조정하거나 프레임 추출 비율을 높여야 함을 의미합니다. + +## 흔히 발생하는 문제와 해결 방법 + +| 문제 | 발생 원인 | 해결 방법 | +|-------|----------------|-----| +| **깨진 문자** | 저해상도 프레임 또는 과도한 압축 | 높은 비트레이트로 프레임을 추출하거나 OCR 전에 비트맵을 확대(`Bitmap.Clone(new Size(...), ...)`) | +| **텍스트 미반환** | ROI가 실제 자막 밴드를 포함하지 않음 | 사각형 좌표를 확인(스크린샷 도구로 측정) | +| **성능 병목** | 30 fps 전체 프레임을 처리하는 것은 과도함 | 대부분의 자막 스트림은 1‑2 fps로 다운샘플링해도 충분 | +| **FFmpeg를 찾을 수 없음** | `ffmpeg.exe`가 `PATH`에 없음 | `ProcessStartInfo.FileName`에 전체 경로 지정하거나 전역 설치 | + +## 솔루션 확장하기 + +- **SRT로 내보내기** – 타임스탬프와 OCR 텍스트를 결합해 SubRip 파일 작성. +- **다국어 지원** – `ocrProcessor.Language = OcrLanguage.Spanish`(또는 지원되는 다른 언어) 설정. +- **실시간 처리** – 디스크가 아닌 라이브 스트림에서 직접 프레임을 파이프라인으로 전달. + +이 모든 변형은 **비디오에서 프레임 추출**, **비디오에서 텍스트 읽기**, **mp4에서 텍스트 추출**이라는 핵심 아이디어를 중심으로 합니다. + +## 결론 + +우리는 C#에서 완전한 **비디오 자막 OCR** 워크플로우를 단계별로 살펴보았습니다. 비디오에서 프레임을 추출하고, 자막 밴드에 OCR을 집중시키며, 결과를 순회함으로써 MP4와 같은 **비디오 파일에서 텍스트를 읽는** 작업을 안정적으로 수행할 수 있습니다. 코드는 바로 복사‑붙여넣기 가능하고, 모듈식 설계 덕분에 원하는 프레임 디코더로 쉽게 교체할 수 있습니다. + +다음 단계는? 결과를 SRT 파일로 내보내거나, 다양한 ROI 크기를 실험해 보거나, 자막을 번역 API에 연결해 다국어 캡션을 만들어 보세요. 텍스트 추출 기본기를 마스터하면 이제 무한히 확장할 수 있습니다. + +행복한 코딩 되시고, 자막이 언제나 선명하길 바랍니다! + +## 다음에 배울 내용은? + +다음 튜토리얼들은 이 가이드에서 다룬 기술을 기반으로 하며, 단계별 설명과 완전한 코드 예제를 포함하고 있어 추가 API 기능을 마스터하고 다양한 구현 방식을 탐구하는 데 도움이 됩니다. + +- [Aspose.OCR을 사용한 언어 선택이 가능한 C# 이미지 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR .NET을 이용한 이미지 텍스트 추출](/ocr/english/net/image-and-drawing-recognition/) +- [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/polish/net/ocr-configuration/_index.md b/ocr/polish/net/ocr-configuration/_index.md index 53dfac79c..2ef982087 100644 --- a/ocr/polish/net/ocr-configuration/_index.md +++ b/ocr/polish/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Odblokuj moc rozpoznawania obrazu OCR w .NET dzięki Aspose.OCR. Łatwo wyodręb Uzyskaj potężne możliwości OCR z Aspose.OCR dla .NET. Bezproblemowo wyodrębniaj tekst z obrazów w różnych językach. ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) Wykorzystaj potencjał Aspose.OCR dla .NET. Łatwo wykonuj rozpoznawanie obrazu OCR przy użyciu list. Zwiększ produktywność i wyodrębnianie danych w swoich aplikacjach. +### [Uzyskaj wersję Aspose OCR w C# – Kompletny przewodnik](./get-aspose-ocr-version-in-c-complete-guide/) +Dowiedz się, jak programowo sprawdzić wersję biblioteki Aspose.OCR w aplikacji C#. ### Typowe przypadki użycia - **Wyodrębnianie tekstu z obrazów** ze skanowanych faktur w celu automatycznej księgowości. @@ -102,4 +104,4 @@ A: Tak, obiekt `OcrResult` udostępnia wartości pewności, które możesz progr {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/polish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a92cf0cdb --- /dev/null +++ b/ocr/polish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: Uzyskaj wersję Aspose OCR w C# za pomocą prostego fragmentu kodu. Dowiedz + się, jak pobrać wersję biblioteki Aspose OCR przy użyciu OcrEngine.GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: pl +og_description: Szybko uzyskaj wersję Aspose OCR w C#. Ten samouczek pokazuje dokładnie, + jak pobrać wersję biblioteki Aspose OCR przy użyciu OcrEngine GetVersion. +og_title: Pobierz wersję Aspose OCR w C# – Kompletny przewodnik +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Pobierz wersję Aspose OCR w C# – Kompletny przewodnik +url: /pl/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pobierz wersję Aspose OCR w C# – Kompletny przewodnik + +Zastanawiałeś się kiedyś, jak **pobrać wersję Aspose OCR** w swoim projekcie .NET? Może rozwiązujesz problem niezgodności wersji, a może po prostu chcesz zalogować dokładny numer biblioteki działającej w produkcji. Niezależnie od powodu, trafiłeś we właściwe miejsce. + +W tym tutorialu przeprowadzimy Cię przez mały, samodzielny program w C#, który wywołuje `OcrEngine.GetVersion()` i wypisuje wynik. Po zakończeniu będziesz wiedział nie tylko *jak* pobrać wersję, ale także *dlaczego* sprawdzanie wersji może zaoszczędzić Ci wiele problemów przy aktualizacji **biblioteki Aspose OCR**. + +## Czego się nauczysz + +- Dodanie pakietu NuGet Aspose.OCR do projektu C# +- Użycie metody `OcrEngine.GetVersion()` (punkt wejścia **ocrengine getversion**) +- Obsługa możliwych wyjątków i weryfikacja wyniku +- Rozszerzenie fragmentu kodu o scenariusze produkcyjne, takie jak logowanie czy warunkowe włączanie funkcji + +Nie wymagana jest wcześniejsza znajomość OCR — wystarczy podstawowa wiedza o C# i Visual Studio (lub Twoim ulubionym IDE). Zaczynajmy. + +--- + +## Krok 1: Przygotuj projekt i pobierz bibliotekę Aspose OCR + +Zanim będziesz mógł wywołać jakiekolwiek API związane z OCR, musisz mieć **bibliotekę Aspose OCR** dodaną do swojego projektu. + +1. Otwórz terminal lub konsolę Package Manager w Visual Studio. +2. Uruchom następujące polecenie, aby zainstalować najnowszą stabilną wersję: + +```bash +dotnet add package Aspose.OCR +``` + +> **Wskazówka:** Jeśli celujesz w .NET Framework zamiast .NET Core, użyj interfejsu UI Menedżera Pakietów NuGet i wybierz wersję pasującą do Twojego środowiska uruchomieniowego. Pakiet zawiera klasę `OcrEngine`, której użyjemy później. + +### Dlaczego to ważne + +Podczas instalacji pakietu wersja zestawu na dysku może różnić się od wersji zwracanej przez bibliotekę w czasie działania. Pobranie wersji za pomocą kodu zapewnia, że odczytujesz dokładnie tę kompilację, którą CLR załadował, co jest kluczowe przy debugowaniu i audytach zgodności. + +--- + +## Krok 2: Napisz minimalny kod, aby **pobrać wersję Aspose OCR** + +Utwórz nową aplikację konsolową (`dotnet new console -n OcrVersionDemo`) i zamień domyślny plik `Program.cs` na poniższy: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Wyjaśnienie poszczególnych części** + +- `using Aspose.OCR;` wprowadza przestrzeń nazw OCR, umożliwiając wywołanie `OcrEngine`. +- `OcrEngine.GetVersion()` to statyczna metoda **ocrengine getversion**, zwracająca łańcuch w formacie np. `"24.5.7"`. +- Umieszczenie wywołania w bloku `try/catch` chroni przed niespodziewanymi problemami w czasie działania — np. brak natywnych binarek na docelowej maszynie. +- Interpolowany łańcuch `$"Aspose OCR version: {version}"` wypisuje czytelną, przyjazną dla człowieka linię. + +### Oczekiwany wynik + +Po uruchomieniu `dotnet run` w katalogu projektu powinieneś zobaczyć coś podobnego do: + +``` +Aspose OCR version: 24.5.7 +``` + +Jeśli biblioteka nie zostanie załadowana, gałąź obsługi błędu wypisze zwięzły komunikat, pomagając szybko zlokalizować problem. + +--- + +## Krok 3: Zweryfikuj, czy wersja odpowiada Twojemu pakietowi NuGet + +Łatwo założyć, że wersja NuGet, którą zainstalowałeś, jest tą samą, która jest używana w czasie działania, ale różne okoliczności środowiskowe mogą to zmienić. Aby podwójnie sprawdzić: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Uruchomienie tego dodatkowego fragmentu wypisze coś w stylu: + +``` +Assembly file version: 24.5.7.0 +``` + +Jeśli dwie wartości się różnią, możesz ładować starszy plik DLL z Global Assembly Cache (GAC) lub z poprzedniego folderu kompilacji. W takim wypadku wyczyść rozwiązanie (`dotnet clean`) i przebuduj projekt. + +--- + +## Krok 4: Umieść sprawdzenie wersji w logowaniu produkcyjnym + +Większość rzeczywistych aplikacji nie wypisuje jedynie do konsoli; zapisują informacje w pliku logu lub systemie telemetrycznym. Oto szybki przykład z użyciem `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Teraz wersja pojawia się w Twoich strukturalnych logach, co ułatwia późniejsze filtrowanie po `{Version}`. Ten wzorzec jest szczególnie przydatny, gdy masz wiele mikroserwisów, z których każdy może korzystać z innej wersji DLL OCR. + +--- + +## Często zadawane pytania i sytuacje brzegowe + +### Co zrobić, gdy `GetVersion()` zwraca pusty łańcuch? + +Zazwyczaj oznacza to uszkodzoną instalację lub brak natywnej zależności. Przeinstaluj pakiet NuGet i upewnij się, że plik `Aspose.OCR.Native.dll` (lub odpowiednia binarka platformowa) znajduje się obok Twojego pliku wykonywalnego. + +### Czy metoda działa w .NET Core 2.0? + +Tak, **Aspose OCR** obsługuje .NET Standard 2.0 i wyższy, więc każda wersja .NET Core implementująca ten standard może wywołać `OcrEngine.GetVersion()`. Pamiętaj jedynie o wskazaniu właściwych identyfikatorów środowiska uruchomieniowego (`win-x64`, `linux-x64` itp.) przy publikacji aplikacji samodzielnej. + +### Czy mogę pobrać wersję bez pliku licencyjnego? + +Oczywiście. `GetVersion()` **nie** wymaga licencji; po prostu zwraca numer kompilacji biblioteki. Jednakże, jeśli spróbujesz wykonać OCR bez ważnej licencji, otrzymasz wyjątek w czasie działania. Dlatego blok `try/catch` w naszym przykładzie jest przydatny — oddziela sprawdzenie wersji od samego procesu OCR. + +--- + +## Pełny działający przykład (gotowy do kopiowania) + +Poniżej znajduje się cały program, gotowy do wklejenia w nowym projekcie konsolowym. Zawiera opcjonalny blok logowania, więc możesz zobaczyć zarówno wyjście konsoli, jak i strukturalne logi w akcji. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Uruchom go poleceniem `dotnet run`, a zobaczysz dwie linie potwierdzające wersję oraz dodatkową linię debugowania, jeśli włączysz `LogLevel.Debug`. + +--- + +## Podsumowanie + +Omówiliśmy wszystko, co potrzebne, aby **pobrać wersję Aspose OCR** w środowisku C# — od instalacji **biblioteki Aspose OCR**, wywołania metody **ocrengine getversion**, obsługi błędów, po włączenie wyniku do logowania produkcyjnego. Mając tę wiedzę, możesz niezawodnie weryfikować, którą dokładnie wersję OCR używa Twoja aplikacja, unikać błędów związanych z wersjami i spełniać wymogi zgodności bez zbędnego stresu. + +Co dalej? Spróbuj połączyć to sprawdzenie wersji z rzeczywistym wywołaniem OCR (`OcrEngine` → `RecognizeImage`) i loguj zarówno wersję, jak i wynik rozpoznawania. Możesz także zbadać wzorzec **retrieve aspose version** dla innych produktów Aspose (PDF, Slides, Cells), aby utrzymać cały zestaw w synchronizacji. + +Miłego kodowania i niech Twoje potoki OCR pozostaną ostre! + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują tematy blisko powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz krok‑po‑kroku wyjaśnienia, pomagające opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/polish/net/ocr-optimization/_index.md index 9273072bb..cbd149388 100644 --- a/ocr/polish/net/ocr-optimization/_index.md +++ b/ocr/polish/net/ocr-optimization/_index.md @@ -81,6 +81,9 @@ Popraw dokładność OCR przy użyciu Aspose.OCR for .NET. Poprawiaj pisownię, ### [Zapisz wielostronicowy wynik jako dokument w rozpoznawaniu obrazu OCR](./save-multipage-result-as-document/) Odblokuj potencjał Aspose.OCR for .NET. Bezproblemowo zapisz wielostronicowe wyniki OCR jako dokumenty dzięki temu kompleksowemu przewodnikowi krok po kroku. +### [Przykład Aspose OCR w C# – Włącz GPU, Ustaw Limit Pamięci i Przetwarzaj Obrazy TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Dowiedz się, jak w Aspose OCR w C# włączyć akcelerację GPU, ustawić limit pamięci i przetwarzać obrazy w formacie TIF. + ## Często zadawane pytania **Q: Czy można wyodrębnić teksty z plików graficznych wielu języków?** diff --git a/ocr/polish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/polish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..10a9b8809 --- /dev/null +++ b/ocr/polish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-03 +description: Przykład Aspose OCR w C# pokazujący, jak ustawić limit pamięci GPU, wczytać + obraz do OCR i rozpoznać tekst z plików TIF, wraz z pełnym kodem i wskazówkami. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: pl +og_description: 'Poznaj kompletny przykład Aspose OCR w C#: włącz GPU, ustaw limit + pamięci GPU, wczytaj obraz do OCR i rozpoznaj tekst z plików TIF. Pełny kod w zestawie.' +og_title: Przykład Aspose OCR w C# – przyspieszenie GPU, limit pamięci i przetwarzanie + TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Przykład Aspose OCR w C# – Włącz GPU, ustaw limit pamięci i przetwarzaj obrazy + TIF +url: /pl/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – Włącz GPU, Ustaw Limit Pamięci i Przetwarzaj Obrazy TIF + +Zastanawiałeś się kiedyś, jak wycisnąć maksymalną wydajność z kodu **Aspose OCR C# example** przy pracy z ogromnymi skanami TIFF? Nie jesteś sam. W wielu projektach rzeczywistych — myśl o digitalizacji archiwów lub wyodrębnianiu danych z wysokiej rozdzielczości paragonów — wąskim gardłem nie jest sam algorytm OCR, lecz wykorzystanie sprzętu. + +Oto co: Aspose OCR obsługuje przyspieszenie GPU, ale musisz dokładnie określić, ile pamięci może zużywać, załadować odpowiedni typ obrazu i w końcu wyciągnąć rozpoznany tekst z pliku .tif. Ten samouczek przeprowadzi Cię przez każdy krok, od instalacji SDK po dostosowanie ustawień GPU, abyś mógł uruchomić OCR z błyskawiczną prędkością bez wyczerpania pamięci RAM GPU. + +Dodamy także kilka scenariuszy „co jeśli” — np. obsługa wielostronicowych TIFF‑ów lub przejście na CPU, gdy GPU nie jest dostępne — abyś otrzymał solidne rozwiązanie, a nie jedynie jednorazowy fragment kodu. + +## Czego będziesz potrzebować + +Zanim zanurkujemy, upewnij się, że masz następujące elementy na swoim komputerze: + +| Wymaganie | Dlaczego jest ważne | +|--------------|----------------| +| **.NET 6 SDK** (lub nowszy) | Aspose OCR celuje w .NET Standard 2.0+, więc każda nowsza wersja .NET działa. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | Główna biblioteka, która dostarcza `OcrEngine`, `GpuSettings`, itd. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Wymagane do przyspieszenia GPU; SDK sprawdzi kompatybilny sterownik w czasie wykonywania. | +| GPU z co najmniej 2 GB VRAM (ustawimy limit na 2048 MB) | Bez wystarczającej pamięci silnik może cicho przełączyć się na CPU. | +| Obraz **wysokiej rozdzielczości TIFF**, który chcesz przetworzyć | Aspose OCR potrafi odczytać praktycznie każdy format rastrowy, ale TIF jest powszechny w skanach. | +| Visual Studio 2022 (lub dowolny edytor, który lubisz) | Do budowania i debugowania projektu C#. | + +Jeśli którekolwiek z nich brakuje, kod nadal się skompiluje, ale nie zobaczysz oczekiwanych przyrostów wydajności. + +## Krok 1: Utwórz silnik przykładu Aspose OCR C# + +Pierwszą rzeczą w każdym **Aspose OCR C# example** jest utworzenie instancji silnika OCR. Pomyśl o `OcrEngine` jako reżyserze filmu — koordynuje wszystko, od ładowania obrazu po wyodrębnianie tekstu. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Wskazówka:** Jeśli planujesz przetwarzać wiele obrazów kolejno, utrzymuj jedną instancję `OcrEngine`. Tworzenie jej ponownie dla każdego obrazu dodaje narzut, który może przyćmić czas OCR. + +## Krok 2: Ustaw limit pamięci GPU (i włącz przyspieszenie) + +Teraz przychodzi część, która często sprawia problemy: **ustaw limit pamięci GPU**. Domyślnie Aspose OCR będzie próbował używać tak dużo VRAM, jak to możliwe, co na współdzielonym stanowisku może pozbawić inne aplikacje zasobów. Obiekt `GpuSettings` pozwala ograniczyć przydział. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Dlaczego ustawiać limit pamięci? + +- **Stabilność:** Zapobiega awariom z powodu braku pamięci przy przetwarzaniu gigantycznych obrazów. +- **Współistnienie:** Pozwala innym aplikacjom intensywnie korzystającym z GPU (np. modele TensorFlow) działać równolegle. +- **Przewidywalność:** Umożliwia powtarzalne testy wydajności, ponieważ GPU nie zacznie wymieniać pamięci. + +Jeśli pominiesz `MemoryLimitMb`, Aspose przydzieli tyle pamięci, ile uzna za konieczne, co może być w porządku na dedykowanym serwerze inferencyjnym, ale ryzykowne na laptopie dewelopera. + +## Krok 3: Załaduj obraz do OCR + +Załadowanie właściwego formatu pliku to kolejny kluczowy element. Metoda `OcrImage.FromFile` automatycznie wykrywa typ obrazu, ale nadal powinieneś sprawdzić, czy plik istnieje i czy jest obsługiwaną wariacją TIFF (np. skompresowany LZW lub CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Obsługa wielostronicowych TIFF‑ów + +Jeśli Twój TIFF zawiera kilka stron, Aspose OCR domyślnie odczyta tylko pierwszą. Aby przetworzyć wszystkie strony, możesz iterować po `image.Pages` (dostępne w nowszych wersjach SDK) i przekazywać każdą stronę do silnika osobno. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Powyższy fragment demonstruje wzorzec **load image for OCR**, który działa zarówno dla plików jednostronicowych, jak i wielostronicowych. + +## Krok 4: Rozpoznaj tekst z TIF (lub dowolnego rastrowego) + +Teraz, gdy obraz znajduje się w pamięci, prosimy Aspose o wykonanie magii. Metoda `Recognize` zwraca `OcrResult`, który zawiera czysty tekst, wyniki pewności oraz informacje o prostokątach ograniczających, jeśli są potrzebne. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Dlaczego to dobrze działa z TIF + +- **Bezstratna kompresja:** TIFF często przechowuje surowe dane pikseli, zapewniając silnikowi OCR najwyższą wierność. +- **Wiele przestrzeni kolorów:** Aspose może obsługiwać TIFF‑y w odcieniach szarości, RGB lub nawet CMYK bez dodatkowego kodu konwersji. + +Jeśli potrzebujesz dostosować pakiety językowe (np. francuski lub japoński), ustaw `ocrEngine.Settings.Language = "fr"` przed wywołaniem `Recognize`. + +## Krok 5: Wyświetl rozpoznany tekst + +Na koniec wypisujemy tekst na konsolę. W rzeczywistej aplikacji możesz zapisać go do bazy danych, pliku JSON lub przekazać ciąg do dalszego potoku NLP. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Oczekiwany wynik + +Uruchomienie programu na wyraźnym skanie 300 dpi wydrukowanej strony zazwyczaj daje coś w rodzaju: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Jeśli obraz jest rozmazany lub limit pamięci GPU jest zbyt niski, możesz zobaczyć zniekształcone znaki lub obcięty wynik. Obniżenie `MemoryLimitMb` poniżej rozmiaru obrazu (często ~1 GB dla TIFF‑a 6000×8000 pikseli) może spowodować automatyczne przejście silnika na CPU. + +## Pełny działający przykład + +Poniżej znajduje się kompletny, gotowy do uruchomienia program. Skopiuj i wklej go do nowego projektu Console App, zamień `YOUR_DIRECTORY/large_photo.tif` na ścieżkę do własnego pliku TIFF i naciśnij **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Szybka lista kontrolna + +- ✅ **Aspose OCR C# example** skompilowany bez błędów. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** ustawiony na 2048 MB. +- ✅ **Image loaded** z pliku TIF. +- ✅ **Text recognized** i wydrukowany. + +## Częste pułapki i jak ich uniknąć + +| Objaw | Prawdopodobna przyczyna | Rozwiązanie | +|---------|------------------------------|-------------| +| `System.DllNotFoundException: cudart64_110.dll` | Środowisko uruchomieniowe CUDA nie jest zainstalowane lub wersja nie pasuje. | Zainstaluj CUDA 11.x (lub 12.x) zgodną z Twoim sterownikiem. | +| OCR returns empty string | Obraz jest zbyt ciemny lub DPI < 150. | Wstępnie przetwórz za pomocą `image.AdjustContrast()` lub przeskaluj do 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` jest za niski dla obrazu. | Zwiększ limit lub podziel obraz na kafelki za pomocą `image.Crop`. | +| `Unsupported image format` error | TIFF używa egzotycznej kompresji (np. JPEG‑2000). | Przekonwertuj TIFF na obsługiwany format przy użyciu ImageMagick przed OCR. | + +## Rozszerzanie demo + +Teraz, gdy masz solidny **aspose ocr c# example**, możesz chcieć zbadać: + +- **Przetwarzanie wsadowe:** Iteruj po folderze TIF‑ów, zapisuj każdy wynik do pliku `.txt`. +- **Pakiety językowe:** `ocrEngine.Settings.Language = "es"` dla hiszpańskiego lub wczytaj własne słowniki. +- **Prostokąty ograniczające:** Użyj `ocrResult.Regions`, aby uzyskać współrzędne dla każdego słowa — przydatne w narzędziach do redakcji. +- **Przejście na CPU:** Otocz blok GPU w try/catch; w razie niepowodzenia ustaw `ocrEngine.Settings.Gpu.Enable = false` i spróbuj ponownie. + +Te rozszerzenia zachowują podstawowy wzorzec, jednocześnie dodając wartość dla konkretnych zastosowań‑ + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Wyodrębnij tekst z obrazu przy użyciu Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Wyodrębnij tekst z obrazu – optymalizacja OCR z Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [Wyodrębnij tekst z obrazu C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/skew-angle-calculation/_index.md b/ocr/polish/net/skew-angle-calculation/_index.md index 76c885f05..97bc66c3a 100644 --- a/ocr/polish/net/skew-angle-calculation/_index.md +++ b/ocr/polish/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Poznaj Aspose.OCR dla .NET, potężne rozwiązanie OCR do dokładnego rozpoznawa Uwolnij moc Aspose.OCR dla .NET, solidnego rozwiązania do rozpoznawania obrazów. Dowiedz się, jak bez wysiłku obliczać kąty skośne. ### [Oblicz kąt pochylenia z URI w rozpoznawaniu obrazu OCR](./calculate-skew-angle-from-uri/) Przeglądaj Aspose.OCR dla .NET, aby bez wysiłku obliczyć kąty skosu w rozpoznawaniu obrazów OCR. Ulepsz swoje projekty z precyzją i wydajnością. +### [Samouczek dokumentu obróconego OCR – automatyczna korekta pochylenia i rotacji w C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Dowiedz się, jak automatycznie wykrywać i korygować pochylenie oraz rotację dokumentów w OCR przy użyciu Aspose.OCR w C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/polish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..c030d1e02 --- /dev/null +++ b/ocr/polish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Samouczek OCR obróconego dokumentu, który pokazuje, jak automatycznie + korygować pochylenie i wykrywać obrót przy użyciu Aspose OCR w C#. Naucz się krok + po kroku z pełnym kodem. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: pl +og_description: Samouczek OCR obróconego dokumentu uczy, jak automatycznie korygować + pochylenie i wykrywać obrót przy użyciu Aspose OCR w C#. Przejdź do pełnego przewodnika. +og_title: Samouczek OCR obróconego dokumentu – Automatyczne prostowanie i naprawa + rotacji w C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Samouczek OCR obróconego dokumentu – Automatyczna korekta pochylenia i rotacji + w C# +url: /pl/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Rotated Document Tutorial – Pełny przewodnik dla programistów C# + +Czy kiedykolwiek natknąłeś się na **ocr rotated document tutorial**, gdy zeskanowany formularz był obrócony lub przechylony? Nie jesteś sam. Te krzywe obrazy mogą zepsuć czyste wyodrębnianie tekstu, ale dobra wiadomość jest taka, że Aspose OCR może automatycznie je wyprostować. + +W tym przewodniku krok po kroku uruchomimy `OcrEngine`, włączymy **automatic skew correction** i **auto detect rotation**, uruchomimy silnik na obróconym obrazie i wydrukujemy czysty tekst. Po zakończeniu dokładnie zrozumiesz, dlaczego każde ustawienie ma znaczenie, jak je dostosować do trudnych przypadków i będziesz mieć gotowy do uruchomienia program w C#. + +## Czego się nauczysz + +* Jak zainstalować i odwołać się do **Aspose OCR** w projekcie .NET. +* Dlaczego włączenie `AutoCorrectSkew` i `AutoDetectRotation` jest kluczem do niezawodnego **ocr rotated document tutorial**. +* Jak załadować dowolny obraz (JPG, PNG, TIFF) i pozwolić silnikowi wykonać ciężką pracę. +* Wskazówki dotyczące obsługi wielostronicowych PDF‑ów, skanów o niskiej rozdzielczości i własnych pakietów językowych. + +> **Wymagania wstępne:** Visual Studio 2022 (lub dowolne IDE C#), środowisko uruchomieniowe .NET 6+, oraz ważna licencja Aspose OCR (lub wersja próbna). Nie wymagana jest wcześniejsza znajomość OCR. + +--- + +## Krok 1 – Zainstaluj Aspose OCR i skonfiguruj projekt + +Na początek. Pobierz pakiet NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Porada:** Jeśli używasz licencji próbnej, umieść plik `Aspose.OCR.lic` w tym samym folderze co plik wykonywalny lub zarejestruj go programowo za pomocą `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Utwórz nową aplikację konsolową: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Teraz masz czystą bazę dla naszego **ocr rotated document tutorial**. + +## Krok 2 – Zainicjalizuj silnik OCR + +Silnik jest sercem procesu. Traktuj go jak scyzoryk szwajcarski do wyodrębniania tekstu; musisz tylko powiedzieć mu, które funkcje włączyć. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Dlaczego te ustawienia?** +* `AutoCorrectSkew` analizuje linię bazową znaków i obraca obraz wystarczająco, aby linie były poziome. +* `AutoDetectRotation` sprawdza ogólną orientację (0°, 90°, 180°, 270°) i odwraca stronę, jeśli jest do góry nogami. Bez nich silnik odczytałby „pɹᴉʍ” zamiast „word”. + +## Krok 3 – Załaduj obraz, który chcesz przetworzyć + +Aspose OCR działa z każdym popularnym formatem rastrowym. Zamień ścieżkę zastępczą na rzeczywistą lokalizację twojego obróconego formularza. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Przypadek brzegowy:** Jeśli otrzymasz wielostronicowy TIFF, użyj `OcrImage.FromMultiPageTiff(filePath)` i przeiteruj `image.Pages`. + +## Krok 4 – Uruchom rozpoznawanie + +Teraz silnik wykonuje magię. Najpierw wyprostuje obraz (dzięki naszym flagom skew/rotation), a następnie wyciągnie znaki. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Jeśli potrzebujesz wsparcia językowego poza językiem angielskim, ustaw je przed wywołaniem `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Krok 5 – Wyświetl rozpoznany tekst + +Na koniec wypisz czysty tekst na konsolę — albo przekieruj go do pliku, bazy danych, cokolwiek pasuje do twojego przepływu pracy. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Oczekiwany wynik** (zakładając, że przykładowy obraz zawiera „Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Zauważ, że tekst pojawia się poprawnie, mimo że źródłowy obraz był obrócony o 90° i lekko przechylony. + +--- + +## Radzenie sobie z typowymi problemami + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Pusty wynik** | Korekcja pochylenia wyłączona lub obraz zbyt ciemny. | Włącz `AutoCorrectSkew` (już włączone) i zwiększ kontrast obrazu za pomocą `image.AdjustContrast(1.2)`. | +| **Śmieciowe znaki** | Nieprawidłowe ustawienie języka. | Ustaw `ocrEngine.Settings.Language` na język dokumentu. | +| **Opóźnienie wydajności przy dużych PDF‑ach** | Silnik przetwarza każdą stronę kolejno. | Użyj `Parallel.ForEach` na `image.Pages`, aby wykorzystać wielordzeniowe CPU. | +| **Wyjątek licencyjny** | Wersja próbna wygasła. | Uzyskaj stałą licencję lub pozostaw się w granicach limitów wersji próbnej (5 stron na uruchomienie). | + +--- + +## Profesjonalne wskazówki dla solidnego OCR Rotated Document Tutorial + +* **Przetwarzanie wsadowe:** Owiń cały przepływ w metodę przyjmującą ścieżkę folderu, iterującą po każdym obrazie i zapisującą każdy wynik do pliku `.txt`. +* **Pre‑processing:** Czasami szumy skanu można zredukować przy pomocy `image.Denoise()` przed rozpoznaniem. +* **Post‑processing:** Użyj wyrażeń regularnych do czyszczenia typowych błędów OCR, np. zamień „0” na „O” tylko gdy otoczone jest literami. +* **Logowanie:** Aspose OCR udostępnia `ocrEngine.Logger` – podłącz go do loggera plikowego, aby przechwytywać ostrzeżenia o niskich wartościach pewności. + +--- + +## Pełny, gotowy do uruchomienia kod + +Zapisz poniższy kod jako `Program.cs` w swoim projekcie konsolowym. Zawiera wszystkie kroki, komentarze i mały pomocnik do przetwarzania wsadowego. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Uruchom go: + +```bash +dotnet run +``` + +Powinieneś zobaczyć wyczyszczony tekst wypisany na konsolę, co dowodzi, że nasz **ocr rotated document tutorial** działa od początku do końca. + +--- + +## Zakończenie + +Masz teraz kompletny **ocr rotated document tutorial**, który automatycznie koryguje pochylenie, wykrywa obrót i wyodrębnia czysty tekst przy użyciu Aspose OCR w C#. Najważniejsze wnioski? Włączenie `AutoCorrectSkew` **i** `AutoDetectRotation` zamienia beznadziejnie przechylony skan w idealnie czytelny wynik przy użyciu kilku linii kodu. + +Od tego momentu możesz rozszerzyć rozwiązanie o zadania wsadowe, zintegrować pakiety językowe lub przekazać wyniki do kolejnych etapów analizy danych. Chcesz dalej zgłębić **automatic skew correction**? Sprawdź API przetwarzania obrazu Aspose lub eksperymentuj z własnymi progami dla szumnych skanów. + +Masz pytania dotyczące obsługi PDF‑ów, wielostronicowych TIFF‑ów lub integracji z Azure Functions? Zostaw komentarz i powodzenia w kodowaniu! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [tryb dokumentu OCR – Tryb wykrywania obszarów w rozpoznawaniu obrazu OCR](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Wyodrębnij tekst z obrazu C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Samouczek Aspose OCR – Rozpoznawanie znaków optycznych](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/polish/net/text-recognition/_index.md index 40c85d634..e7f7fe6fe 100644 --- a/ocr/polish/net/text-recognition/_index.md +++ b/ocr/polish/net/text-recognition/_index.md @@ -23,7 +23,7 @@ W tym samouczku poprowadzimy Cię przez wykorzystanie możliwości Aspose.OCR dl ## Uzyskaj wynik rozpoznawania w trybie rozpoznawania obrazu OCR -Poznaj możliwości Aspose.OCR dla .NET i zmień sposób obsługi rozpoznawania tekstu w obrazach. Odkryj zawiłości uzyskiwania wyników rozpoznawania dzięki naszemu obszernemu przewodnikowi. Niezależnie od tego, czy jesteś doświadczonym programistą, czy dopiero zaczynasz, ten samouczek umożliwi Ci bezproblemową integrację OCR z Twoimi projektami. +Poznaj możliwości Aspose.OCR dla .NET i zmień sposób obsługi rozpoznawania tekstu w obrazach. Odkryj zawiłości uzyskiwania wyników rozpoznania dzięki naszemu obszernemu przewodnikowi. Niezależnie od tego, czy jesteś doświadczonym programistą, czy dopiero zaczynasz, ten samouczek umożliwi Ci bezproblemową integrację OCR z Twoimi projektami. ## Uzyskaj wynik jako JSON w rozpoznawaniu obrazu OCR @@ -55,9 +55,20 @@ Ulepsz swoje aplikacje .NET za pomocą Aspose.OCR, aby efektywnie rozpoznawać t Odblokuj potencjał OCR w .NET dzięki Aspose.OCR. Wyodrębnij tekst z plików PDF bez wysiłku. Pobierz teraz, aby zapewnić bezproblemową integrację. ### [Rozpoznaj tabelę w rozpoznawaniu obrazu OCR](./recognize-table/) Odblokuj potencjał Aspose.OCR dla .NET dzięki naszemu obszernemu przewodnikowi na temat rozpoznawania tabel w rozpoznawaniu obrazów OCR. +### [Wykonaj OCR na obrazie przy użyciu Aspose OCR – Przewodnik w języku hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Dowiedz się, jak wykonać OCR na obrazie przy użyciu Aspose OCR, korzystając z przewodnika w języku hindi. +### [Wykonaj OCR na pliku PDF przy użyciu Aspose.OCR – Kompletny przewodnik C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Poznaj kompletny przewodnik C# do wykonywania OCR na plikach PDF przy użyciu Aspose.OCR, krok po kroku. +### [Jak używać Aspose: konwersja obrazu do HTML z OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Dowiedz się, jak przy pomocy Aspose.OCR zamienić obrazy na pliki HTML, zachowując rozpoznany tekst. +### [Wykonaj OCR na obrazie i wykryj błędnie napisane słowa w C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Dowiedz się, jak przy użyciu Aspose.OCR w C# wykonać OCR na obrazie i wykrywać błędnie napisane słowa, zwiększając jakość tekstu. +### [OCR napisów wideo w C# – Kompletny przewodnik](./video-subtitle-ocr-in-c-complete-guide/) +Dowiedz się, jak używać Aspose.OCR w C# do rozpoznawania i konwertowania napisów wideo. Kompletny przewodnik krok po kroku. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/polish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..450c52de4 --- /dev/null +++ b/ocr/polish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,263 @@ +--- +category: general +date: 2026-06-03 +description: Jak używać Aspose do konwertowania obrazu na HTML i wyodrębniania tekstu + z obrazu w C#. Dowiedz się, jak szybko generować HTML z obrazu i wykonywać OCR obrazu + do HTML. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: pl +og_description: Jak używać Aspose do konwertowania obrazu na HTML, wyodrębniania tekstu + z obrazu i generowania HTML z obrazu przy użyciu OCR w C#. Zapoznaj się z tym kompletnym + przewodnikiem. +og_title: 'Jak używać Aspose: konwertuj obraz do HTML przy użyciu OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Jak używać Aspose: konwertuj obraz na HTML z OCR' +url: /pl/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak używać Aspose: konwertować obraz na HTML z OCR + +Zastanawiałeś się kiedyś **jak używać Aspose**, aby przekształcić zeskanowany obraz w schludny HTML? Może masz stronę z czasopisma, paragon lub odręczną notatkę i potrzebujesz zachować tekst oraz układ dla publikacji w sieci. Dobrą wiadomością jest to, że nie musisz pisać własnego parsera ani zmagać się z niskopoziomowym przetwarzaniem obrazu — Aspose.OCR wykona ciężką pracę za Ciebie. + +W tym samouczku przeprowadzimy Cię przez **kompletny, gotowy do uruchomienia przykład**, który pokaże, jak **convert image to HTML**, **extract text from image** i **generate HTML from image** przy użyciu biblioteki Aspose OCR w C#. Po zakończeniu będziesz mieć małą aplikację konsolową, która generuje plik HTML z zachowanym oryginalnym układem strony, gotowy do wstawienia na dowolną witrynę. + +## Wymagania wstępne + +- **.NET 6.0 SDK** lub nowszy (kod działa zarówno z .NET Core, jak i .NET Framework). +- **Visual Studio 2022** (lub dowolny edytor, którego używasz). +- **Aspose.OCR for .NET** – zainstaluj przez NuGet: `dotnet add package Aspose.OCR`. +- Plik obrazu (JPEG/PNG), który chcesz przekształcić, np. `magazine_page.jpg`. + +Nie są potrzebne żadne dodatkowe pliki konfiguracyjne; biblioteka dostarcza wszystko, co niezbędne do OCR i generowania układu HTML. + +## Krok 1: Utwórz projekt i dodaj Aspose.OCR + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Jeśli używasz Visual Studio, po prostu kliknij prawym przyciskiem myszy projekt → *Manage NuGet Packages* → wyszukaj **Aspose.OCR** i zainstaluj go. Ten krok zapewnia, że możesz **ocr image to html** bez brakujących referencji. + +## Krok 2: Zainicjalizuj silnik OCR + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Tutaj tworzymy instancję `OcrEngine`. Nie musisz podawać żadnych poświadczeń w wersji darmowej; biblioteka użyje wbudowanych modeli rozpoznawania. + +## Krok 3: Załaduj źródłowy obraz + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Zastąp `YOUR_DIRECTORY` absolutną lub względną ścieżką, w której znajduje się Twój obraz. Jeśli plik znajduje się w tym samym folderze co wykonywalny, możesz po prostu użyć `"magazine_page.jpg"`. + +## Krok 4: Rozpoznaj i żądaj HTML z układem + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Właściwość `recognitionResult.Text` zawiera teraz pełny dokument HTML. Gdybyś potrzebował tylko zwykłego tekstu, możesz użyć `OutputFormat.Text`, ale skupiamy się na **convert image to html** z zachowaniem dokładności układu. + +## Krok 5: Zapisz plik HTML + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Uruchomienie programu wygeneruje `magazine.html`. Otwórz go, a zobaczysz tekst pierwotnej strony rozmieszczony dokładnie tak, jak w obrazie źródłowym — idealny do archiwizacji lub publikacji w sieci. + +## Pełny działający przykład + +Poniżej znajduje się **kompletny, gotowy do skopiowania** program. Żadne fragmenty nie zostały pominięte, więc możesz go skompilować i uruchomić od razu po ustawieniu właściwych ścieżek. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Oczekiwany wynik + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Dokładne atrybuty `style` będą się różnić w zależności od oryginalnego obrazu, ale struktura gwarantuje, że **extract text from image** i **generate html from image** odbywają się w jednym, płynnym kroku. + +## Częste pytania i przypadki brzegowe + +### Co zrobić, gdy obraz ma niską rozdzielczość? + +Aspose.OCR działa najlepiej z obrazami o rozdzielczości co najmniej **300 DPI**. Jeśli plik jest rozmyty, spróbuj wstępnie przetworzyć go przy użyciu biblioteki do ulepszania obrazu (np. ImageSharp) przed przekazaniem do silnika OCR. Niska jakość może wpływać zarówno na dokładność **extract text from image**, jak i na wierność wygenerowanego układu HTML. + +### Czy mogę kontrolować język OCR? + +Tak. Ustaw właściwość `Language` w obiekcie `OcrEngine` przed wywołaniem `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +### Jak uzyskać zwykły tekst zamiast HTML? + +Jeśli potrzebujesz tylko surowego ciągu znaków, zamień `OutputFormat.HtmlWithLayout` na `OutputFormat.Text`. Wtedy `recognitionResult.Text` będzie zawierał jedynie wyodrębnione znaki. + +### Czy istnieje sposób na osadzenie obrazów w wygenerowanym HTML? + +Aspose.OCR może osadzić oryginalny obraz jako URI danych base‑64, gdy użyjesz `OutputFormat.HtmlWithLayoutAndImages`. Jest to przydatne, gdy chcesz mieć pojedynczy plik HTML bez zewnętrznych zasobów. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Jak obsłużyć duże partie? + +Do przetwarzania wsadowego, otocz logikę pętlą `foreach` po liście ścieżek do plików. Ponowne użycie tej samej instancji `OcrEngine` zmniejsza narzut i przyspiesza **convert image to html** pipeline. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Wskazówki dotyczące kodu gotowego do produkcji + +- **Dispose resources**: Both `OcrEngine` and `OcrImage` implement `IDisposable`. Wrap them in `using` statements to free native memory promptly. +- **Error handling**: Catch `IOException` for file‑related issues and `OcrException` for recognition problems. +- **Performance**: If you process many images, consider enabling **parallelism** (`Parallel.ForEach`) but be mindful of CPU usage—OCR is CPU‑intensive. +- **Logging**: Integrate a logger (e.g., Serilog) to capture OCR confidence scores (`recognitionResult.Confidence`) for quality monitoring. + +## Zakończenie + +Właśnie omówiliśmy **how to use Aspose** do **convert image to HTML**, **extract text from image** i **generate HTML from image** w kilku prostych krokach. Pełny przykład kodu pokazuje, jak **ocr image to html** zachowując układ, co stanowi solidną podstawę dla każdego projektu digitalizacji dokumentów. + +Od tego momentu możesz: + +- Eksperymentować z różnymi opcjami `OutputFormat`, aby dopasować je do swoich potrzeb. +- Połączyć wygenerowany HTML z frameworkiem CSS dla responsywnego stylowania. +- Przekazać wyodrębniony tekst do indeksu wyszukiwania lub pipeline’u uczenia maszynowego. + +Spróbuj, dostosuj ustawienia i zobacz, jak bez wysiłku Aspose zamienia obrazy w treść gotową do publikacji w sieci. Jeśli napotkasz problemy, zostaw komentarz — miłego kodowania! + +![Diagram przedstawiający przepływ OCR od obrazu do układu HTML – jak używać Aspose](/images/ocr-pipeline.png "jak używać aspose") + +--- + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki dotyczą ściśle powiązanych tematów, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z krok po kroku wyjaśnieniami, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Wyodrębnij tekst z obrazu C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Konwertuj obraz na tekst – wykonaj OCR na obrazie z URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/polish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..57d9a22a3 --- /dev/null +++ b/ocr/polish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-03 +description: Wykonaj OCR na obrazie i wyodrębnij tekst z obrazu przy użyciu Aspose.OCR. + Dowiedz się, jak wykrywać błędnie napisane słowa i uzyskać sugestie ortograficzne + w jednym demo w C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: pl +og_description: Przeprowadź OCR na obrazie, aby wyodrębnić z niego tekst, a następnie + wykryj błędnie napisane słowa i uzyskaj sugestie poprawek ortograficznych przy użyciu + Aspose.OCR w C#. +og_title: Wykonaj OCR na obrazie i wykryj błędnie napisane słowa w C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Wykonaj OCR na obrazie i wykryj błędnie napisane słowa w C# +url: /pl/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wykonaj OCR na obrazie i wykryj błędnie napisane słowa w C# + +Zastanawiałeś się kiedyś, jak **wykonać OCR na plikach obrazu** bez wpadania w szał? Nie jesteś sam. Niezależnie od tego, czy digitalizujesz stare listy, skanujesz paragony, czy budujesz inteligentny przepływ dokumentów, wyodrębnienie czystego tekstu ze zdjęć to pierwszy krok. Dobra wiadomość? Dzięki Aspose.OCR możesz uruchomić rozwiązanie w kilka minut, a dodatkowo możesz **wykrywać błędnie napisane słowa** i **uzyskiwać sugestie ortograficzne** w tym samym przebiegu. + +W tym samouczku przeprowadzimy Cię przez kompletną, gotową do uruchomienia aplikację konsolową w C#, która **wyodrębnia tekst z obrazu**, uruchamia angielski sprawdzacz pisowni i wypisuje każdy błąd wraz z przydatnymi propozycjami poprawek. Po zakończeniu będziesz dokładnie wiedział **jak wyodrębnić tekst**, jak podłączyć API sprawdzania pisowni oraz jak wygląda oczekiwany wynik w konsoli. + +## Co zbudujesz + +- Załadujesz bitmapę (lub PNG) zawierającą błędy typograficzne. +- Uruchomisz Aspose.OCR, aby **wykonać OCR na obrazie** i uzyskać surowe dane tekstowe. +- Zainicjujesz wbudowany angielski sprawdzacz pisowni. +- **Wykryjesz błędnie napisane słowa** i **uzyskasz sugestie ortograficzne** dla każdego z nich. +- Wydrukujesz schludny raport w konsoli. + +Bez zewnętrznych usług, bez skomplikowanych wywołań HTTP — tylko jeden pakiet NuGet i kilka linii kodu. + +## Wymagania wstępne + +- .NET 6.0 SDK lub nowszy (kod działa również na .NET Framework 4.7+). +- Visual Studio 2022 (lub dowolny ulubiony edytor). +- Pakiet NuGet Aspose.OCR for .NET (`Aspose.OCR`). +- Plik obrazu (`letter_with_typos.png`) umieszczony w miejscu, które możesz odwołać w projekcie. + +Jeśli nigdy wcześniej nie używałeś Aspose, nie martw się — instalacja pakietu jest tak prosta, jak uruchomienie: + +```bash +dotnet add package Aspose.OCR +``` + +Teraz zanurzmy się w implementację. + +## Krok 1: Utwórz projekt i zainstaluj Aspose.OCR + +Utwórz nowy projekt konsolowy i pobierz bibliotekę OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Po zakończeniu przywracania otwórz `Program.cs`. Zastąpimy domyślną zawartość pełnym kodem demonstracyjnym później, ale najpierw wyjaśnimy, dlaczego każdy namespace ma znaczenie. + +- `Aspose.OCR` – rdzeń silnika OCR i obsługa obrazów. +- `Aspose.OCR.SpellCheck` – narzędzia sprawdzania pisowni dostarczane wraz z biblioteką. +- `System` – standardowe klasy bazowe .NET (np. `Console`). + +## Krok 2: Załaduj obraz i wykonaj OCR na obrazie + +Pierwsze prawdziwe działanie to przekazanie obrazu do silnika OCR. Aspose.OCR odczytuje wiele formatów (PNG, JPEG, TIFF). Oto fragment, który wykonuje najcięższą pracę: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Dlaczego to ważne:** `OcrImage.FromFile` ukrywa szczegóły na poziomie pikseli, podczas gdy `OcrEngine.Recognize` uruchamia wytrenowany model neuronowy, który przetwarza wizualne glify na znaki Unicode. Właściwość `ocrResult.Text` zawiera teraz surowy ciąg znaków — dokładnie to, czego potrzebujesz, aby **wyodrębnić tekst z obrazu**. + +> **Pro tip:** Jeśli Twój obraz zawiera wiele języków, możesz ustawić `ocrEngine.Language = OcrLanguage.Multilingual;` przed wywołaniem `Recognize`. + +## Krok 3: Zainicjuj angielski sprawdzacz pisowni + +Aspose.OCR dostarcza wbudowany silnik sprawdzania pisowni, który rozumie angielski od razu po instalacji. Inicjalizacja to jednowierszowy kod: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Dlaczego ten krok jest kluczowy:** Wynik OCR może zawierać błędnie rozpoznane znaki (np. „l” zamiast „1”) lub rzeczywiste literówki w źródłowym dokumencie. Sprawdzacz pisowni przeskanuje ciąg, znajdzie podejrzane tokeny i zasugeruje alternatywy. + +## Krok 4: Wykryj błędnie napisane słowa i uzyskaj sugestie ortograficzne + +Teraz przekazujemy tekst OCR do sprawdzacza: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` to kolekcja, w której każdy element zawiera niepoprawne słowo oraz tablicę możliwych poprawek. + +## Krok 5: Wyświetl wyniki + +Na koniec iterujemy po kolekcji i wypisujemy raport przyjazny dla człowieka: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Oczekiwany wynik w konsoli + +Zakładając, że `letter_with_typos.png` zawiera zdanie: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Uruchomienie demonstracji wygeneruje coś w stylu: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Zauważ, że każda literówka jest sparowana z kilkoma prawdopodobnymi poprawkami — dokładnie to, czego potrzebujesz przy budowie przyjaznego interfejsu korekty. + +## Pełny działający przykład + +Poniżej znajduje się **kompletny, gotowy do skopiowania** program. Zamień `YOUR_DIRECTORY` na rzeczywistą ścieżkę do pliku obrazu. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Przypadki brzegowe do rozważenia** +> - **Pusty obraz:** Jeśli silnik OCR zwróci pusty ciąg, `spellChecker.Check` po prostu zwróci pustą kolekcję — bez awarii. +> - **Tekst nie‑angielski:** Zamień `OcrLanguage.English` na `OcrLanguage.French` (lub dowolny obsługiwany język), aby **wykrywać błędnie napisane słowa** w innych językach. +> - **Duże dokumenty:** W przypadku wielostronicowych PDF‑ów, należy iterować po każdej stronie, wykonać OCR, a następnie zagregować wyniki przed sprawdzeniem pisowni. + +## Przegląd wizualny (tekst alternatywny obrazu) + +![Diagram przedstawiający przepływ wykonania OCR na obrazie, wyodrębniania tekstu z obrazu oraz wykrywania błędnie napisanych słów wraz z sugestiami ortograficznymi](perform-ocr-on-image-flow.png) + +*Diagram powyżej ilustruje pełny pipeline: obraz → silnik OCR → surowy tekst → sprawdzacz pisowni → sugestie.* + +## Często zadawane pytania i pro tipy + +| Pytanie | Odpowiedź | +|----------|-----------| +| **Czy potrzebuję połączenia z internetem?** | Nie. Aspose.OCR działa w pełni lokalnie; idealne do środowisk offline lub o wysokich wymaganiach bezpieczeństwa. | +| **Jak dokładny jest sprawdzacz pisowni?** | Korzysta ze słownika liczącego ~150 tys. angielskich słów oraz dopasowywania rozmytego, więc większość typowych literówek zostaje wykryta. | +| **Czy mogę dostosować słownik?** | Tak. `SpellChecker.AddUserDictionary("custom.txt")` pozwala wczytać terminy specyficzne dla domeny (np. nazwy produktów). | +| **Co jeśli obraz jest przekrzywiony?** | Silnik OCR automatycznie wykrywa orientację, ale w trudnych przypadkach możesz ręcznie wywołać `ocrEngine.ImagePreprocessing.Rotate(angle)`. | +| **Czy istnieje sposób na podświetlenie sugestii w UI?** | Po uzyskaniu kolekcji `misspellings` możesz odwzorować każde `entry.Word` na pozycję w `ocrResult.Text` i podkreślić je w RichTextBoxie lub widoku webowym. | + +## Zakończenie + +Pokazaliśmy Ci **jak wykonać OCR na obrazie**, **wyodrębnić tekst z obrazu**, a następnie **wykrywać błędnie napisane słowa** i **uzyskiwać sugestie ortograficzne** — wszystko w zwięzłej aplikacji konsolowej C#. Główna idea jest prosta: pozwól Aspose.OCR wykonać ciężką pracę rozpoznawania znaków, a wbudowanemu sprawdzaczowi pisowni oczyścić wynik. Od tego punktu możesz rozbudować demo do pełnoprawnej usługi przetwarzania dokumentów, zintegrować je z API webowym lub podłączyć do edytora desktopowego. + +Gotowy na kolejny krok? Spróbuj zmienić język na hiszpański, przetworzyć wielostronicowy PDF lub zbudować mały interfejs WPF, który pozwoli użytkownikom kliknąć słowo i zaakceptować sugestię. Bloki konstrukcyjne są już na miejscu — wystarczy eksperymentować. + +Jeśli napotkasz problemy lub masz pomysły na rozszerzenia, zostaw komentarz poniżej. Szczęśliwego kodowania! + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne, działające przykłady kodu oraz szczegółowe wyjaśnienia, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Wyodrębnianie tekstu z obrazu w C# z wyborem języka przy użyciu Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Wyodrębnianie tekstu z obrazu przy użyciu Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Optymalizacja OCR obrazu przy użyciu Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/polish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..6ef5db46c --- /dev/null +++ b/ocr/polish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: Wykonaj OCR obrazu przy użyciu Aspose OCR w C#. Dowiedz się, jak wczytać + obraz do OCR i wyodrębnić tekst w języku hindi z obrazu offline, krok po kroku z + kodem. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: pl +og_description: Wykonaj OCR na obrazie przy użyciu Aspose OCR w C#. Ten tutorial pokazuje, + jak załadować obraz do OCR i wyodrębnić tekst w języku hindi z obrazu offline, wraz + z gotowym kodem do uruchomienia. +og_title: Wykonaj OCR na obrazie – Przewodnik Aspose OCR w języku hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Wykonaj OCR na obrazie przy użyciu Aspose OCR – Przewodnik w języku hindi +url: /pl/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wykonaj OCR na obrazie przy użyciu Aspose OCR – Przewodnik po języku hindi + +Kiedykolwiek potrzebowałeś **wykonać OCR na obrazie** plików, ale nie wiedziałeś, jak uzyskać z nich znaki hindi? Nie jesteś sam — wielu programistów napotyka ten problem, gdy po raz pierwszy próbują odczytać skrypty niełacińskie. Dobrą wiadomością jest to, że Aspose OCR czyni to dość prostym i możesz to zrobić całkowicie offline. + +W tym przewodniku **wczytamy obraz do OCR**, wskażemy silnik na Twoje lokalne pakiety językowe i w końcu **wyodrębnimy dane obrazu tekstu w języku hindi** bez konieczności korzystania z internetu. Po zakończeniu będziesz mieć gotową aplikację konsolową C#, która odczytuje hinduski paragon i wypisuje tekst w konsoli. + +## Czego będziesz potrzebować + +- **.NET 6.0** lub nowszy (kod działa również na .NET Framework 4.7+) +- **Aspose.OCR for .NET** pakiet NuGet + `dotnet add package Aspose.OCR` +- Folder zawierający **offline Hindi language resources** (pobierz z portalu Aspose) +- Plik obrazu z tekstem w języku hindi, np. `receipt_hindi.png` + +To wszystko — żadnych zewnętrznych usług, kluczy API, po prostu prosty kod. + +## Wykonaj OCR na obrazie – Implementacja krok po kroku + +Poniżej dzielimy proces na siedem przejrzystych kroków. Każdy krok wyjaśnia **dlaczego** jest istotny, a nie tylko **co** wpisać. + +### Krok 1: Utwórz instancję silnika OCR + +Silnik jest sercem Aspose OCR. Utworzenie jego instancji daje dostęp do wszystkich ustawień, które będziesz modyfikować później. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Dlaczego?** +> Bez `OcrEngine` nie masz obiektu, na którym można wywołać `Recognize`. Traktuj go jak „kamerę”, która później zeskanuje Twój obraz. + +### Krok 2: Wskaż silnik na zasoby offline + +Aspose dostarcza pakiety językowe, które możesz przechowywać lokalnie. Ustawienie `ResourcesFolder` informuje silnik, gdzie szukać. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Wskazówka:** +> Używaj ścieżki bezwzględnej podczas rozwoju, a następnie przełącz się na ścieżkę względną lub ustawienie konfiguracyjne w produkcji. + +### Krok 3: Wymuś tryb offline + +Możesz się zastanawiać: „Czy naprawdę muszę wyłączyć wyszukiwanie online?” Jeśli pracujesz za zaporą lub po prostu chcesz deterministycznych wyników, ustaw `UseOfflineResources` na `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> Pozostawienie tej flagi jako `false` może spowodować, że silnik pobierze dodatkowe dane, co zwiększa opóźnienie i może naruszyć polityki bezpieczeństwa. + +### Krok 4: Wybierz hindi jako język rozpoznawania + +Tutaj **wyodrębniamy obraz tekstu w języku hindi**, informując silnik, jakiego języka się spodziewać. To znacząco poprawia dokładność. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Dlaczego to pomaga:** +> Silniki OCR używają modeli znaków specyficznych dla języka. Blokując się na hindi, unikasz zgadywania przez silnik spośród dziesiątek skryptów. + +### Krok 5: Wczytaj obraz do OCR + +Teraz faktycznie **wczytujemy obraz do OCR**. Metoda `OcrImage.FromFile` odczytuje bitmapę w formacie, który rozumie silnik. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Typowy problem:** +> Podanie ścieżki z ukośnikami (/) w Windows działa, ale użycie `Path.Combine` sprawia, że kod jest niezależny od platformy. + +### Krok 6: Uruchom rozpoznawanie + +Po skonfigurowaniu wszystkiego, w końcu **wykonujemy OCR na obrazie**, wywołując `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Co się dzieje?** Silnik skanuje każdy piksel, dopasowuje wzorce do bazy glifów hindi i tworzy ciąg znaków Unicode. + +### Krok 7: Wyświetl rozpoznany tekst + +Obiekt wyniku zawiera właściwość `Text`, w której znajduje się wyodrębniony ciąg. Po prostu wypisujemy go w konsoli. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Oczekiwany wynik:** +> Jeśli `receipt_hindi.png` zawiera „भुगतान सफल”, konsola wydrukuje dokładnie tę linię, zachowując znaki diakrytyczne. + +## Wczytaj obraz do OCR – Przygotowanie zasobu + +Jeśli zastanawiasz się, czy możesz podać silnikowi strumień zamiast pliku, odpowiedź brzmi tak. Zastąp `OcrImage.FromFile` przez: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Dlaczego używać strumienia?** +> Strumienie pozwalają pracować z obrazami przechowywanymi w bazach danych, chmurze (blobach) lub zasobach osadzonych — idealne dla skalowalnych usług. + +## Wyodrębnij obraz tekstu w języku hindi – Obsługa przypadków brzegowych + +1. **Brak pakietu językowego** – Jeśli pakiet hindi nie zostanie znaleziony, `Recognize` zgłasza wyjątek. Owiń wywołanie w try/catch i zaloguj przyjazny komunikat. +2. **Obrazy o niskiej rozdzielczości** – Dokładność OCR spada poniżej 300 dpi. Przetwórz obraz (zmień rozmiar, wyostrz) przed wczytaniem. +3. **Dokumenty wielojęzykowe** – Możesz włączyć wiele języków: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Te poprawki zapewniają, że Twoja procedura **perform OCR on image** pozostaje solidna w środowisku produkcyjnym. + +## Uruchomienie pełnego przykładu + +Zapisz poniższy plik jako `Program.cs`, zamień ścieżki zastępcze i uruchom: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Po wykonaniu `dotnet run` powinieneś zobaczyć coś podobnego do: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Jeśli otrzymasz pusty ciąg, sprawdź ponownie, czy **ResourcesFolder** wskazuje na folder zawierający `Hindi.traineddata` oraz czy obraz jest wystarczająco wyraźny. + +## Podsumowanie + +Przeprowadziliśmy Cię przez proces **perform OCR on image** plików przy użyciu Aspose OCR, obejmując wszystko od **load image for OCR** po **extract Hindi text image** w całkowicie offline scenariuszu. Pełny, uruchamialny kod powyżej zapewnia solidną bazę, a wskazówki dotyczące strumieni, obsługi błędów i wsparcia wielojęzycznego pomogą dostosować rozwiązanie do projektów w rzeczywistym świecie. + +Gotowy na kolejny krok? Spróbuj przełączyć język na **OcrLanguage.Tamil** lub podawać obrazy z magazynu Azure Blob. Możesz także eksperymentować z ustawieniami `ImagePreprocessing`, aby zwiększyć dokładność przy szumnych paragonach. + +Masz pytania lub napotkałeś problem? zostaw komentarz — miłego kodowania! + +![Perform OCR on image example + + +## Co powinieneś nauczyć się dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Wyodrębnij tekst z obrazu 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/) +- [Wyodrębnij tekst z obrazu – optymalizacja OCR przy użyciu Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/polish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..54c392504 --- /dev/null +++ b/ocr/polish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-03 +description: Wykonaj OCR na pliku PDF i przekształć zeskanowany PDF w przeszukiwalny + PDF przy użyciu Aspose.OCR. Dowiedz się, jak rozpoznawać tekst z PDF i tworzyć przeszukiwalne + PDF‑y w kilka minut. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: pl +og_description: Wykonaj OCR na pliku PDF i natychmiast utwórz przeszukiwalny PDF. + Ten samouczek pokazuje krok po kroku, jak rozpoznać tekst z PDF przy użyciu Aspose.OCR. +og_title: Wykonaj OCR na PDF – Kompletny przewodnik C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Wykonaj OCR na PDF za pomocą Aspose.OCR – Kompletny przewodnik C# +url: /pl/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wykonaj OCR na PDF przy użyciu Aspose.OCR – Kompletny przewodnik C# + +Zastanawiałeś się kiedyś **jak wykonać OCR na plikach PDF** bez walki z dziesiątkami narzędzi wiersza poleceń? Nie jesteś sam. Niezależnie od tego, czy digitalizujesz faktury, archiwizujesz stare raporty, czy po prostu potrzebujesz przeszukiwalnej wersji zeskanowanego kontraktu, przekształcenie statycznego PDF‑a w coś, co naprawdę można przeszukiwać, to prawdziwa rewolucja. + +W tym przewodniku przejdziemy krok po kroku **jak utworzyć przeszukiwalne pliki PDF** ze zeskanowanych PDF‑ów (a nawet zwykłych obrazów) przy użyciu Aspose.OCR dla .NET. Po zakończeniu będziesz w stanie **rozpoznać tekst z PDF** za pomocą kilku linii kodu C#, a także zrozumiesz, dlaczego każdy krok jest potrzebny, abyś mógł dostosować rozwiązanie do własnych projektów. + +> **Szybka informacja:** Cały proces sprowadza się do trzech rzeczy — zainicjowania silnika OCR, podania mu źródła (PDF lub obrazu) oraz zapisania wyniku jako przeszukiwalnego PDF. Zanurzmy się. + +--- + +## Czego będziesz potrzebować + +Zanim zaczniemy, upewnij się, że masz: + +| Wymaganie wstępne | Dlaczego jest to ważne | +|-------------------|------------------------| +| **.NET 6.0+** (lub .NET Framework 4.6+) | Aspose.OCR celuje w nowoczesne środowiska uruchomieniowe; starsze wersje mogą nie mieć najnowszych API. | +| **Aspose.OCR for .NET** pakiet NuGet | Dostarcza klasę `OcrEngine` oraz narzędzia do obsługi PDF. | +| **Ważna licencja Aspose** (lub wersja ewaluacyjna) | Bez licencji napotkasz 30‑dniowy limit wersji próbnej i znaki wodne. | +| **Zeskanowany PDF** (lub plik obrazu), który chcesz uczynić przeszukiwalnym | To dokument źródłowy dla OCR. | +| **Visual Studio 2022** (lub dowolny edytor C#) | Ułatwia debugowanie, ale każdy IDE się sprawdzi. | + +Możesz zainstalować bibliotekę przy pomocy następującego polecenia NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Jeśli pracujesz w potoku CI, dodaj plik licencji do artefaktów builda i wczytuj go w czasie działania, aby uniknąć twardego kodowania ścieżek. + +--- + +## Wykonaj OCR na PDF – Konfiguracja Aspose.OCR + +Pierwszą rzeczą, której potrzebujemy, jest świeża instancja `OcrEngine`. Pomyśl o niej jak o mózgu, który będzie czytał Twój dokument. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Dlaczego nowa instancja za każdym razem? Silnik przechowuje konfigurację (np. ustawienia języka), które mogą się różnić w zależności od dokumentu. Tworzenie nowej instancji przy każdym uruchomieniu zapewnia czysty start i zapobiega mieszaniu się ustawień między zadaniami. + +--- + +## Jak utworzyć przeszukiwalny PDF – Konfiguracja haseł (opcjonalnie) + +Jeśli Twój PDF jest zabezpieczony, musisz podać silnikowi hasło, zanim będzie mógł odczytać strony: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Pominięcie tego kroku w zabezpieczonym pliku spowoduje wyrzucenie `PdfPasswordException`. Zawsze otaczaj to blokiem try‑catch, jeśli nie jesteś pewien statusu ochrony. + +--- + +## Konwersja zeskanowanego PDF do przeszukiwalnego PDF – Ładowanie źródła + +Aspose.OCR pracuje z abstrakcją `OcrImage`, która może opakowywać PDF‑y, TIFF‑y, JPEG‑y itp. Oto jak wczytać zeskanowany PDF do pamięci: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +W tle, metoda `FromFile` parsuje każdą stronę na obrazy rastrowe, które silnik OCR może przetworzyć. Jeśli masz wielostronicowy PDF, silnik automatycznie przeiteruje wszystkie strony. + +--- + +## Rozpoznawanie tekstu z PDF – Wykonywanie OCR + +Teraz serce tutorialu: poproś silnik o rozpoznanie tekstu i wyjście jako przeszukiwalny PDF. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` instruuje silnik, aby osadził niewidoczną warstwę tekstową na oryginalnych zeskanowanych obrazach. Wynikowy PDF zachowuje wizualną wierność skanu, a jednocześnie staje się w pełni przeszukiwalny — dokładnie to, czego potrzebujesz przy audytach zgodności. + +--- + +## Konwersja obrazu do przeszukiwalnego PDF – Zapis wyniku + +Na koniec zapisz dane binarne na dysk: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Właściwość `Binary` zawiera surowe bajty PDF. Możesz także przesłać je bezpośrednio w odpowiedzi HTTP, jeśli tworzysz API. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*Tekst alternatywny obrazu: Diagram przepływu OCR ilustrujący, jak zeskanowany PDF jest przekształcany w przeszukiwalny PDF.* + +--- + +## Przypadki brzegowe i praktyczne wskazówki + +### 1. Duże pliki i zarządzanie pamięcią +Jeśli przetwarzasz PDF‑y większe niż 100 MB, rozważ użycie `OcrEngineSettings.MemoryLimit`, aby ograniczyć zużycie pamięci. Dodatkowo, przetwarzaj strony w partiach, aby uniknąć `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Obsługa języków +Domyślnie Aspose.OCR zakłada język angielski. Aby rozpoznać inne języki, ustaw właściwość `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Scenariusze wielowątkowe +`OcrEngine` **nie** jest bezpieczny wątkowo. Jeśli potrzebujesz równoległego przetwarzania, utwórz osobny silnik dla każdego wątku. + +### 4. Debugowanie dokładności OCR +Możesz wyodrębnić czysty tekst z `ocrResult` w celu debugowania: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Jeśli wynik wygląda na zniekształcony, eksperymentuj z `PreprocessSettings` (np. deskew, despeckle), aby poprawić jakość. + +### 5. Pułapki licencyjne +Gdy uruchamiasz wersję ewaluacyjną, Aspose dodaje znak wodny do wyjściowego PDF. Zarejestruj licencję wcześnie w aplikacji: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Pełny działający przykład – od początku do końca + +Poniżej znajduje się kompletny, gotowy do uruchomienia program, który zawiera wszystkie powyższe wskazówki. Śmiało skopiuj i wklej go do nowego projektu konsolowego. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Oczekiwany wynik:** Po uruchomieniu zobaczysz w konsoli komunikat potwierdzający lokalizację pliku. Otwórz `output.pdf` w dowolnym przeglądarce PDF; spróbuj wpisać słowo, które wiesz, że występuje w oryginalnym skanie. Jeśli tekst zostanie podświetlony, udało Ci się **wykonać OCR na PDF** i stworzyć przeszukiwalny dokument. + +--- + +## Najczęściej zadawane pytania + +**P: Czy mogę użyć tego do konwersji pojedynczego obrazu (PNG/JPEG) na przeszukiwalny PDF?** +O: Oczywiście. Zastąp `OcrImage.FromFile("input.pdf")` ścieżką do pliku obrazu. Silnik rasteryzuje obraz i osadza warstwę OCR w taki sam sposób. + +**P: Co jeśli mój PDF zawiera zarówno zeskanowane strony, jak i natywny tekst?** +O: Silnik nałoży warstwę OCR na istniejącą zawartość, więc natywny tekst pozostanie wybieralny, a zeskanowane strony staną się przeszukiwalne. + +**P: Jak dokładny jest OCR?** +O: Dokładność zależy od jakości źródła. Czyste, wysokiej rozdzielczości skany (>300 dpi) dają ponad 95 % trafności. W przypadku zaszumionych dokumentów włącz `PreprocessSettings` (deskew, despeckle) przed wywołaniem `Recognize`. + +--- + +## Kolejne kroki – Rozbudowa zestawu narzędzi OCR + +Teraz, gdy potrafisz **rozpoznawać tekst z PDF** i **konwertować zeskanowane PDF‑y na przeszukiwalne PDF‑y**, rozważ następujące tematy: + +- **Przetwarzanie wsadowe**: Iteruj po folderze PDF‑ów i automatycznie generuj przeszukiwalne wersje. +- **Ekstrakcja tekstu**: Użyj `ocrResult.Text`, aby zasilić indeks wyszukiwania (np. Elasticsearch). +- **Niestandardowe pakiety językowe**: Pobierz dodatkowe dane językowe z Aspose, aby obsługiwać skrypty azjatyckie. +- **Zgodność PDF/A**: Połącz Aspose.PDF z wynikiem OCR, aby tworzyć archiwalne PDF‑y spełniające standard PDF/A. + +Każdy z tych punktów bazuje na podstawowych krokach, które omówiliśmy, więc jesteś gotowy, aby rozbudować swoje rozwiązanie. + +--- + +## Podsumowanie + +Pokazaliśmy Ci **jak wykonać OCR na plikach PDF** przy użyciu Aspose.OCR, przekształciliśmy zeskanowane PDF‑y w w pełni przeszukiwalne dokumenty oraz omówiliśmy konwersję zwykłych obrazów do przeszukiwalnych PDF‑ów. Kod + +## Co powinieneś nauczyć się dalej? + +Poniższe tutoriale obejmują tematy ściśle powiązane, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne przykłady kodu oraz szczegółowe wyjaśnienia, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia w własnych projektach. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/polish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..03f72b5f7 --- /dev/null +++ b/ocr/polish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Samouczek OCR napisów wideo pokazujący, jak wyodrębniać klatki z wideo + i odczytywać tekst z plików wideo, takich jak MP4, przy użyciu Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: pl +og_description: Poznaj OCR napisów wideo z Aspose.OCR. Wyodrębnij klatki z wideo, + odczytaj tekst z wideo i wyodrębnij tekst z pliku MP4 w kilka minut. +og_title: OCR napisów wideo w C# – przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR napisów wideo w C# – Kompletny przewodnik +url: /pl/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR napisów wideo w C# – Kompletny przewodnik + +Kiedykolwiek potrzebowałeś **video subtitle ocr**, ale nie wiedziałeś, od czego zacząć? Nie jesteś sam. Niezależnie od tego, czy digitalizujesz nagrania wykładów, wyciągasz napisy z filmów szkoleniowych, czy po prostu jesteś ciekawy, jak odczytać tekst z wideo, ten samouczek pokaże Ci dokładnie, jak zrobić to w C# i Aspose.OCR. + +W ciągu kilku minut wyodrębnimy klatki z wideo, uruchomimy OCR na tych klatkach i ostatecznie wyświetlimy tekst napisów klatka po klatce. Po zakończeniu będziesz w stanie **read text from video** plików — w tym MP4 — bez poszukiwania narzędzi zewnętrznych. + +## Co zbudujesz + +Stworzymy małą aplikację konsolową, która: + +1. Dekoduje plik MP4 (lub dowolny obsługiwany format) na poszczególne klatki `Bitmap`. +2. Ogranicza region OCR do paska napisów, aby silnik nie rozpraszał się całym obrazem. +3. Przetwarza każdą klatkę przy użyciu `VideoOcrProcessor` firmy Aspose. +4. Wypisuje rozpoznany tekst napisów w konsoli. + +Bez zbędnych dodatków, po prostu działający przykład end‑to‑end, który możesz wstawić do prawdziwego projektu. + +## Wymagania wstępne + +- **.NET 6.0** lub nowszy (kod działa również na .NET Framework 4.7+). +- **Aspose.OCR for .NET** – zainstaluj przez NuGet: `Install-Package Aspose.OCR`. +- Plik wideo (MP4 sprawdza się doskonale). +- Sposób na dekodowanie klatek wideo – demo używa metody zastępczej, ale możesz podłączyć FFmpeg, OpenCV lub dowolną bibliotekę zwracającą obiekty `Bitmap`. + +> Pro tip: Jeśli pracujesz w systemie Windows, pakiet `System.Drawing.Common` działa dobrze dla `Bitmap`. Na Linux/macOS będziesz potrzebował natywnej zależności `libgdiplus`. + +## Krok 1 – Wyodrębnianie klatek z wideo + +Pierwszą przeszkodą jest przekształcenie ruchomego obrazu w obrazy statyczne. Metoda `GetVideoFrames` poniżej jest celowo pusta; zamień ją na swój ulubiony dekoder. Oto szybki szkic przy użyciu FFmpeg‑Core (tylko aby zilustrować strukturę danych): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Dlaczego to ważne:** Wyodrębnianie klatek dostarcza silnikowi OCR statyczny obraz do przetworzenia, co znacząco zwiększa dokładność w porównaniu z próbą odczytu bezpośrednio z strumienia wideo. + +## Krok 2 – Konfiguracja VideoOcrProcessor + +Teraz, gdy mamy sekwencję obiektów `Bitmap`, możemy przekazać je do Aspose.OCR. `VideoOcrProcessor` pozwala zdefiniować **Region of Interest (ROI)** – idealny dla napisów, które zazwyczaj znajdują się na górze lub na dole klatki. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Dlaczego ograniczyć ROI?** Ignorując resztę obrazu, redukujemy szum, skracamy czas przetwarzania i unikamy fałszywych trafień pochodzących z grafiki tła. + +## Krok 3 – Uruchomienie OCR na sekwencji klatek + +Gdy procesor jest gotowy, podawanie klatek to jednowierszowy kod. Metoda `Process` zwraca wyliczalną kolekcję obiektów `OcrResult`, z których każdy zawiera rozpoznany tekst dla odpowiadającej mu klatki. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Co dzieje się pod maską?** Aspose.OCR wewnętrznie normalizuje każdy bitmap, uruchamia rozpoznawanie oparte na sieci neuronowej, a następnie przetwarza wynik, aby poprawić interpunkcję i podziały linii. + +## Krok 4 – Wyświetlanie wyodrębnionego tekstu + +Na koniec iterujemy po wynikach i wypisujemy każdą linię napisu. Możesz także zapisać je do pliku SRT, bazy danych lub przekazać do usługi tłumaczeniowej. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Pełny działający przykład + +Po połączeniu wszystkiego razem otrzymujemy samodzielny program konsolowy: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Oczekiwany wynik (przykład)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Jeśli OCR ma problemy z konkretną klatką, zobaczysz pusty ciąg znaków – to sygnał, aby dostosować ROI lub zwiększyć częstotliwość wyodrębniania klatek. + +## Częste problemy i jak je naprawić + +| Problem | Dlaczego się pojawia | Rozwiązanie | +|-------|----------------|-----| +| **Garbage characters** | Klatki o niskiej rozdzielczości lub silna kompresja | Wyodrębnij klatki przy wyższym bitrate lub zwiększ rozmiar bitmapy przed OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI nie obejmuje rzeczywiście paska napisów | Sprawdź współrzędne prostokąta (użyj narzędzia do zrzutów ekranu, aby zmierzyć). | +| **Performance bottleneck** | Przetwarzanie każdej klatki przy 30 fps jest przesadą | Zredukuj częstotliwość do 1‑2 fps dla większości strumieni napisów; nadal możesz przechwycić każdą zmianę napisu. | +| **FFmpeg not found** | `ffmpeg.exe` nie znajduje się w `PATH` | Podaj pełną ścieżkę w `ProcessStartInfo.FileName` lub zainstaluj FFmpeg globalnie. | + +## Rozszerzanie rozwiązania + +- **Export to SRT** – połącz znaczniki czasu z tekstem OCR i zapisz plik SubRip. +- **Multi‑language support** – ustaw `ocrProcessor.Language = OcrLanguage.Spanish` (lub dowolny obsługiwany język). +- **Real‑time processing** – przekazuj klatki bezpośrednio z transmisji na żywo zamiast odczytywać je z dysku. + +Wszystkie te warianty wciąż opierają się na podstawowych pomysłach **extract frames from video**, **read text from video** i **extract text from mp4**. + +## Podsumowanie + +Właśnie przeszliśmy kompletny przepływ pracy **video subtitle ocr** w C#. Poprzez wyodrębnianie klatek z wideo, skupienie OCR na paśmie napisów i iterowanie po wynikach, możesz niezawodnie **read text from video** plików, takich jak MP4. Kod jest gotowy do skopiowania i wklejenia, a modularna konstrukcja pozwala wymienić dowolny dekoder klatek, którego preferujesz. + +Kolejne kroki? Spróbuj wyeksportować wyniki do pliku SRT, eksperymentuj z różnymi rozmiarami ROI lub przekazuj napisy do API tłumaczeń w celu uzyskania wielojęzycznych napisów. Nie ma granic, gdy opanujesz podstawy wyodrębniania tekstu z wideo. + +Miłego kodowania i niech Twoje napisy zawsze będą krystalicznie czyste! + +## Co powinieneś się nauczyć dalej? + +Poniższe samouczki obejmują ściśle powiązane tematy, które rozwijają techniki przedstawione w tym przewodniku. Każdy zasób zawiera kompletne działające przykłady kodu z wyjaśnieniami krok po kroku, aby pomóc Ci opanować dodatkowe funkcje API i odkrywać alternatywne podejścia implementacyjne w własnych projektach. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/ocr-configuration/_index.md b/ocr/portuguese/net/ocr-configuration/_index.md index 917456822..45368fde0 100644 --- a/ocr/portuguese/net/ocr-configuration/_index.md +++ b/ocr/portuguese/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Desbloqueie o poder do reconhecimento de imagens OCR em .NET com Aspose.OCR. Ext Desbloqueie recursos poderosos de OCR com Aspose.OCR para .NET. Extraia texto de imagens de forma contínua. ### [OCROperation com Lista em Reconhecimento de Imagens OCR](./ocr-operation-with-list/) Desbloqueie o potencial do Aspose.OCR para .NET. Realize reconhecimento de imagens OCR com listas de forma simples. Aumente a produtividade e a extração de dados em suas aplicações. +### [Obtenha a Versão do Aspose OCR em C# – Guia Completo](./get-aspose-ocr-version-in-c-complete-guide/) +Aprenda a recuperar a versão da biblioteca Aspose OCR usando C# com este guia passo a passo. ### Casos de Uso Comuns - **Extrair imagens de texto** de faturas escaneadas para contabilidade automatizada. @@ -102,4 +104,4 @@ A: Sim, o objeto `OcrResult` fornece valores de confiança que podem ser inspeci {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/portuguese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..5bcbe242e --- /dev/null +++ b/ocr/portuguese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: Obtenha a versão do Aspose OCR em C# com um snippet simples. Aprenda + como recuperar a versão da biblioteca Aspose OCR usando OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: pt +og_description: Obtenha a versão do Aspose OCR em C# rapidamente. Este tutorial mostra + exatamente como recuperar a versão da biblioteca Aspose OCR usando OcrEngine GetVersion. +og_title: Obtenha a versão do Aspose OCR em C# – Guia completo +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Obtenha a versão do Aspose OCR em C# – Guia completo +url: /pt/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Obtenha a Versão do Aspose OCR em C# – Guia Completo + +Já se perguntou como **obter a versão do Aspose OCR** dentro do seu projeto .NET? Talvez você esteja resolvendo um conflito de versões, ou simplesmente queira registrar a versão exata da biblioteca que está em produção. Seja qual for o motivo, você chegou ao lugar certo. + +Neste tutorial vamos percorrer um pequeno programa C# autônomo que chama `OcrEngine.GetVersion()` e exibe o resultado. Ao final, você saberá não apenas *como* recuperar a versão, mas também *por que* verificar a versão pode evitar dores de cabeça ao atualizar a **biblioteca Aspose OCR**. + +## O que Você Vai Aprender + +- Adicionar o pacote NuGet Aspose.OCR a um projeto C# +- Usar o método `OcrEngine.GetVersion()` (o ponto de entrada **ocrengine getversion**) +- Tratar possíveis exceções e verificar a saída +- Estender o trecho de código para cenários reais, como logging ou toggles condicionais de recursos + +Nenhuma experiência prévia com OCR é necessária—apenas um entendimento básico de C# e Visual Studio (ou sua IDE favorita). Vamos começar. + +--- + +## Etapa 1: Configurar o Projeto e Importar a Biblioteca Aspose OCR + +Antes de chamar qualquer API relacionada a OCR, você precisa que a **biblioteca Aspose OCR** esteja referenciada no seu projeto. + +1. Abra um terminal ou o Package Manager Console no Visual Studio. +2. Execute o comando a seguir para instalar a versão estável mais recente: + +```bash +dotnet add package Aspose.OCR +``` + +> **Dica:** Se você estiver direcionando o .NET Framework em vez do .NET Core, use a UI do NuGet Package Manager e escolha a versão que corresponde ao seu runtime. O pacote inclui a classe `OcrEngine` que usaremos adiante. + +### Por que isso importa + +Ao instalar o pacote, a versão do assembly no disco pode ser diferente da versão reportada pela biblioteca em tempo de execução. Consultar a versão via código garante que você está lendo a build exata que o CLR carregou, o que é crucial para depuração e auditorias de conformidade. + +--- + +## Etapa 2: Escreva o Código Mínimo para **Obter a Versão do Aspose OCR** + +Crie um novo aplicativo console (`dotnet new console -n OcrVersionDemo`) e substitua o `Program.cs` padrão pelo seguinte: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Explicação de cada parte** + +- `using Aspose.OCR;` traz o namespace OCR para o escopo, permitindo chamar `OcrEngine`. +- `OcrEngine.GetVersion()` é o método estático **ocrengine getversion** que retorna uma string como `"24.5.7"`. +- Envolver a chamada em um bloco `try/catch` protege contra surpresas em tempo de execução—por exemplo, se as bibliotecas nativas não forem encontradas na máquina de destino. +- A string interpolada `$"Aspose OCR version: {version}"` imprime uma linha clara e legível. + +### Saída esperada + +Ao executar `dotnet run` dentro da pasta do projeto, você deverá ver algo semelhante a: + +``` +Aspose OCR version: 24.5.7 +``` + +Se a biblioteca não puder ser carregada, o ramo de erro exibirá uma mensagem concisa, ajudando a identificar o problema rapidamente. + +--- + +## Etapa 3: Verifique se a Versão corresponde ao seu Pacote NuGet + +É fácil assumir que a versão do NuGet que você instalou é a que está sendo usada em tempo de execução, mas peculiaridades do ambiente podem interferir. Para confirmar: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Executar este trecho extra imprimirá algo como: + +``` +Assembly file version: 24.5.7.0 +``` + +Se os dois valores forem diferentes, pode ser que você esteja carregando um DLL mais antigo do Global Assembly Cache (GAC) ou de uma pasta de build anterior. Nesse caso, limpe sua solução (`dotnet clean`) e reconstrua. + +--- + +## Etapa 4: Inclua a Verificação de Versão no Logging de Produção + +A maioria das aplicações reais não se limita a imprimir no console; elas gravam em arquivos de log ou sistemas de telemetria. Aqui está um exemplo rápido usando `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Agora a versão aparece nos seus logs estruturados, facilitando o filtro por `{Version}` posteriormente. Esse padrão é especialmente útil quando você tem vários microsserviços que podem estar usando DLLs OCR diferentes. + +--- + +## Perguntas Frequentes & Casos Limítrofes + +### E se `GetVersion()` retornar uma string vazia? + +Isso geralmente indica uma instalação corrompida ou uma dependência nativa ausente. Reinstale o pacote NuGet e verifique se o `Aspose.OCR.Native.dll` (ou o binário específico da plataforma) está ao lado do seu executável. + +### O método funciona no .NET Core 2.0? + +Sim, **Aspose OCR** suporta .NET Standard 2.0 e superior, portanto qualquer versão do .NET Core que implemente esse padrão pode chamar `OcrEngine.GetVersion()`. Apenas certifique‑se de referenciar os identificadores de runtime corretos (`win-x64`, `linux-x64`, etc.) se estiver publicando um aplicativo autocontido. + +### Posso obter a versão sem um arquivo de licença? + +Absolutamente. `GetVersion()` **não** requer licença; ele apenas relata o número da build da biblioteca. Contudo, se você tentar executar OCR sem uma licença válida, receberá uma exceção em tempo de execução. Por isso o `try/catch` no nosso exemplo é valioso—ele isola a verificação de versão do fluxo de execução do OCR. + +--- + +## Exemplo Completo (Pronto para Copiar‑Colar) + +Abaixo está o programa inteiro, pronto para ser inserido em um novo projeto console. Ele inclui o bloco opcional de logging, permitindo que você veja tanto a saída no console quanto nos logs estruturados. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Execute com `dotnet run` e você verá duas linhas confirmando a versão, além de uma linha de depuração se habilitar `LogLevel.Debug`. + +--- + +## Conclusão + +Cobremos tudo o que você precisa para **obter a versão do Aspose OCR** em um ambiente C#—desde a instalação da **biblioteca Aspose OCR**, chamada ao método **ocrengine getversion**, tratamento de erros, até a incorporação do resultado em logging de nível de produção. Com esse conhecimento, você pode verificar de forma confiável a build exata de OCR que sua aplicação está usando, evitar bugs relacionados a versões e atender a requisitos de conformidade sem esforço. + +Próximos passos? Experimente combinar essa verificação de versão com uma chamada real de OCR (`OcrEngine` → `RecognizeImage`) e registre tanto a versão quanto o resultado do reconhecimento. Você também pode explorar o padrão **retrieve aspose version** para outros produtos Aspose (PDF, Slides, Cells) e manter toda a sua suíte sincronizada. + +Boa codificação, e que seus pipelines de OCR permaneçam afiados! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/portuguese/net/ocr-optimization/_index.md index 7a728f21a..3705e9522 100644 --- a/ocr/portuguese/net/ocr-optimization/_index.md +++ b/ocr/portuguese/net/ocr-optimization/_index.md @@ -28,7 +28,7 @@ Neste guia você descobrirá como **extrair texto de imagem** de arquivos com As - **O .NET Core é suportado?** Totalmente suportado no .NET Framework 4.5+, .NET Core 3.1+, .NET 5/6+. ## O que é “extrair texto de imagem”? -Extrair texto de uma imagem significa usar reconhecimento óptico de caracteres (OCR) para ler os caracteres que aparecem em um bitmap e exportá‑los como texto simples ou documentos formatados. Aspose.OCR utiliza algoritmos sofisticados para lidar com várias fontes, idiomas e qualidades de imagem. +Extrair texto de uma imagem significa usar reconhecimento óptico de caracteres (OCR) para ler os caracteres que aparecem em um bitmap e exportá‑‑los como texto simples ou documentos formatados. Aspose.OCR utiliza algoritmos sofisticados para lidar com várias fontes, idiomas e qualidades de imagem. ## Por que usar Aspose.OCR para .NET? - **Alta precisão** – mecanismos avançados de reconhecimento reduzem erros. @@ -74,6 +74,8 @@ Explore Aspose.OCR para .NET. Aumente a precisão do OCR com filtros de pré‑p Melhore a precisão do OCR com Aspose.OCR para .NET. Corrija ortografia, personalize dicionários e alcance reconhecimento de texto livre de erros sem esforço. ### [Salvar Resultado Multipágina como Documento em Reconhecimento de Imagem OCR](./save-multipage-result-as-document/) Desbloqueie o potencial do Aspose.OCR para .NET. Salve facilmente resultados de OCR multipágina como documentos com este guia completo passo a passo. +### [Exemplo Aspose OCR C# – Ativar GPU, Definir Limite de Memória e Processar Imagens TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Aprenda a habilitar aceleração GPU, limitar uso de memória e processar arquivos TIF com Aspose.OCR em C#. ## Perguntas Frequentes diff --git a/ocr/portuguese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/portuguese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..d39aba6c8 --- /dev/null +++ b/ocr/portuguese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-03 +description: Exemplo Aspose OCR C# que mostra como definir o limite de memória da + GPU, carregar imagem para OCR e reconhecer texto de arquivos TIF com código completo + e dicas. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: pt +og_description: 'Aprenda um exemplo completo de Aspose OCR em C#: habilite a GPU, + defina o limite de memória da GPU, carregue uma imagem para OCR e reconheça texto + de arquivos TIF. Código completo incluído.' +og_title: Exemplo Aspose OCR C# – Aceleração por GPU, Limite de Memória e Processamento + de TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Exemplo Aspose OCR C# – Ativar GPU, Definir Limite de Memória e Processar Imagens + TIF +url: /pt/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Exemplo Aspose OCR C# – Ativar GPU, Definir Limite de Memória e Processar Imagens TIF + +Já se perguntou como extrair o máximo de desempenho do **Aspose OCR C# example** ao lidar com escaneamentos TIFF massivos? Você não está sozinho. Em muitos projetos reais — pense em digitalizar arquivos ou extrair dados de recibos de alta resolução — o gargalo não é o algoritmo de OCR em si, mas a utilização do hardware. + +A verdade é que o Aspose OCR suporta aceleração por GPU, mas você precisa informar exatamente quanta memória ele pode usar, carregar o tipo correto de imagem e, por fim, extrair o texto reconhecido de um arquivo .tif. Este tutorial guia você por cada passo, desde a instalação do SDK até o ajuste das configurações da GPU, para que você possa executar OCR em velocidade impressionante sem estourar a RAM da sua GPU. + +Também incluiremos alguns cenários “e se” — como lidar com TIFFs multipáginas ou reverter para CPU quando não houver GPU — para que você termine com uma solução robusta, não apenas um trecho de código pontual. + +## O que você vai precisar + +Antes de mergulharmos, certifique‑se de que você tem o seguinte na sua máquina: + +| Pré‑requisito | Por que é importante | +|--------------|----------------------| +| **.NET 6 SDK** (ou superior) | O Aspose OCR tem como alvo .NET Standard 2.0+, então qualquer versão recente do .NET funciona. | +| **Pacote NuGet Aspose.OCR** (`Install-Package Aspose.OCR`) | A biblioteca principal que fornece `OcrEngine`, `GpuSettings`, etc. | +| **CUDA 11+** (NVIDIA) **ou ROCm 5+** (AMD) | Necessário para aceleração por GPU; o SDK verificará a presença de um driver compatível em tempo de execução. | +| Uma **GPU com pelo menos 2 GB de VRAM** (vamos limitar a 2048 MB) | Sem memória suficiente, o motor pode reverter silenciosamente para CPU. | +| Uma imagem **TIFF de alta resolução** que você deseja processar | O Aspose OCR consegue ler praticamente qualquer formato raster, mas TIF é comum para escaneamentos. | +| Visual Studio 2022 (ou qualquer editor de sua preferência) | Para compilar e depurar o projeto C#. | + +Se algum desses itens estiver ausente, o código ainda compilará, mas você não verá os ganhos de desempenho que buscamos. + +## Etapa 1: Criar o Motor do Exemplo Aspose OCR C# + +A primeira coisa em todo **Aspose OCR C# example** é instanciar o motor de OCR. Pense no `OcrEngine` como o diretor de um filme — ele coordena tudo, desde o carregamento da imagem até a extração do texto. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Dica de especialista:** Se você pretende processar muitas imagens em sequência, mantenha um único `OcrEngine` ativo. Recriar o motor a cada imagem adiciona overhead que pode superar o tempo de OCR. + +## Etapa 2: Definir Limite de Memória da GPU (e Habilitar Aceleração) + +Agora vem a parte que costuma confundir as pessoas: **definir limite de memória da GPU**. Por padrão, o Aspose OCR tenta usar toda a VRAM disponível, o que em uma estação de trabalho compartilhada pode privar outros aplicativos. O objeto `GpuSettings` permite limitar essa alocação. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Por que definir um limite de memória? + +- **Estabilidade:** Impede travamentos por falta de memória ao processar imagens gigantescas. +- **Co‑existência:** Permite que outros aplicativos pesados em GPU (por exemplo, modelos TensorFlow) rodem lado a lado. +- **Previsibilidade:** Torna os testes de desempenho repetíveis, pois a GPU não começará a fazer swap. + +Se você omitir `MemoryLimitMb`, o Aspose alocará o que considerar necessário, o que pode ser aceitável em um servidor dedicado de inferência, mas arriscado em um laptop de desenvolvedor. + +## Etapa 3: Carregar a Imagem para OCR + +Carregar o formato de arquivo correto é o próximo passo crucial. O método `OcrImage.FromFile` detecta automaticamente o tipo da imagem, mas ainda assim você deve verificar se o arquivo existe e se ele é uma variante TIFF suportada (por exemplo, compressão LZW ou CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Manipulando TIFFs multipáginas + +Se o seu TIFF contiver várias páginas, o Aspose OCR lerá apenas a primeira por padrão. Para processar todas as páginas, você pode iterar sobre `image.Pages` (disponível em versões mais recentes do SDK) e alimentar cada página ao motor separadamente. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +O trecho acima demonstra um padrão **carregar imagem para OCR** que funciona tanto para arquivos de página única quanto para multipáginas. + +## Etapa 4: Reconhecer Texto do TIF (ou qualquer raster) + +Agora que a imagem está na memória, pedimos ao Aspose que faça a mágica. O método `Recognize` devolve um `OcrResult` que contém o texto puro, pontuações de confiança e até informações de caixa delimitadora, caso você precise delas. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Por que isso funciona bem com TIF + +- **Compressão sem perdas:** TIFF costuma armazenar dados de pixel brutos, oferecendo ao motor de OCR a mais alta fidelidade. +- **Múltiplos espaços de cor:** O Aspose pode lidar com TIFF em escala de cinza, RGB ou até CMYK sem código de conversão extra. + +Se precisar ajustar pacotes de idioma (por exemplo, francês ou japonês), defina `ocrEngine.Settings.Language = "fr"` antes de chamar `Recognize`. + +## Etapa 5: Exibir o Texto Reconhecido + +Por fim, exibimos o texto no console. Em uma aplicação real você poderia gravar em um banco de dados, em um arquivo JSON ou alimentar a string em um pipeline de NLP subsequente. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Saída esperada + +Executar o programa em um escaneamento claro, 300 dpi, de uma página impressa normalmente produz algo como: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Se a imagem estiver borrada ou o limite de memória da GPU for muito baixo, você pode ver caracteres corrompidos ou um resultado truncado. Reduzir `MemoryLimitMb` abaixo da pegada da imagem (geralmente ~1 GB para um TIFF de 6000×8000 pixels) pode fazer o motor reverter automaticamente para CPU. + +## Exemplo Completo Funcional + +Abaixo está o programa completo, pronto para ser executado. Copie‑e‑cole em um novo projeto Console App, substitua `YOUR_DIRECTORY/large_photo.tif` pelo caminho da sua própria TIFF e pressione **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Checklist rápido + +- ✅ **Aspose OCR C# example** compilado sem erros. +- ✅ **GPU habilitada** (`Enable = true`). +- ✅ **Limite de memória da GPU** definido para 2048 MB. +- ✅ **Imagem carregada** a partir de um arquivo TIF. +- ✅ **Texto reconhecido** e impresso. + +## Armadilhas Comuns & Como Evitá‑las + +| Sintoma | Causa provável | Solução | +|---------|----------------|---------| +| `System.DllNotFoundException: cudart64_110.dll` | Runtime CUDA não instalado ou versão incompatível. | Instale o CUDA 11.x (ou 12.x) compatível com seu driver. | +| OCR devolve string vazia | Imagem muito escura ou DPI < 150. | Pré‑processar com `image.AdjustContrast()` ou reamostrar para 300 dpi. | +| Travamento por falta de memória na GPU | `MemoryLimitMb` muito baixo para a imagem. | Aumente o limite ou divida a imagem em blocos usando `image.Crop`. | +| Erro `Unsupported image format` | TIFF usa compressão exótica (por exemplo, JPEG‑2000). | Converta o TIFF para um formato suportado com ImageMagick antes do OCR. | + +## Expandindo a Demonstração + +Agora que você tem um **aspose ocr c# example** sólido, pode explorar: + +- **Processamento em lote:** Percorrer uma pasta de TIFs, gravando cada resultado em um arquivo `.txt`. +- **Pacotes de idioma:** `ocrEngine.Settings.Language = "es"` para espanhol, ou carregar dicionários personalizados. +- **Caixas delimitadoras:** Use `ocrResult.Regions` para obter coordenadas de cada palavra — útil para ferramentas de redação. +- **Fallback para CPU:** Envolva o bloco de GPU em um try/catch; em caso de falha, defina `ocrEngine.Settings.Gpu.Enable = false` e tente novamente. + +Essas extensões mantêm o padrão central intacto enquanto adicionam valor para casos de uso específicos. + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/portuguese/net/skew-angle-calculation/_index.md b/ocr/portuguese/net/skew-angle-calculation/_index.md index 3199a6e51..5d3fce621 100644 --- a/ocr/portuguese/net/skew-angle-calculation/_index.md +++ b/ocr/portuguese/net/skew-angle-calculation/_index.md @@ -40,9 +40,12 @@ Explore o Aspose.OCR for .NET, uma solução poderosa de OCR para reconhecimento Liberte o poder do Aspose.OCR for .NET, uma solução robusta para reconhecimento de imagens. Aprenda como calcular ângulos de inclinação sem esforço. ### [Calcule o ângulo de inclinação do URI no reconhecimento de imagem OCR](./calculate-skew-angle-from-uri/) Explore o Aspose.OCR for .NET para calcular facilmente ângulos de inclinação no reconhecimento de imagem OCR. Aprimore seus projetos com precisão e eficiência. +### [Tutorial de Documento OCR Rotacionado – Correção Automática de Inclinação e Rotação em C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Aprenda a corrigir automaticamente a inclinação e rotação de documentos OCR usando Aspose.OCR for .NET em C#. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/portuguese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..e30b53d61 --- /dev/null +++ b/ocr/portuguese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,274 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial de OCR de documento girado que mostra como corrigir automaticamente + a inclinação e detectar a rotação usando Aspose OCR em C#. Aprenda passo a passo + com código completo. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: pt +og_description: O tutorial de OCR para documentos rotacionados ensina como corrigir + automaticamente a inclinação e detectar a rotação usando Aspose OCR em C#. Siga + o guia completo. +og_title: Tutorial de OCR para Documento Rotacionado – Correção Automática de Inclinação + e Rotação em C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Tutorial de OCR para Documento Rotacionado – Correção Automática de Inclinação + e Rotação em C# +url: /pt/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial de Documento OCR Rotacionado – Guia Completo para Desenvolvedores C# + +Já se deparou com um **ocr rotated document tutorial** quando um formulário escaneado chegou de lado ou inclinado? Você não está sozinho. Essas imagens tortas podem arruinar uma extração de texto limpa, mas a boa notícia é que o Aspose OCR pode endireitar tudo automaticamente. + +Neste guia passo a passo, criaremos um `OcrEngine`, ativaremos a **automatic skew correction** e a **auto detect rotation**, executaremos o engine em uma imagem rotacionada e imprimiremos o texto limpo. Ao final, você saberá exatamente por que cada configuração importa, como ajustá‑la para casos extremos e terá um programa C# pronto para executar. + +## O que você aprenderá + +* Como instalar e referenciar o **Aspose OCR** em um projeto .NET. +* Por que habilitar `AutoCorrectSkew` e `AutoDetectRotation` é a chave para um **ocr rotated document tutorial** confiável. +* Como carregar qualquer imagem (JPG, PNG, TIFF) e deixar o engine fazer o trabalho pesado. +* Dicas para lidar com PDFs de várias páginas, digitalizações de baixa resolução e pacotes de idioma personalizados. + +> **Pré‑requisitos:** Visual Studio 2022 (ou qualquer IDE C#), runtime .NET 6+ e uma licença válida do Aspose OCR (ou o teste gratuito). Não é necessária experiência prévia em OCR. + +--- + +## Etapa 1 – Instalar o Aspose OCR e Configurar o Projeto + +Primeiro, o básico. Baixe o pacote NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Dica profissional:** Se você estiver usando uma licença de avaliação, coloque o arquivo `Aspose.OCR.lic` na mesma pasta do seu executável, ou registre‑lo programaticamente com `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Crie um novo aplicativo de console: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Agora você tem uma base limpa para o nosso **ocr rotated document tutorial**. + +## Etapa 2 – Inicializar o Engine OCR + +O engine é o coração do processo. Pense nele como um canivete suíço para extração de texto; você só precisa dizer quais truques habilitar. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Por que essas configurações?** +* `AutoCorrectSkew` analisa a linha de base dos caracteres e rotaciona a imagem o suficiente para tornar as linhas horizontais. +* `AutoDetectRotation` verifica a orientação geral (0°, 90°, 180°, 270°) e inverte a página se estiver de cabeça‑para‑baixo. Sem elas, o engine leria “pɹᴉʍ” em vez de “word”. + +## Etapa 3 – Carregar a Imagem que Você Deseja Processar + +O Aspose OCR funciona com qualquer formato raster comum. Substitua o caminho placeholder pela localização real do seu formulário rotacionado. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Caso extremo:** Se você receber um TIFF de várias páginas, use `OcrImage.FromMultiPageTiff(filePath)` e faça loop em `image.Pages`. + +## Etapa 4 – Executar o Reconhecimento + +Agora o engine faz a mágica. Primeiro endireitará a imagem (graças aos nossos flags de skew/rotação) e depois extrairá os caracteres. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Se precisar de suporte a idiomas além do inglês, configure antes de chamar `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Etapa 5 – Exibir o Texto Reconhecido + +Finalmente, despeje o texto limpo no console — ou redirecione para um arquivo, um banco de dados, o que melhor se adequar ao seu fluxo de trabalho. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Saída esperada** (supondo que a imagem de exemplo contenha “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Observe como o texto aparece corretamente mesmo que a imagem original tenha sido rotacionada 90° e levemente inclinada. + +--- + +## Lidando com Problemas Comuns + +| Problema | Por que acontece | Correção | +|------|----------------|-----| +| **Saída em branco** | Correção de skew desativada ou imagem muito escura. | Habilite `AutoCorrectSkew` (já está ativado) e aumente o contraste da imagem via `image.AdjustContrast(1.2)`. | +| **Caracteres lixo** | Configuração de idioma errada. | Defina `ocrEngine.Settings.Language` para corresponder ao idioma do documento. | +| **Atraso de desempenho em PDFs grandes** | O engine processa cada página sequencialmente. | Use `Parallel.ForEach` em `image.Pages` para aproveitar CPUs multi‑core. | +| **Exceção de licença** | Teste expirado. | Adquira uma licença permanente ou permaneça dentro dos limites de teste (5 páginas por execução). | + +## Dicas Profissionais para um Tutorial de OCR Rotacionado Robusto + +* **Processamento em lote:** Envolva todo o fluxo em um método que aceita um caminho de pasta, itera sobre cada imagem e grava cada resultado em um arquivo `.txt`. +* **Pré‑processamento:** Às vezes, uma digitalização ruidosa se beneficia de `image.Denoise()` antes do reconhecimento. +* **Pós‑processamento:** Use expressões regulares para limpar leituras comuns de OCR, por exemplo, substituir “0” por “O” apenas quando cercado por letras. +* **Log:** O Aspose OCR fornece `ocrEngine.Logger` — conecte‑o a um logger de arquivo para capturar avisos sobre pontuações de baixa confiança. + +## Código Completo, Pronto‑para‑Executar + +Salve o seguinte como `Program.cs` dentro do seu projeto de console. Ele inclui todas as etapas, comentários e um pequeno helper para processamento em lote. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Execute‑o: + +```bash +dotnet run +``` + +Você deverá ver o texto limpo impresso no console, provando que nosso **ocr rotated document tutorial** funciona de ponta a ponta. + +--- + +## Conclusão + +Agora você tem um **ocr rotated document tutorial** completo que corrige automaticamente o skew, detecta rotação e extrai texto limpo usando Aspose OCR em C#. O principal aprendizado? Habilitar `AutoCorrectSkew` **e** `AutoDetectRotation` transforma uma digitalização extremamente inclinada em uma saída perfeitamente legível com apenas algumas linhas de código. + +A partir daqui, você pode expandir para trabalhos em lote, integrar pacotes de idioma ou alimentar os resultados em pipelines de análise downstream. Quer explorar mais a **automatic skew correction**? Confira a API de pré‑processamento de imagens da Aspose, ou experimente limites personalizados para digitalizações ruidosas. + +Tem perguntas sobre como lidar com PDFs, TIFFs de várias páginas ou integrar com Azure Functions? Deixe um comentário e feliz codificação! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens de implementação alternativas em seus próprios projetos. + +- [modo de documento OCR – Detectar Modo de Áreas no Reconhecimento de Imagem OCR](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extrair texto de imagem C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Tutorial Aspose OCR – Reconhecimento Óptico de Caracteres](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/portuguese/net/text-recognition/_index.md index 8efadbd23..0e9eebbfd 100644 --- a/ocr/portuguese/net/text-recognition/_index.md +++ b/ocr/portuguese/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Liberte o poder do Aspose.OCR para .NET. Aprenda a obter resultados de OCR no fo Aprimore seus aplicativos .NET com Aspose.OCR para reconhecimento eficiente de texto de imagem. Explore o modo de detecção de áreas de OCR para obter resultados precisos. ### [Reconhecer PDF em reconhecimento de imagem OCR](./recognize-pdf/) Desbloqueie o potencial do OCR em .NET com Aspose.OCR. Extraia texto de PDFs sem esforço. Baixe agora para uma experiência de integração perfeita. +### [Realizar OCR em PDF com Aspose.OCR – Guia Completo em C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Aprenda a executar OCR em PDFs usando Aspose.OCR com um guia completo em C#. Integre facilmente em seus aplicativos .NET. ### [Reconhecer tabela no reconhecimento de imagem OCR](./recognize-table/) Desbloqueie o potencial do Aspose.OCR para .NET com nosso guia completo sobre reconhecimento de tabelas no reconhecimento de imagem OCR. +### [Realizar OCR em Imagem com Aspose OCR – Guia em Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Aprenda a executar OCR em imagens usando Aspose OCR com suporte ao idioma Hindi. Guia passo a passo para integrar OCR em seus aplicativos. +### [Como usar Aspose: Converter imagem para HTML com OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Aprenda a converter imagens em HTML usando Aspose OCR, preservando o texto reconhecido em formato web. +### [Executar OCR em Imagem e Detectar Palavras Erradas em C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Aprenda a executar OCR em imagens e identificar palavras com erros ortográficos usando Aspose.OCR em C#. +### [OCR de Legenda de Vídeo em C# – Guia Completo](./video-subtitle-ocr-in-c-complete-guide/) +Aprenda a extrair legendas de vídeos usando Aspose.OCR em C#, com um guia passo a passo para integrar OCR de legendas em seus aplicativos. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/portuguese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..f15f34773 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: Como usar o Aspose para converter imagem em HTML e extrair texto da imagem + em C#. Aprenda a gerar HTML a partir de imagem e fazer OCR de imagem para HTML rapidamente. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: pt +og_description: Como usar o Aspose para converter imagem em HTML, extrair texto da + imagem e gerar HTML a partir da imagem com OCR em C#. Siga este guia completo. +og_title: 'Como usar o Aspose: converter imagem em HTML com OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Como usar o Aspose: converter imagem em HTML com OCR' +url: /pt/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como usar Aspose: Converter imagem em HTML com OCR + +Já se perguntou **como usar Aspose** para transformar uma foto escaneada em HTML organizado? Talvez você tenha uma página de revista, um recibo ou um bilhete manuscrito e precise que o texto e o layout sejam preservados para publicação na web. A boa notícia é que você não precisa escrever um analisador personalizado ou lidar com processamento de imagem de baixo nível—Aspose.OCR faz o trabalho pesado para você. + +Neste tutorial, percorreremos um **exemplo completo e executável** que mostra como **converter imagem em HTML**, **extrair texto de imagem** e **gerar HTML a partir de imagem** usando a biblioteca Aspose OCR em C#. Ao final, você terá um pequeno aplicativo de console que produz um arquivo HTML com o layout da página original intacto, pronto para ser inserido em qualquer site. + +## Pré-requisitos + +Antes de mergulharmos, certifique‑se de que você tem o seguinte na sua máquina: + +- **.NET 6.0 SDK** ou posterior (o código funciona tanto com .NET Core quanto com .NET Framework). +- **Visual Studio 2022** (ou qualquer editor de sua preferência). +- **Aspose.OCR for .NET** – instale via NuGet: `dotnet add package Aspose.OCR`. +- Um arquivo de imagem (JPEG/PNG) que você deseja transformar, por exemplo, `magazine_page.jpg`. + +Nenhum arquivo de configuração extra é necessário; a biblioteca já inclui tudo o que é preciso para OCR e geração de layout HTML. + +## Etapa 1: Configurar o projeto e adicionar Aspose.OCR + +Primeiro, crie um novo projeto de console e inclua o pacote Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Dica profissional:** Se você estiver usando o Visual Studio, basta clicar com o botão direito no projeto → *Gerenciar Pacotes NuGet* → pesquisar por **Aspose.OCR** e instalá-lo. Esta etapa garante que você possa **ocr image to html** sem referências ausentes. + +## Etapa 2: Inicializar o motor OCR + +O núcleo do processo é a classe `OcrEngine`. Pense nela como o cérebro que lê a imagem e decide como gerar o resultado. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Aqui instanciamos `OcrEngine`. Você não precisa fornecer credenciais para a versão gratuita; a biblioteca usará seus modelos de reconhecimento embutidos. + +## Etapa 3: Carregar a imagem de origem + +Em seguida, aponte o motor para o arquivo que você deseja processar. Aspose fornece o conveniente método `OcrImage.FromFile` que lida com a maioria dos formatos de imagem. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Substitua `YOUR_DIRECTORY` pelo caminho absoluto ou relativo onde sua imagem está localizada. Se a imagem estiver na mesma pasta que o executável, você pode simplesmente usar `"magazine_page.jpg"`. + +## Etapa 4: Reconhecer e solicitar HTML com layout + +Este é o ponto central do tutorial. Ao passar `OutputFormat.HtmlWithLayout` informamos ao Aspose para **gerar HTML a partir da imagem** preservando o posicionamento original de blocos de texto, imagens e tabelas. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +A propriedade `recognitionResult.Text` agora contém um documento HTML completo. Se você precisasse apenas de texto simples, poderia usar `OutputFormat.Text`, mas estamos focando em **convert image to html** com fidelidade de layout. + +## Etapa 5: Salvar o arquivo HTML + +Finalmente, grave a string HTML no disco. Isso fornece um arquivo pronto para uso que você pode abrir em qualquer navegador. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Executar o programa gerará `magazine.html`. Abra‑o e você verá o texto da página original posicionado exatamente como apareceu na imagem de origem—perfeito para arquivamento ou publicação na web. + +## Exemplo completo em funcionamento + +Abaixo está o programa **completo, pronto para copiar e colar**. Nenhuma parte foi omitida, para que você possa compilar e executá‑lo imediatamente após definir os caminhos corretos. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Saída esperada + +Ao abrir `magazine.html` em um navegador, você deverá ver algo semelhante a isto (simplificado para ilustração): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Os atributos `style` exatos diferirão com base na imagem original, mas a estrutura garante que **extract text from image** e **generate html from image** ocorram em uma única etapa contínua. + +## Perguntas comuns e casos extremos + +### E se a imagem for de baixa resolução? + +Aspose.OCR funciona melhor com imagens que tenham pelo menos **300 DPI**. Se seu arquivo estiver borrado, tente pré‑processá‑lo com uma biblioteca de aprimoramento de imagem (por exemplo, ImageSharp) antes de enviá‑lo ao motor OCR. Baixa qualidade pode afetar tanto a precisão de **extract text from image** quanto a fidelidade do layout HTML gerado. + +### Posso controlar o idioma do OCR? + +Sim. Defina a propriedade `Language` no `OcrEngine` antes de chamar `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +### Como obter texto simples em vez de HTML? + +Se você precisar apenas da string bruta, substitua `OutputFormat.HtmlWithLayout` por `OutputFormat.Text`. O mesmo `recognitionResult.Text` então conterá apenas os caracteres extraídos. + +### Existe uma maneira de incorporar imagens ao HTML gerado? + +Aspose.OCR pode incorporar a imagem original como um URI de dados base‑64 quando você usa `OutputFormat.HtmlWithLayoutAndImages`. Isso é útil quando você deseja um único arquivo HTML sem recursos externos. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### E quanto ao processamento de grandes lotes? + +Para processamento em lote, envolva a lógica em um loop `foreach` sobre uma lista de caminhos de arquivos. Reutilizar a mesma instância de `OcrEngine` reduz a sobrecarga e acelera o pipeline de **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Dicas para código pronto para produção + +- **Liberar recursos**: Tanto `OcrEngine` quanto `OcrImage` implementam `IDisposable`. Envolva‑os em declarações `using` para liberar a memória nativa rapidamente. +- **Tratamento de erros**: Capture `IOException` para problemas relacionados a arquivos e `OcrException` para problemas de reconhecimento. +- **Desempenho**: Se você processar muitas imagens, considere habilitar **paralelismo** (`Parallel.ForEach`), mas fique atento ao uso de CPU—OCR é intensivo em CPU. +- **Log**: Integre um logger (por exemplo, Serilog) para capturar as pontuações de confiança do OCR (`recognitionResult.Confidence`) para monitoramento de qualidade. + +## Conclusão + +Acabamos de cobrir **como usar Aspose** para **converter imagem em HTML**, **extrair texto de imagem** e **gerar HTML a partir de imagem** em alguns passos simples. O exemplo de código completo mostra como **ocr image to html** preservando o layout, tornando‑o uma base sólida para qualquer projeto de digitalização de documentos. + +A partir daqui, você pode: + +- Experimentar diferentes opções de `OutputFormat` para atender às suas necessidades. +- Combinar a saída HTML com um framework CSS para estilização responsiva. +- Alimentar o texto extraído em um índice de busca ou em um pipeline de aprendizado de máquina. + +Experimente, ajuste as configurações e veja como a Aspose transforma imagens em conteúdo pronto para a web com facilidade. Se encontrar algum problema, deixe um comentário—bom código! + +![Diagrama mostrando o pipeline OCR de imagem para layout HTML – como usar Aspose](/images/ocr-pipeline.png "como usar aspose") + +--- + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos estreitamente relacionados que se baseiam nas técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [Extrair texto de imagem C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Converter imagem em texto – Executar OCR em imagem a partir de URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Reconhecer texto em 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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/portuguese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..bbc0c91b4 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-03 +description: Execute OCR em imagem e extraia texto da imagem usando Aspose.OCR. Aprenda + como detectar palavras com erros ortográficos e obter sugestões de correção em uma + única demonstração em C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: pt +og_description: Execute OCR em uma imagem para extrair texto da imagem, depois detecte + palavras com erros ortográficos e obtenha sugestões de correção com Aspose.OCR em + C#. +og_title: Realizar OCR em Imagem e Detectar Palavras com Erros Ortográficos em C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Realizar OCR em Imagem e Detectar Palavras Ortograficamente Incorretas em C# +url: /pt/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR em Imagem e Detectar Palavras com Erro de Ortografia em C# + +Já se perguntou como **executar OCR em imagem** sem perder a cabeça? Você não está sozinho. Seja digitalizando cartas antigas, escaneando recibos ou construindo um fluxo de trabalho inteligente para documentos, extrair texto limpo de fotos é o primeiro obstáculo. A boa notícia? Com Aspose.OCR você pode montar uma solução em minutos, e o bônus é que também pode **detectar palavras com erro de ortografia** e **obter sugestões de correção** na mesma execução. + +Neste tutorial vamos percorrer um aplicativo console C# completo, pronto‑para‑executar, que **extrai texto de imagem**, executa um verificador ortográfico em inglês e imprime cada erro com sugestões úteis. Ao final, você saberá exatamente **como extrair texto**, como conectar a API de verificação ortográfica e como será a saída esperada no console. + +## O que você vai construir + +- Carregar um bitmap (ou PNG) que contém erros tipográficos. +- Executar Aspose.OCR para **executar OCR em imagem** e obter os dados brutos em forma de string. +- Inicializar o verificador ortográfico interno em inglês. +- **Detectar palavras com erro de ortografia** e **obter sugestões de correção** para cada uma. +- Imprimir um relatório organizado no console. + +Sem serviços externos, sem chamadas HTTP complicadas — apenas um único pacote NuGet e algumas linhas de código. + +## Pré‑requisitos + +- .NET 6.0 SDK ou superior (o código também funciona no .NET Framework 4.7+). +- Visual Studio 2022 (ou qualquer editor de sua preferência). +- Pacote NuGet Aspose.OCR para .NET (`Aspose.OCR`). +- Um arquivo de imagem (`letter_with_typos.png`) colocado em algum local que você possa referenciar a partir do projeto. + +Se você nunca usou Aspose antes, não se preocupe — instalar o pacote é tão fácil quanto executar: + +```bash +dotnet add package Aspose.OCR +``` + +Agora vamos mergulhar na implementação. + +## Etapa 1: Configurar o Projeto e Instalar Aspose.OCR + +Crie um novo projeto console e adicione a biblioteca OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Depois que a restauração terminar, abra `Program.cs`. Substituiremos o conteúdo padrão pelo código completo do demo mais adiante, mas primeiro vamos entender por que cada namespace é importante. + +- `Aspose.OCR` – Núcleo do motor OCR e manipulação de imagens. +- `Aspose.OCR.SpellCheck` – Utilitários de verificação ortográfica que acompanham a biblioteca. +- `System` – Classes base padrão do .NET (ex.: `Console`). + +## Etapa 2: Carregar a Imagem e Executar OCR em Imagem + +O primeiro trabalho real é alimentar a imagem ao motor OCR. Aspose.OCR lê muitos formatos (PNG, JPEG, TIFF). Aqui está o trecho que faz o trabalho pesado: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Por que isso importa:** `OcrImage.FromFile` abstrai os detalhes de nível de pixel, enquanto `OcrEngine.Recognize` executa o modelo neural treinado que traduz glifos visuais em caracteres Unicode. A propriedade `ocrResult.Text` agora contém a string bruta — exatamente o que você precisa para **extrair texto de imagem**. + +> **Dica profissional:** Se sua imagem contiver múltiplos idiomas, você pode definir `ocrEngine.Language = OcrLanguage.Multilingual;` antes de chamar `Recognize`. + +## Etapa 3: Inicializar o Verificador Ortográfico em Inglês + +Aspose.OCR vem com um motor de verificação ortográfica interno que entende inglês pronto para uso. Inicializá‑lo é uma linha única: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Por que esta etapa é crucial:** A saída do OCR pode incluir caracteres reconhecidos incorretamente (ex.: “l” vs “1”) ou erros reais de digitação no documento original. O verificador ortográfico analisará a string, localizará tokens suspeitos e sugerirá alternativas. + +## Etapa 4: Detectar Palavras com Erro de Ortografia e Obter Sugestões + +Agora alimentamos o texto do OCR ao verificador: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` é uma coleção onde cada entrada contém a palavra incorreta e um array de possíveis correções. + +## Etapa 5: Exibir os Resultados + +Por fim, iteramos sobre a coleção e imprimimos um relatório legível: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Saída Esperada no Console + +Assumindo que `letter_with_typos.png` contenha a frase: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Executar o demo produzirá algo como: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Observe como cada erro de digitação é acompanhado por algumas correções plausíveis — exatamente o que você precisa ao construir uma interface de correção amigável ao usuário. + +## Exemplo Completo Funcional + +Abaixo está o programa **completo, pronto‑para‑copiar‑e‑colar**. Substitua `YOUR_DIRECTORY` pelo caminho real do seu arquivo de imagem. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Casos Limite a Considerar** +> - **Imagem Vazia:** Se o motor OCR retornar uma string vazia, `spellChecker.Check` simplesmente retornará uma coleção vazia — sem falhas. +> - **Texto Não‑Inglês:** Troque `OcrLanguage.English` por `OcrLanguage.French` (ou qualquer idioma suportado) para **detectar palavras com erro de ortografia** em outras localidades. +> - **Documentos Grandes:** Para PDFs de várias páginas, você faria um loop sobre cada página, executaria OCR e então agregaria os resultados antes da verificação ortográfica. + +## Visão Geral Visual (Texto Alternativo da Imagem) + +![Diagrama mostrando o fluxo para executar OCR em imagem, extrair texto de imagem e depois detectar palavras com erro de ortografia com sugestões de correção](perform-ocr-on-image-flow.png) + +*O diagrama acima ilustra o pipeline de ponta a ponta: imagem → motor OCR → texto bruto → verificador ortográfico → sugestões.* + +## Perguntas Frequentes & Dicas Profissionais + +| Pergunta | Resposta | +|----------|----------| +| **Preciso de conexão com a internet?** | Não. Aspose.OCR funciona totalmente localmente; ideal para ambientes offline ou seguros. | +| **Quão preciso é o verificador ortográfico?** | Ele usa um dicionário de ~150 k palavras em inglês e correspondência aproximada, então a maioria dos erros comuns são capturados. | +| **Posso personalizar o dicionário?** | Sim. `SpellChecker.AddUserDictionary("custom.txt")` permite carregar termos específicos de domínio (ex.: nomes de produtos). | +| **E se a imagem estiver inclinada?** | O motor OCR detecta a orientação automaticamente, mas você pode chamar manualmente `ocrEngine.ImagePreprocessing.Rotate(angle)` para casos difíceis. | +| **Existe uma forma de destacar sugestões na UI?** | Depois de obter a coleção `misspellings`, você pode mapear cada `entry.Word` de volta à sua posição em `ocrResult.Text` e sublinhá‑la em um RichTextBox ou visualização web. | + +## Conclusão + +Acabamos de mostrar **como executar OCR em imagem**, **extrair texto de imagem** e então **detectar palavras com erro de ortografia** enquanto **obtemos sugestões de correção** — tudo com um conciso aplicativo console C#. A ideia central é simples: deixe o Aspose.OCR fazer o trabalho pesado de reconhecer caracteres e, em seguida, use seu verificador ortográfico interno para limpar a saída. A partir daqui você pode expandir o demo para um serviço completo de processamento de documentos, integrá‑lo a uma API web ou conectá‑lo a um editor desktop. + +Pronto para o próximo passo? Experimente trocar o idioma para espanhol, processar um PDF de várias páginas ou criar uma pequena interface WPF que permita ao usuário clicar em uma palavra para aceitar a sugestão. Os blocos de construção já estão no lugar — basta continuar experimentando. + +Se você encontrou algum obstáculo ou tem ideias para extensões, deixe um comentário abaixo. Boa codificação! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Extrair texto de imagem C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extrair Texto de Imagem Usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extrair Texto de Imagem – Otimização de OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/portuguese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..e03eb5a42 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: Execute OCR em imagem usando Aspose OCR em C#. Aprenda como carregar + a imagem para OCR e extrair texto em hindi offline com código passo a passo. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: pt +og_description: Execute OCR em imagem com Aspose OCR em C#. Este tutorial mostra como + carregar a imagem para OCR e extrair texto em hindi offline, completo com código + executável. +og_title: Executar OCR em Imagem – Guia de OCR em Hindi da Aspose +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Realizar OCR em Imagem com Aspose OCR – Guia em Hindi +url: /pt/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR em Imagem com Aspose OCR – Guia em Hindi + +Já precisou **realizar OCR em imagem** arquivos mas ficou preso em como obter caracteres em Hindi deles? Você não está sozinho—muitos desenvolvedores encontram essa barreira ao tentar ler scripts não latinos pela primeira vez. A boa notícia é que o Aspose OCR torna isso bastante simples, e você pode até fazer tudo completamente offline. + +Neste guia, vamos **carregar imagem para OCR**, apontar o motor para seus pacotes de idioma offline e, finalmente, **extrair texto em Hindi da imagem** sem nunca acessar a internet. Ao final, você terá um aplicativo console C# pronto‑para‑executar que lê um recibo em Hindi e imprime o texto no console. + +## O que você precisará + +- **.NET 6.0** ou superior (o código também funciona no .NET Framework 4.7+) +- **Aspose.OCR for .NET** pacote NuGet + `dotnet add package Aspose.OCR` +- Uma pasta contendo os **recursos de idioma Hindi offline** (baixe no portal da Aspose) +- Um arquivo de imagem com texto em Hindi, por exemplo, `receipt_hindi.png` + +É isso—nenhum serviço externo, nenhuma chave de API, apenas código direto. + +## Realizar OCR em Imagem – Implementação Passo a Passo + +A seguir, dividimos o processo em sete etapas claras. Cada etapa é explicada **por que** ela importa, não apenas **o que** digitar. + +### Etapa 1: Criar a Instância do Motor OCR + +O motor é o coração do Aspose OCR. Instanciá‑lo fornece acesso a todas as configurações que você ajustará mais tarde. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +**Por quê?** +> Sem um `OcrEngine` você não tem um objeto para chamar `Recognize`. Pense nele como a “câmera” que mais tarde escaneará sua imagem. + +### Etapa 2: Apontar o Motor para Recursos Offline + +A Aspose fornece pacotes de idioma que você pode armazenar localmente. Definir `ResourcesFolder` informa ao motor onde procurar. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +**Dica:** +> Use um caminho absoluto durante o desenvolvimento, depois troque para um caminho relativo ou configuração para produção. + +### Etapa 3: Forçar Modo Offline + +Você pode se perguntar, “Eu realmente preciso desativar a busca online?” +Se você está trabalhando atrás de um firewall ou apenas quer resultados determinísticos, defina `UseOfflineResources` como `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +**Dica profissional:** +> Deixar essa flag como `false` pode fazer o motor baixar dados adicionais, o que aumenta a latência e pode violar políticas de segurança. + +### Etapa 4: Selecionar Hindi como o Idioma de Reconhecimento + +Aqui nós **extraímos texto em Hindi da imagem** informando ao motor qual idioma esperar. Isso melhora drasticamente a precisão. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +**Por que ajuda:** +> Motores de OCR usam modelos de caracteres específicos por idioma. Ao fixar em Hindi, você evita que o motor adivinhe entre dezenas de scripts. + +### Etapa 5: Carregar Imagem para OCR + +Agora realmente **carregamos a imagem para OCR**. O método `OcrImage.FromFile` lê o bitmap em um formato que o motor entende. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +**Armadilha comum:** +> Fornecer um caminho com barras normais no Windows funciona, mas usar `Path.Combine` torna seu código independente de plataforma. + +### Etapa 6: Executar o Reconhecimento + +Com tudo configurado, finalmente **realizamos OCR em imagem** chamando `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +**O que está acontecendo?** +> O motor escaneia cada pixel, compara padrões com o banco de dados de glifos em Hindi e constrói uma string de caracteres Unicode. + +### Etapa 7: Exibir o Texto Reconhecido + +O objeto de resultado contém uma propriedade `Text` que contém a string extraída. Simplesmente a escrevemos no console. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +**Saída esperada:** +> Se `receipt_hindi.png` contiver “भुगतान सफल”, o console imprimirá exatamente essa linha, preservando os diacríticos. + +## Carregar Imagem para OCR – Preparando o Recurso + +Se você está se perguntando se pode alimentar o motor com um stream ao invés de um arquivo, a resposta é sim. Substitua `OcrImage.FromFile` por: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +**Por que usar um stream?** +> Streams permitem trabalhar com imagens armazenadas em bancos de dados, blobs na nuvem ou recursos incorporados—perfeito para serviços escaláveis. + +## Extrair Texto em Hindi da Imagem – Lidando com Casos de Borda + +1. **Pacote de idioma ausente** – Se o pacote Hindi não for encontrado, `Recognize` lança uma exceção. Envolva a chamada em um try/catch e registre uma mensagem amigável. +2. **Imagens de baixa resolução** – A precisão do OCR cai abaixo de 300 dpi. Pré‑procese a imagem (redimensionar, nitidez) antes de carregar. +3. **Documentos multilíngues** – Você pode habilitar vários idiomas: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Esses ajustes garantem que sua rotina de **realizar OCR em imagem** permaneça robusta em produção. + +## Executando o Exemplo Completo + +Salve o arquivo a seguir como `Program.cs`, substitua os caminhos de placeholder e execute: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Ao executar `dotnet run`, você deverá ver algo como: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Se você obtiver uma string vazia, verifique novamente se o **ResourcesFolder** aponta para a pasta contendo `Hindi.traineddata` e se a imagem está clara o suficiente. + +## Conclusão + +Nós percorremos como **realizar OCR em arquivos de imagem** com Aspose OCR, cobrindo tudo desde **carregar imagem para OCR** até **extrair texto em Hindi da imagem** em um cenário totalmente offline. O código completo e executável acima fornece uma base sólida, e as dicas sobre streams, tratamento de erros e suporte multilíngue ajudarão a adaptar a solução a projetos do mundo real. + +Pronto para o próximo passo? Experimente mudar o idioma para **OcrLanguage.Tamil** ou alimentar imagens a partir de um armazenamento Azure Blob. Você também pode experimentar as configurações `ImagePreprocessing` para aumentar a precisão em recibos ruidosos. + +Tem perguntas ou encontrou algum problema? Deixe um comentário—bom código! + +![Exemplo de OCR em imagem + +## O que você deve aprender a seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que expandem as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [Extrair texto de imagem 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/) +- [Extrair Texto de Imagem – Otimização OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/portuguese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..fca43ea7a --- /dev/null +++ b/ocr/portuguese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-03 +description: Execute OCR em PDF e converta PDF escaneado em PDF pesquisável usando + Aspose.OCR. Aprenda como reconhecer texto de PDF e criar PDFs pesquisáveis em minutos. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: pt +og_description: Execute OCR em PDF e crie instantaneamente um PDF pesquisável. Este + tutorial mostra passo a passo como reconhecer texto de PDF usando Aspose.OCR. +og_title: Realizar OCR em PDF – Guia Completo de C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Realize OCR em PDF com Aspose.OCR – Guia Completo em C# +url: /pt/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Executar OCR em PDF com Aspose.OCR – Guia Completo em C# + +Já se perguntou **como executar OCR em PDF** sem lutar com dezenas de ferramentas de linha de comando? Você não está sozinho. Seja digitalizando notas fiscais, arquivando relatórios antigos ou simplesmente precisando de uma versão pesquisável de um contrato escaneado, transformar um PDF estático em algo que você realmente pode buscar é revolucionário. + +Neste guia vamos percorrer **como criar PDFs pesquisáveis** a partir de PDFs escaneados (e até mesmo de imagens simples) usando Aspose.OCR para .NET. Ao final, você será capaz de **reconhecer texto de PDF** com poucas linhas de código C#, e entenderá o porquê de cada passo para adaptar a solução aos seus próprios projetos. + +> **Resumo rápido:** Todo o processo se resume a três coisas — inicializar o motor OCR, fornecer a fonte (PDF ou imagem) e salvar a saída PDF pesquisável. Vamos mergulhar. + +--- + +## O que você precisará + +Antes de começar, certifique‑se de que tem: + +| Pré‑requisito | Por que é importante | +|--------------|----------------------| +| **.NET 6.0+** (ou .NET Framework 4.6+) | Aspose.OCR tem como alvo runtimes modernos; versões mais antigas podem perder atualizações de API. | +| **Aspose.OCR for .NET** pacote NuGet | Fornece a classe `OcrEngine` e utilitários de manipulação de PDF. | +| **Uma licença válida da Aspose** (ou use a avaliação gratuita) | Sem licença você encontrará um limite de avaliação de 30 dias e marcas d'água. | +| **Um PDF escaneado** (ou um arquivo de imagem) que você deseja tornar pesquisável | Este é o documento de origem para o OCR. | +| **Visual Studio 2022** (ou qualquer editor C#) | Facilita a depuração, mas qualquer IDE funciona. | + +Você pode instalar a biblioteca com o seguinte comando NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Dica de especialista:** Se você estiver trabalhando em um pipeline CI, adicione o arquivo de licença aos artefatos de build e carregue‑o em tempo de execução para evitar caminhos codificados. + +--- + +## Executar OCR em PDF – Configurando Aspose.OCR + +A primeira coisa que precisamos é uma nova instância de `OcrEngine`. Pense nela como o cérebro que lerá seu documento. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Por que uma nova instância a cada vez? O motor mantém configurações (como idioma) que podem variar por documento. Instanciá‑lo por execução garante um estado limpo e evita interferência entre trabalhos. + +--- + +## Como criar PDF pesquisável – Configurando senhas (Opcional) + +Se o seu PDF estiver protegido, você precisa informar a senha ao motor antes que ele possa ler as páginas: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Pular esta etapa em um arquivo protegido gerará uma `PdfPasswordException`. Sempre envolva em um try‑catch se não tiver certeza sobre o status de proteção. + +--- + +## Converter PDF escaneado em PDF pesquisável – Carregando a fonte + +Aspose.OCR trabalha com a abstração `OcrImage`, que pode envolver PDFs, TIFFs, JPEGs, etc. Veja como carregar um PDF escaneado na memória: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Nos bastidores, `FromFile` analisa cada página em imagens raster que o motor OCR pode processar. Se você tiver um PDF de várias páginas, o motor iterará automaticamente sobre cada página. + +--- + +## Reconhecer texto de PDF – Executando o OCR + +Agora o núcleo do tutorial: peça ao motor para reconhecer o texto e gerar um PDF pesquisável. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` indica ao motor que ele deve incorporar uma camada de texto invisível sobre as imagens escaneadas originais. O PDF resultante mantém a fidelidade visual da digitalização enquanto se torna totalmente pesquisável — exatamente o que você precisa para auditorias de conformidade. + +--- + +## Converter imagem em PDF pesquisável – Salvando o resultado + +Por fim, grave os dados binários no disco: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +A propriedade `Binary` contém os bytes brutos do PDF. Você também pode transmiti‑los diretamente para uma resposta web se estiver construindo uma API. + +--- + +![Diagrama mostrando o fluxo de conversão OCR para criar PDF pesquisável](https://example.com/ocr-flow.png "Diagrama do fluxo de OCR em PDF") + +*Texto alternativo da imagem: Diagrama do fluxo de OCR em PDF ilustrando como um PDF escaneado é transformado em um PDF pesquisável.* + +--- + +## Casos de borda e dicas práticas + +### 1. Arquivos grandes e gerenciamento de memória +Se você estiver processando PDFs maiores que 100 MB, considere usar `OcrEngineSettings.MemoryLimit` para limitar o uso de memória. Além disso, processe páginas em lotes para evitar `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Suporte a idiomas +Por padrão o Aspose.OCR assume inglês. Para reconhecer outros idiomas, defina a propriedade `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Cenários multithread +`OcrEngine` **não** é thread‑safe. Se precisar de processamento paralelo, crie um motor separado por thread. + +### 4. Depurando a precisão do OCR +Você pode extrair o texto puro de `ocrResult` para depuração: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Se a saída parecer confusa, experimente `PreprocessSettings` (por exemplo, deskew, despeckle) para melhorar a qualidade. + +### 5. Armadilhas de licenciamento +Quando você executa a versão de avaliação, a Aspose adiciona uma marca d'água ao PDF de saída. Registre sua licença logo no início da aplicação: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Exemplo completo – Do início ao fim + +Abaixo está o programa completo, pronto‑para‑executar, que incorpora todas as dicas acima. Sinta‑se à vontade para copiar‑colar em um novo projeto de console. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Saída esperada:** Após a execução, você verá uma linha no console confirmando o local do arquivo. Abra `output.pdf` em qualquer visualizador de PDF; tente digitar uma palavra que você sabe que aparece na digitalização original. Se o texto for destacado, você realizou com sucesso o **OCR em PDF** e criou um documento pesquisável. + +--- + +## Perguntas Frequentes + +**P: Posso usar isso para converter uma única imagem (PNG/JPEG) em PDF pesquisável?** +R: Absolutamente. Substitua `OcrImage.FromFile("input.pdf")` pelo caminho do seu arquivo de imagem. O motor rasterizará a imagem e incorporará a camada OCR da mesma forma. + +**P: E se meu PDF contiver páginas escaneadas e texto nativo?** +R: O motor sobreporá o texto OCR ao conteúdo existente, de modo que o texto nativo permanece selecionável enquanto as páginas escaneadas se tornam pesquisáveis. + +**P: Quão precisa é a OCR?** +R: A precisão depende da qualidade da fonte. Digitalizações limpas e de alta resolução (>300 dpi) entregam >95 % de precisão. Para documentos ruidosos, habilite `PreprocessSettings` (deskew, despeckle) antes de chamar `Recognize`. + +--- + +## Próximos passos – Expandindo seu kit de ferramentas OCR + +Agora que você pode **reconhecer texto de PDF** e **converter PDF escaneado em PDF pesquisável**, considere estes tópicos de continuação: + +- **Processamento em lote**: Percorra uma pasta de PDFs e gere versões pesquisáveis automaticamente. +- **Extração de texto**: Use `ocrResult.Text` para alimentar um índice de busca (por exemplo, Elasticsearch). +- **Pacotes de idioma personalizados**: Baixe dados de idioma adicionais da Aspose para suportar scripts asiáticos. +- **Conformidade PDF/A**: Combine Aspose.PDF com a saída OCR para criar PDFs prontos para arquivamento. + +Cada um desses itens se baseia nos passos centrais que cobrimos, então você está bem posicionado para expandir sua solução. + +--- + +## Conclusão + +Acabamos de mostrar **como executar OCR em PDF** usando Aspose.OCR, transformar PDFs escaneados em PDFs totalmente pesquisáveis e ainda cobrir a conversão de imagens simples em PDFs pesquisáveis. O código + +## O que você deve aprender a seguir? + +Os tutoriais a seguir abordam tópicos intimamente relacionados que ampliam as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas em seus próprios projetos. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [How to OCR 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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/portuguese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..b4a652493 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial de OCR de legendas de vídeo mostrando como extrair quadros de + vídeo e ler texto de arquivos de vídeo como MP4 usando Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: pt +og_description: Aprenda OCR de legendas de vídeo com Aspose.OCR. Extraia quadros de + vídeo, leia texto do vídeo e extraia texto de MP4 em poucos minutos. +og_title: OCR de Legendas de Vídeo em C# – Guia Passo a Passo +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR de Legendas de Vídeo em C# – Guia Completo +url: /pt/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR de Legendas de Vídeo em C# – Guia Completo + +Já precisou de **video subtitle ocr** mas não sabia por onde começar? Você não está sozinho. Seja digitalizando gravações de aulas, extraindo legendas de vídeos de treinamento, ou simplesmente curioso sobre como ler texto de vídeo, este tutorial mostra exatamente como fazer isso com C# e Aspose.OCR. + +Nos próximos minutos, extrairemos quadros do vídeo, executaremos OCR nesses quadros e, finalmente, exibiremos o texto da legenda quadro a quadro. Ao final, você será capaz de **ler texto de vídeo** arquivos — incluindo MP4 — sem precisar procurar ferramentas de terceiros. + +## O que você vai construir + +Vamos criar um pequeno aplicativo de console que: + +1. Decodifica um MP4 (ou qualquer formato suportado) em quadros individuais `Bitmap`. +2. Limita a região de OCR à faixa de legenda para que o motor não seja distraído pela imagem inteira. +3. Processa cada quadro com o `VideoOcrProcessor` da Aspose. +4. Imprime o texto da legenda reconhecido no console. + +Sem enrolação, apenas um exemplo funcional de ponta a ponta que você pode inserir em um projeto real. + +## Pré-requisitos + +- **.NET 6.0** ou posterior (o código também funciona no .NET Framework 4.7+). +- **Aspose.OCR for .NET** – instale via NuGet: `Install-Package Aspose.OCR`. +- Um arquivo de vídeo (MP4 funciona muito bem). +- Uma forma de decodificar quadros de vídeo – a demonstração usa um método placeholder, mas você pode integrar FFmpeg, OpenCV ou qualquer biblioteca que retorne objetos `Bitmap`. + +> Dica profissional: Se você estiver no Windows, o pacote `System.Drawing.Common` funciona bem para `Bitmap`. No Linux/macOS você precisará da dependência nativa `libgdiplus`. + +## Etapa 1 – Extrair Quadros do Vídeo + +O primeiro obstáculo é transformar uma imagem em movimento em imagens estáticas. O método `GetVideoFrames` abaixo foi deixado intencionalmente em branco; substitua-o pelo seu decodificador favorito. Aqui está um esboço rápido usando FFmpeg‑Core (apenas para ilustrar a forma dos dados): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Por que isso importa:** Extrair quadros fornece ao motor de OCR uma imagem estática para trabalhar, o que melhora drasticamente a precisão em comparação com tentar ler diretamente de um fluxo de vídeo. + +## Etapa 2 – Configurar o VideoOcrProcessor + +Agora que temos uma sequência de objetos `Bitmap`, podemos entregá-los ao Aspose.OCR. O `VideoOcrProcessor` nos permite definir uma **Região de Interesse (ROI)** – perfeito para legendas que geralmente ficam na parte superior ou inferior do quadro. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Por que limitar a ROI?** Ao ignorar o resto da imagem, reduzimos o ruído, diminuímos o tempo de processamento e evitamos falsos positivos de gráficos de fundo. + +## Etapa 3 – Executar OCR na Sequência de Quadros + +Com o processador pronto, alimentar os quadros é uma única linha de código. O método `Process` retorna um enumerável de objetos `OcrResult`, cada um contendo o texto reconhecido para seu respectivo quadro. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **O que está acontecendo nos bastidores?** O Aspose.OCR normaliza internamente cada bitmap, executa um reconhecedor baseado em rede neural e, em seguida, pós-processa a saída para melhorar pontuação e quebras de linha. + +## Etapa 4 – Exibir o Texto Extraído + +Finalmente, iteramos sobre os resultados e imprimimos cada linha de legenda. Você também pode gravá-las em um arquivo SRT, em um banco de dados ou enviá-las para um serviço de tradução. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Exemplo Completo Funcional + +Juntando tudo, obtemos um programa de console autônomo: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Saída esperada (exemplo)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Se o OCR tiver dificuldades com um quadro específico, você verá uma string vazia – isso indica que você deve ajustar a ROI ou aumentar a taxa de extração de quadros. + +## Armadilhas Comuns & Como Corrigi‑las + +| Problema | Por que acontece | Correção | +|----------|------------------|----------| +| **Caracteres estranhos** | Quadros de baixa resolução ou compressão pesada | Extraia quadros em uma taxa de bits mais alta, ou aumente a escala do bitmap antes do OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **Nenhum texto retornado** | A ROI não cobre realmente a faixa de legenda | Verifique as coordenadas do retângulo (use uma ferramenta de captura de tela para medir). | +| **Gargalo de desempenho** | Processar todos os quadros a 30 fps é excessivo | Reduza a taxa para 1‑2 fps na maioria dos fluxos de legenda; ainda é possível capturar cada mudança de legenda. | +| **FFmpeg não encontrado** | `ffmpeg.exe` não está no `PATH` | Forneça o caminho completo em `ProcessStartInfo.FileName` ou instale o FFmpeg globalmente. | + +## Expandindo a Solução + +- **Exportar para SRT** – concatene os timestamps com o texto OCR e escreva um arquivo SubRip. +- **Suporte multilíngue** – defina `ocrProcessor.Language = OcrLanguage.Spanish` (ou qualquer idioma suportado). +- **Processamento em tempo real** – canalize quadros diretamente de um stream ao vivo ao invés de ler do disco. + +Todas essas variações ainda giram em torno das ideias principais de **extrair quadros de vídeo**, **ler texto de vídeo**, e **extrair texto de mp4**. + +## Conclusão + +Acabamos de percorrer um fluxo de trabalho completo de **video subtitle ocr** em C#. Ao extrair quadros do vídeo, focar o OCR na faixa de legenda e iterar sobre os resultados, você pode ler **texto de vídeo** de forma confiável em arquivos como MP4. O código está pronto para copiar‑colar, e o design modular permite trocar por qualquer decodificador de quadros que preferir. + +Próximos passos? Tente exportar os resultados para um arquivo SRT, experimente diferentes tamanhos de ROI, ou envie as legendas para uma API de tradução para legendas multilíngues. O céu é o limite depois que você dominar o básico de extração de texto de vídeo. + +Feliz codificação, e que suas legendas estejam sempre cristalinas! + +## O que Você Deve Aprender a Seguir? + +Os tutoriais a seguir cobrem tópicos intimamente relacionados que expandem as técnicas demonstradas neste guia. Cada recurso inclui exemplos de código completos e funcionais com explicações passo a passo para ajudá‑lo a dominar recursos adicionais da API e explorar abordagens alternativas de implementação em seus próprios projetos. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/russian/net/ocr-configuration/_index.md index 2a0ac8c03..dfbdd33bb 100644 --- a/ocr/russian/net/ocr-configuration/_index.md +++ b/ocr/russian/net/ocr-configuration/_index.md @@ -21,7 +21,7 @@ weight: 24 Если вы ищете **как извлечь данные OCR** ​​из изображений в ваших проектах .NET, вы найдете это в нужном месте. Aspose.OCR для .NET выполняет распознавание изображений OCR простым, быстрым и высоконастраиваемым. В этом руководстве мы предлагаем основные схемы построения — работу с архивами, папками, выбор языка и обработку на основе списков — чтобы вы могли уверенно получать текст из изображений. ## Быстрые ответы -- **Что означает «как извлечь OCR»?** Это использование OCR‑движки для чтения и преобразования текста, находящегося на изображении, в редактируемых строках. +- **Что означает «как извлечь OCR»?** Это использование OCR‑движка для чтения и преобразования текста, находящегося на изображении, в редактируемых строках. - **Какая библиотека рекомендуется для .NET?** Aspose.OCR Обеспечивает богатый API для поиска изображений OCR без внешних зависимостей. - **Нужна ли мне лицензия?** Бесплатная пробная версия подходит для измерений; для использования в продаже требуется коммерческая лицензия. - **Какие версии .NET поддерживаются?** .NET Framework4.5+, .NETCore3.1+, .NET5/6/7+. @@ -62,6 +62,8 @@ weight: 24 Откройте мощные возможности OCR с Aspose.OCR для .NET. Бесшовно извлеките текст из изображений. ### [OCROоперация со списком в распознавании изображений OCR](./ocr-operation-with-list/) Расширьте потенциал Aspose.OCR для .NET. Легко выполняйте распознавание изображений OCR со списками. Повышайте продуктивность и извлечение данных в ваших приложениях. +### [Получить версию Aspose OCR в C# – Полное руководство](./get-aspose-ocr-version-in-c-complete-guide/) +Узнайте, как программно определить текущую версию Aspose.OCR в приложениях C#. ### Распространенные случаи использования - **Извлечение текстовых изображений** из отсканированных счетов для автоматического бухгалтерского учета. @@ -102,4 +104,4 @@ A: Да, объект `OcrResult` обеспечивает значения до {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/russian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..fae023314 --- /dev/null +++ b/ocr/russian/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Получите версию Aspose OCR в C# с помощью простого фрагмента кода. Узнайте, + как получить версию библиотеки Aspose OCR, используя OcrEngine.GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: ru +og_description: Быстро получите версию Aspose OCR в C#. Этот учебник точно показывает, + как получить версию библиотеки Aspose OCR с помощью OcrEngine.GetVersion. +og_title: Получите версию Aspose OCR на C# – Полное руководство +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Получить версию Aspose OCR в C# – Полное руководство +url: /ru/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Получить версию Aspose OCR в C# – Полное руководство + +Вы когда‑нибудь задумывались, как **получить версию Aspose OCR** из вашего проекта .NET? Возможно, вы устраняете несоответствие или просто хотите записать точную сборку библиотеки, работающую в продакшене. Какова бы ни была причина, вы попали в нужное место. + +В этом руководстве мы пройдемся по небольшому, автономному C#‑приложению, которое вызывает `OcrEngine.GetVersion()` и выводит результат. К концу вы узнаете не только *как* получить версию, но и *почему* проверка версии может избавить вас от головной боли при обновлении **библиотеки Aspose OCR**. + +## Что вы узнаете + +- Добавить пакет Aspose.OCR NuGet в проект C# +- Использовать метод `OcrEngine.GetVersion()` (точка входа **ocrengine getversion**) +- Обработать возможные исключения и проверить вывод +- Расширить фрагмент для реальных сценариев, таких как логирование или условные переключатели функций + +Предыдущий опыт работы с OCR не требуется — достаточно базовых знаний C# и Visual Studio (или вашего любимого IDE). Поехали. + +--- + +## Шаг 1: Настройка проекта и подключение библиотеки Aspose OCR + +Прежде чем вы сможете вызвать какие‑либо OCR‑API, необходимо добавить **библиотеку Aspose OCR** в ваш проект. + +1. Откройте терминал или консоль диспетчера пакетов в Visual Studio. +2. Выполните следующую команду, чтобы установить последнюю стабильную версию: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Если вы нацеливаетесь на .NET Framework вместо .NET Core, используйте UI NuGet Package Manager и выберите версию, соответствующую вашей среде выполнения. Пакет включает класс `OcrEngine`, который мы будем использовать позже. + +### Почему это важно + +При установке пакета версия сборки на диске может отличаться от версии, которую библиотека сообщает во время выполнения. Запрос версии через код гарантирует, что вы читаете именно ту сборку, которую загрузил CLR, что критично для отладки и аудитов соответствия. + +## Шаг 2: Написать минимальный код для **получения версии Aspose OCR** + +Создайте новое консольное приложение (`dotnet new console -n OcrVersionDemo`) и замените файл `Program.cs` следующим содержимым: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Объяснение каждой части** + +- `using Aspose.OCR;` импортирует пространство имён OCR, позволяя вызывать `OcrEngine`. +- `OcrEngine.GetVersion()` — это статический метод **ocrengine getversion**, возвращающий строку вроде `"24.5.7"`. +- Обёртывание вызова в блок `try/catch` защищает от неожиданных ошибок во время выполнения — возможно, нативные бинарные файлы не найдены на целевой машине. +- Интерполированная строка `$"Aspose OCR version: {version}"` выводит понятную, читаемую строку. + +### Ожидаемый вывод + +При запуске `dotnet run` в папке проекта вы должны увидеть что‑то подобное: + +``` +Aspose OCR version: 24.5.7 +``` + +Если библиотеку не удалось загрузить, ветка ошибки выведет краткое сообщение, помогая быстро локализовать проблему. + +## Шаг 3: Проверить, что версия совпадает с вашей NuGet‑пакетой + +Легко предположить, что установленная версия NuGet — это та, что используется во время выполнения, но особенности среды могут вмешаться. Чтобы убедиться: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Выполнение этого дополнительного фрагмента выведет что‑то вроде: + +``` +Assembly file version: 24.5.7.0 +``` + +Если два значения различаются, возможно, вы загружаете более старый DLL из Global Assembly Cache (GAC) или из предыдущей папки сборки. В этом случае выполните очистку решения (`dotnet clean`) и пересоберите проект. + +## Шаг 4: Добавить проверку версии в производственное логирование + +Большинство реальных приложений не просто выводят информацию в консоль; они записывают её в файл журнала или систему телеметрии. Вот быстрый пример с использованием `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Теперь версия появляется в ваших структурированных логах, её легко отфильтровать по `{Version}` позже. Такой подход особенно полезен, когда у вас несколько микросервисов, каждый из которых может подтягивать потенциально разную DLL OCR. + +## Часто задаваемые вопросы и крайние случаи + +### Что если `GetVersion()` возвращает пустую строку? + +Это обычно указывает на повреждённую установку или отсутствие нативной зависимости. Переустановите пакет NuGet и убедитесь, что `Aspose.OCR.Native.dll` (или соответствующий платформенно‑специфичный бинарный файл) находится рядом с исполняемым файлом. + +### Работает ли метод на .NET Core 2.0? + +Да, **Aspose OCR** поддерживает .NET Standard 2.0 и выше, поэтому любой .NET Core, реализующий этот стандарт, может вызвать `OcrEngine.GetVersion()`. Просто убедитесь, что указали правильные идентификаторы среды выполнения (`win-x64`, `linux-x64` и т.д.), если публикуете автономное приложение. + +### Можно ли получить версию без файла лицензии? + +Абсолютно. `GetVersion()` **не требует** лицензии; он просто сообщает номер сборки библиотеки. Однако попытка выполнить OCR без действующей лицензии приведёт к исключению во время выполнения. Поэтому `try/catch` в нашем примере полезен — он изолирует проверку версии от процесса распознавания. + +## Полный рабочий пример (готов к копированию) + +Ниже представлен весь код программы, готовый к вставке в новый консольный проект. В нём включён необязательный блок логирования, так что вы увидите как вывод в консоль, так и структурированные логи в действии. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Запустите его командой `dotnet run`, и вы увидите две строки, подтверждающие версию, плюс отладочную строку, если включите `LogLevel.Debug`. + +## Заключение + +Мы рассмотрели всё, что нужно, чтобы **получить версию Aspose OCR** в среде C# — от установки **библиотеки Aspose OCR**, вызова метода **ocrengine getversion**, обработки ошибок до внедрения результата в производственное логирование. Обладая этими знаниями, вы теперь можете надёжно проверять точную сборку OCR, используемую вашим приложением, избегать ошибок, связанных с версиями, и удовлетворять требованиям соответствия без лишних усилий. + +Что дальше? Попробуйте сочетать эту проверку версии с реальным вызовом OCR (`OcrEngine` → `RecognizeImage`) и логировать одновременно версию и результат распознавания. Вы также можете изучить шаблон **retrieve aspose version** для других продуктов Aspose (PDF, Slides, Cells), чтобы синхронизировать весь ваш набор библиотек. + +Счастливого кодинга, и пусть ваши OCR‑конвейеры остаются острыми! + +## Что вам стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом руководстве. Каждый ресурс включает полностью работающие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Как получить результаты OCR с Aspose.OCR для .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Извлечение текста из изображения C# с выбором языка с помощью Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Как пакетно обрабатывать изображения OCR со списком в Aspose.OCR для .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/russian/net/ocr-optimization/_index.md index 64f6e406b..e83dcff01 100644 --- a/ocr/russian/net/ocr-optimization/_index.md +++ b/ocr/russian/net/ocr-optimization/_index.md @@ -74,6 +74,9 @@ weight: 25 ### [Сохранение многостраничных результатов как документ в распознавании OCR](./save-multipage-result-as-document/) Раскройте потенциал Aspose.OCR для .NET. Легко сохраняйте многостраничные результаты OCR в виде документов с помощью этого всестороннего пошагового руководства. +### [Пример Aspose OCR на C# – Включить GPU, установить ограничение памяти и обрабатывать TIF‑изображения](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Узнайте, как включить ускорение GPU, задать лимит памяти и обрабатывать TIF‑файлы с помощью Aspose OCR в C#. + ## Часто задаваемые вопросы **Q: Могу ли я извлекать текст из файлов изображений, содержащих несколько языков?** diff --git a/ocr/russian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/russian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..ae0cc0107 --- /dev/null +++ b/ocr/russian/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,288 @@ +--- +category: general +date: 2026-06-03 +description: Пример Aspose OCR на C#, показывающий, как установить ограничение памяти + GPU, загрузить изображение для OCR и распознать текст из файлов TIF с полным кодом + и советами. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: ru +og_description: 'Изучите полный пример Aspose OCR на C#: включите GPU, задайте ограничение + памяти GPU, загрузите изображение для OCR и распознайте текст из файлов TIF. Полный + код включён.' +og_title: Пример Aspose OCR на C# – ускорение с помощью GPU, ограничение памяти и + обработка TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Пример Aspose OCR на C# – включение GPU, установка ограничения памяти и обработка + TIF‑изображений +url: /ru/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – Включить GPU, установить ограничение памяти и обрабатывать TIF‑изображения + +Задумывались ли вы когда‑нибудь, как выжать максимум производительности из кода **Aspose OCR C# example**, работая с огромными сканами TIFF? Вы не одиноки. Во многих реальных проектах — например, оцифровке архивов или извлечении данных из высокоразрешённых чеков — узким местом является не сам алгоритм OCR, а использование аппаратных ресурсов. + +Вот в чём дело: Aspose OCR поддерживает ускорение с помощью GPU, но вам нужно явно указать, сколько памяти он может использовать, загрузить правильный тип изображения и, наконец, извлечь распознанный текст из файла .tif. Этот учебник проведёт вас через каждый шаг, от установки SDK до настройки параметров GPU, чтобы вы могли выполнять OCR на молниеносной скорости, не перегружая память вашего GPU. + +Мы также добавим несколько сценариев «что если» — например, обработку многостраничных TIFF или переход на CPU, если GPU недоступен — чтобы у вас получилось надёжное решение, а не просто одноразовый фрагмент кода. + +## Что вам понадобится + +Прежде чем мы начнём, убедитесь, что на вашем компьютере есть следующее: + +| Требование | Почему это важно | +|------------|-------------------| +| **.NET 6 SDK** (or later) | Aspose OCR ориентирован на .NET Standard 2.0+, поэтому любой современный .NET‑версии подходит. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | Основная библиотека, предоставляющая `OcrEngine`, `GpuSettings`, etc. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Требуется для ускорения с помощью GPU; SDK проверит наличие совместимого драйвера во время выполнения. | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | Без достаточного объёма памяти движок может тихо переключиться на CPU. | +| A **high‑resolution TIFF** image you want to process | Aspose OCR может читать практически любой растровый формат, но TIF часто используется для сканов. | +| Visual Studio 2022 (or any editor you like) | Для сборки и отладки проекта C#. | + +Если чего‑то не хватает, код всё равно скомпилируется, но вы не увидите ожидаемого прироста производительности. + +## Шаг 1: Создать движок Aspose OCR C# Example + +Первое, что делается в каждом **Aspose OCR C# example**, — это создание экземпляра OCR‑движка. Представьте `OcrEngine` как режиссёра фильма — он координирует всё, от загрузки изображения до извлечения текста. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro tip:** Если вы планируете обрабатывать много изображений подряд, держите один `OcrEngine` живым. Пересоздание его для каждого изображения добавляет накладные расходы, которые могут затмить время OCR. + +## Шаг 2: Установить ограничение памяти GPU (и включить ускорение) + +Теперь переходим к части, которая часто ставит людей в тупик: **установить ограничение памяти GPU**. По умолчанию Aspose OCR пытается использовать столько видеопамяти, сколько может, что на общем рабочем месте может «голодать» другие приложения. Объект `GpuSettings` позволяет ограничить выделение. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Почему устанавливать ограничение памяти? + +- **Stability:** Предотвращает сбои из‑за нехватки памяти при обработке гигантских изображений. +- **Co‑existence:** Позволяет другим приложениям, использующим GPU (например, модели TensorFlow), работать одновременно. +- **Predictability:** Делает тестирование производительности воспроизводимым, поскольку GPU не будет начинать свопинг. + +Если опустить `MemoryLimitMb`, Aspose выделит столько памяти, сколько посчитает нужным, что может быть приемлемо на выделенном сервере вывода, но рискованно на ноутбуке разработчика. + +## Шаг 3: Загрузить изображение для OCR + +Загрузка правильного формата файла — следующий важный шаг. Метод `OcrImage.FromFile` автоматически определяет тип изображения, но всё равно следует проверить, существует ли файл и поддерживается ли его вариант TIFF (например, сжатие LZW или CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Обработка многостраничных TIFF + +Если ваш TIFF содержит несколько страниц, Aspose OCR по умолчанию прочитает только первую. Чтобы обработать все страницы, можно перебрать `image.Pages` (доступно в более новых версиях SDK) и передавать каждую страницу движку отдельно. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Приведённый выше фрагмент демонстрирует шаблон **load image for OCR**, который работает как с одностраничными, так и с многостраничными файлами. + +## Шаг 4: Распознать текст из TIF (или любого растра) + +Теперь, когда изображение находится в памяти, мы просим Aspose выполнить свою магию. Метод `Recognize` возвращает `OcrResult`, который содержит простой текст, оценки уверенности и даже информацию о ограничивающих прямоугольниках, если она нужна. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Почему это хорошо работает с TIF + +- **Lossless compression:** TIFF часто хранит необработанные пиксельные данные, обеспечивая OCR‑движку наивысшую точность. +- **Multiple color spaces:** Aspose может работать с градациями серого, RGB или даже CMYK‑TIFF без дополнительного кода преобразования. + +Если необходимо настроить языковые пакеты (например, французский или японский), установите `ocrEngine.Settings.Language = "fr"` перед вызовом `Recognize`. + +## Шаг 5: Вывести распознанный текст + +Наконец, выводим текст в консоль. В реальном приложении вы можете записать его в базу данных, JSON‑файл или передать строку в последующий конвейер NLP. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Ожидаемый вывод + +Запуск программы на чистом скане печатной страницы с разрешением 300 dpi обычно даёт примерно следующее: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Если изображение размыто или ограничение памяти GPU слишком низкое, вы можете увидеть искажённые символы или усечённый результат. Уменьшение `MemoryLimitMb` ниже объёма изображения (обычно ~1 ГБ для TIFF 6000×8000 пикселей) может привести к автоматическому переключению движка на CPU. + +## Полный рабочий пример + +Ниже представлен полный готовый к запуску пример программы. Скопируйте и вставьте его в новый проект Console App, замените `YOUR_DIRECTORY/large_photo.tif` на путь к вашему TIFF‑файлу и нажмите **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Быстрый чек‑лист + +- ✅ **Aspose OCR C# example** скомпилирован без ошибок. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** установлен в 2048 MB. +- ✅ **Image loaded** из TIF‑файла. +- ✅ **Text recognized** и выведен. + +## Распространённые подводные камни и как их избежать + +| Симптом | Вероятная причина | Решение | +|---------|-------------------|---------| +| `System.DllNotFoundException: cudart64_110.dll` | Среда выполнения CUDA не установлена или версия не совпадает. | Установите CUDA 11.x (или 12.x), соответствующую вашему драйверу. | +| OCR returns empty string | Изображение слишком тёмное или DPI < 150. | Предобработайте с помощью `image.AdjustContrast()` или пересчитайте до 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` слишком низок для изображения. | Увеличьте ограничение или разбейте изображение на плитки с помощью `image.Crop`. | +| `Unsupported image format` error | TIFF использует экзотическое сжатие (например, JPEG‑2000). | Конвертируйте TIFF в поддерживаемый формат с помощью ImageMagick перед OCR. | + +## Расширение демонстрации + +Теперь, когда у вас есть надёжный **aspose ocr c# example**, вы можете захотеть исследовать: + +- **Batch processing:** Перебор папки с TIF‑файлами, запись каждого результата в файл `.txt`. +- **Language packs:** `ocrEngine.Settings.Language = "es"` для испанского или загрузка пользовательских словарей. +- **Bounding boxes:** Используйте `ocrResult.Regions` для получения координат каждого слова — удобно для инструментов редактирования. +- **CPU fallback:** Оберните блок GPU в try/catch; при ошибке установите `ocrEngine.Settings.Gpu.Enable = false` и повторите попытку. + +Эти расширения сохраняют основной шаблон, одновременно добавляя ценность для конкретных случаев использования‑ + +## Что следует изучить дальше? + +Следующие учебники охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Извлечение текста из изображения с помощью Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Извлечение текста из изображения – оптимизация OCR с Aspose.OCR для .NET](/ocr/english/net/ocr-optimization/) +- [Извлечение текста из изображения C# с выбором языка с использованием Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/skew-angle-calculation/_index.md b/ocr/russian/net/skew-angle-calculation/_index.md index 54d92e3ba..701aaec5a 100644 --- a/ocr/russian/net/skew-angle-calculation/_index.md +++ b/ocr/russian/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ url: /ru/net/skew-angle-calculation/ Раскройте возможности Aspose.OCR для .NET, надежного решения для распознавания изображений. Узнайте, как легко вычислять углы перекоса. ### [Вычислить угол наклона по URI в распознавании изображений OCR](./calculate-skew-angle-from-uri/) Изучите Aspose.OCR для .NET, чтобы легко вычислять углы перекоса при распознавании изображений OCR. Усовершенствуйте свои проекты с точностью и эффективностью. +### [Учебник по обработке повернутых документов OCR – автоматическое исправление перекоса и вращения в C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Узнайте, как автоматически исправлять перекос и вращение изображений в OCR с помощью Aspose.OCR для .NET в C#. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/russian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..32ac6c3cf --- /dev/null +++ b/ocr/russian/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: Учебник по OCR вращённого документа, показывающий, как автоматически + исправлять наклон и определять поворот с помощью Aspose OCR в C#. Учитесь пошагово + с полным кодом. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: ru +og_description: Учебник по OCR вращённого документа учит, как автоматически исправлять + наклон и определять поворот с помощью Aspose OCR в C#. Следуйте полному руководству. +og_title: Учебник по OCR вращённого документа – автоматическое исправление наклона + и поворота в C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Учебник по OCR вращённого документа – автоматическое исправление наклона и + поворота в C# +url: /ru/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Rotated Document Tutorial – Полное руководство для разработчиков C# + +Ever stumbled upon an **ocr rotated document tutorial** when a scanned form came in sideways or slanted? You’re not alone. Those wonky images can ruin a clean text extraction, but the good news is that Aspose OCR can straighten things out for you automatically. + +В этом пошаговом руководстве мы создадим `OcrEngine`, включим **automatic skew correction** и **auto detect rotation**, запустим движок на повернутом изображении и выведем чистый текст. К концу вы точно поймёте, почему каждый параметр важен, как настроить их для граничных случаев, и у вас будет готовая к запуску программа на C#. + +## Что вы узнаете + +* Как установить и подключить **Aspose OCR** в проект .NET. +* Почему включение `AutoCorrectSkew` и `AutoDetectRotation` является ключом к надёжному **ocr rotated document tutorial**. +* Как загрузить любое изображение (JPG, PNG, TIFF) и позволить движку выполнить тяжёлую работу. +* Советы по работе с многостраничными PDF, сканами низкого разрешения и пользовательскими языковыми пакетами. + +> **Prerequisites:** Visual Studio 2022 (или любой IDE C#), .NET 6+ runtime и действующая лицензия Aspose OCR (или бесплатная пробная версия). Предыдущий опыт работы с OCR не требуется. + +--- + +## Шаг 1 – Установить Aspose OCR и настроить проект + +Сначала самое главное. Получите пакет NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Если вы используете пробную лицензию, поместите файл `Aspose.OCR.lic` в ту же папку, что и ваш исполняемый файл, или зарегистрируйте её программно с помощью `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Создайте новое консольное приложение: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Теперь у вас чистый лист для нашего **ocr rotated document tutorial**. + +## Шаг 2 – Инициализировать OCR‑движок + +Движок — сердце процесса. Считайте его швейцарским ножом для извлечения текста; вам просто нужно указать, какие функции включить. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Почему эти настройки?** +* `AutoCorrectSkew` анализирует базовую линию символов и поворачивает изображение настолько, чтобы строки стали горизонтальными. +* `AutoDetectRotation` проверяет общую ориентацию (0°, 90°, 180°, 270°) и переворачивает страницу, если она вверх ногами. Без этого движок будет читать «pɹᴉʍ» вместо «word». + +## Шаг 3 – Загрузить изображение для обработки + +Aspose OCR работает с любым распространённым растровым форматом. Замените путь‑заполнитель реальным расположением вашего повернутого формуляра. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** Если вы получаете многостраничный TIFF, используйте `OcrImage.FromMultiPageTiff(filePath)` и перебирайте `image.Pages`. + +## Шаг 4 – Запустить распознавание + +Теперь движок делает волшебство. Сначала он выпрямит изображение (благодаря нашим флагам skew/rotation), а затем извлечёт символы. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Если вам нужна поддержка языков, отличных от английского, задайте её перед вызовом `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Шаг 5 – Вывести распознанный текст + +Наконец, выведите чистый текст в консоль — или перенаправьте его в файл, базу данных, что угодно, в зависимости от вашего рабочего процесса. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Expected output** (при условии, что пример изображения содержит «Invoice #1234»): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Обратите внимание, как текст отображается корректно, несмотря на то, что исходное изображение было повернуто на 90° и слегка наклонено. + +--- + +## Обработка распространённых проблем + +| Issue | Why it Happens | Fix | +|------|----------------|-----| +| **Пустой вывод** | Коррекция наклона отключена или изображение слишком тёмное. | Включите `AutoCorrectSkew` (уже включено) и увеличьте контраст изображения с помощью `image.AdjustContrast(1.2)`. | +| **Неправильные символы** | Неправильная настройка языка. | Установите `ocrEngine.Settings.Language` в соответствие с языком документа. | +| **Замедление при больших PDF** | Движок обрабатывает каждую страницу последовательно. | Используйте `Parallel.ForEach` на `image.Pages`, чтобы задействовать многоядерные процессоры. | +| **Исключение лицензии** | Срок пробной лицензии истёк. | Получите постоянную лицензию или соблюдайте ограничения пробной версии (5 страниц за запуск). | + +## Профессиональные советы для надёжного OCR Rotated Document Tutorial + +* **Batch processing:** Оберните весь процесс в метод, принимающий путь к папке, перебирающий каждое изображение и записывающий каждый результат в файл `.txt`. +* **Pre‑processing:** Иногда шумный скан выигрывает от применения `image.Denoise()` перед распознаванием. +* **Post‑processing:** Используйте регулярные выражения для очистки типичных ошибок OCR, например заменяйте «0» на «O» только когда он окружён буквами. +* **Logging:** Aspose OCR предоставляет `ocrEngine.Logger` — подключите его к файловому логгеру, чтобы фиксировать предупреждения о низких уровнях уверенности. + +## Полный, готовый к запуску код + +Сохраните следующее как `Program.cs` в вашем консольном проекте. Он включает все шаги, комментарии и небольшую вспомогательную функцию для пакетной обработки. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Запустите его: + +```bash +dotnet run +``` + +Вы должны увидеть очищенный текст, выведенный в консоль, что доказывает, что наш **ocr rotated document tutorial** работает от начала до конца. + +## Заключение + +Теперь у вас есть полное **ocr rotated document tutorial**, которое автоматически исправляет наклон, определяет ориентацию и извлекает чистый текст с помощью Aspose OCR в C#. Главный вывод? Включение `AutoCorrectSkew` **и** `AutoDetectRotation` превращает безнадёжно наклонённый скан в полностью читаемый вывод всего несколькими строками кода. + +Отсюда вы можете расширить процесс до пакетных заданий, интегрировать языковые пакеты или передавать результаты в последующие аналитические конвейеры. Хотите подробнее изучить **automatic skew correction**? Ознакомьтесь с API предобработки изображений Aspose или поэкспериментируйте с пользовательскими пороговыми значениями для шумных сканов. + +Есть вопросы по работе с PDF, многостраничными TIFF или интеграции с Azure Functions? Оставьте комментарий, и удачной разработки! + +## Что вам стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полностью рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [режим документа OCR – Detect Areas Mode в распознавании изображений OCR](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Извлечение текста из изображения C# с выбором языка с помощью Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Оптическое распознавание символов](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/russian/net/text-recognition/_index.md index cbc7a99c9..b8d479fd8 100644 --- a/ocr/russian/net/text-recognition/_index.md +++ b/ocr/russian/net/text-recognition/_index.md @@ -49,15 +49,26 @@ url: /ru/net/text-recognition/ Изучите Aspose.OCR для .NET, мощное решение OCR для плавного распознавания текста на изображениях. ### [Получить результат в формате JSON в распознавании изображений OCR](./get-result-as-json/) Раскройте возможности Aspose.OCR для .NET. Научитесь легко получать результаты оптического распознавания символов в формате JSON. Улучшите распознавание изображений с помощью этого пошагового руководства. +### [Как использовать Aspose: преобразовать изображение в HTML с OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Преобразуйте изображения в HTML с помощью OCR Aspose, получая точный текст и структуру в веб-формате. ### [Режим OCR Detect Areas в распознавании изображений OCR](./ocr-detect-areas-mode/) Усовершенствуйте свои .NET-приложения с помощью Aspose.OCR для эффективного распознавания текста на изображениях. Изучите режим обнаружения областей OCR для получения точных результатов. ### [Распознать PDF в распознавании изображений OCR](./recognize-pdf/) Раскройте потенциал оптического распознавания символов в .NET с помощью Aspose.OCR. Извлекайте текст из PDF-файлов без особых усилий. Загрузите сейчас и получите беспрепятственную интеграцию. +### [Выполнить OCR PDF с Aspose OCR – полное руководство на C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Полное пошаговое руководство по выполнению OCR PDF с помощью Aspose OCR на C#. ### [Распознать таблицу в распознавании изображений OCR](./recognize-table/) Раскройте потенциал Aspose.OCR для .NET с помощью нашего подробного руководства по распознаванию таблиц в распознавании изображений OCR. +### [Выполнить OCR изображения с Aspose OCR – руководство на хинди](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Изучите, как с помощью Aspose OCR выполнить распознавание текста на изображениях с поддержкой хинди. +### [Выполнить OCR изображения и обнаружить орфографические ошибки в C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Научитесь выполнять OCR изображения и выявлять ошибочно написанные слова с помощью Aspose.OCR в C#. +### [OCR субтитров видео на C# – Полное руководство](./video-subtitle-ocr-in-c-complete-guide/) +Полное руководство по использованию Aspose.OCR в C# для распознавания субтитров из видеофайлов. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/russian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..3b7a26eb5 --- /dev/null +++ b/ocr/russian/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,281 @@ +--- +category: general +date: 2026-06-03 +description: Как использовать Aspose для преобразования изображения в HTML и извлечения + текста из изображения на C#. Узнайте, как быстро генерировать HTML из изображения + и выполнять OCR изображения в HTML. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: ru +og_description: Как использовать Aspose для преобразования изображения в HTML, извлечения + текста из изображения и генерации HTML из изображения с помощью OCR в C#. Следуйте + этому полному руководству. +og_title: 'Как использовать Aspose: преобразовать изображение в HTML с помощью OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Как использовать Aspose: преобразовать изображение в HTML с помощью OCR' +url: /ru/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как использовать Aspose: Преобразовать изображение в HTML с OCR + +Когда‑то задавались вопросом **как использовать Aspose**, чтобы превратить отсканированную картинку в аккуратный HTML? Возможно, у вас есть страница журнала, чек или рукописная записка, и вам нужно сохранить текст и макет для публикации в вебе. Хорошая новость: не требуется писать собственный парсер или возиться с низкоуровневой обработкой изображений — Aspose.OCR сделает всю тяжёлую работу за вас. + +В этом руководстве мы пройдём через **полный, готовый к запуску пример**, который показывает, как **преобразовать изображение в HTML**, **извлечь текст из изображения** и **сгенерировать HTML из изображения** с помощью библиотеки Aspose OCR на C#. К концу вы получите небольшое консольное приложение, которое создаёт HTML‑файл с сохранённым оригинальным макетом страницы, готовый к размещению на любом сайте. + +## Требования + +Прежде чем приступить, убедитесь, что на вашем компьютере установлено следующее: + +- **.NET 6.0 SDK** или новее (код работает как с .NET Core, так и с .NET Framework). +- **Visual Studio 2022** (или любой другой редактор). +- **Aspose.OCR for .NET** — установите через NuGet: `dotnet add package Aspose.OCR`. +- Файл изображения (JPEG/PNG), который вы хотите преобразовать, например, `magazine_page.jpg`. + +Дополнительные файлы конфигурации не требуются; библиотека поставляется со всеми необходимыми компонентами для OCR и генерации HTML‑макета. + +## Шаг 1: Создание проекта и добавление Aspose.OCR + +Сначала создайте новый консольный проект и подключите пакет Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Совет:** Если вы используете Visual Studio, просто щёлкните правой кнопкой мыши по проекту → *Manage NuGet Packages* → найдите **Aspose.OCR** и установите его. Этот шаг гарантирует, что вы сможете **ocr image to html** без отсутствующих ссылок. + +## Шаг 2: Инициализация OCR‑движка + +Ядром процесса является класс `OcrEngine`. Считайте его «мозгом», который читает картинку и решает, как вывести результат. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Здесь мы создаём экземпляр `OcrEngine`. Для бесплатной версии передавать учётные данные не требуется; библиотека использует встроенные модели распознавания. + +## Шаг 3: Загрузка исходного изображения + +Далее указываем движку файл, который нужно обработать. Aspose предоставляет удобный метод `OcrImage.FromFile`, поддерживающий большинство форматов изображений. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Замените `YOUR_DIRECTORY` на абсолютный или относительный путь к вашему изображению. Если файл находится в той же папке, что и исполняемый файл, можно просто использовать `"magazine_page.jpg"`. + +## Шаг 4: Распознавание и запрос HTML с макетом + +Это сердце руководства. Передавая `OutputFormat.HtmlWithLayout`, мы просим Aspose **generate HTML from image**, сохраняя оригинальное расположение блоков текста, изображений и таблиц. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Свойство `recognitionResult.Text` теперь содержит полноценный HTML‑документ. Если нужен только обычный текст, можно использовать `OutputFormat.Text`, но мы сосредоточены на **convert image to html** с сохранением макета. + +## Шаг 5: Сохранение HTML‑файла + +Наконец, записываем строку HTML на диск. Полученный файл готов к открытию в любом браузере. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Запуск программы создаст `magazine.html`. Откройте его, и вы увидите текст оригинальной страницы, расположенный точно так же, как на исходном изображении — идеально для архивирования или публикации в вебе. + +## Полный рабочий пример + +Ниже приведена **полная, готовая к копированию** программа. Ни один фрагмент не опущен, так что вы можете сразу её собрать и запустить после указания правильных путей. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Ожидаемый результат + +При открытии `magazine.html` в браузере вы должны увидеть нечто подобное (упрощённо для иллюстрации): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Точные атрибуты `style` будут отличаться в зависимости от исходного изображения, но структура гарантирует, что **extract text from image** и **generate html from image** происходят в одном бесшовном шаге. + +## Часто задаваемые вопросы и особые случаи + +### Что делать, если изображение низкого разрешения? + +Aspose.OCR работает лучше всего с изображениями минимум **300 DPI**. Если ваш файл размытый, попробуйте предварительно обработать его с помощью библиотеки улучшения изображений (например, ImageSharp) перед передачей в OCR‑движок. Низкое качество может повлиять как на точность **extract text from image**, так и на достоверность генерируемого HTML‑макета. + +### Можно ли задать язык распознавания? + +Да. Установите свойство `Language` у `OcrEngine` перед вызовом `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Это повышает точность распознавания при работе с неанглийскими символами. + +### Как получить обычный текст вместо HTML? + +Если нужен лишь сырой текст, замените `OutputFormat.HtmlWithLayout` на `OutputFormat.Text`. Тогда `recognitionResult.Text` будет содержать только извлечённые символы. + +### Можно ли встроить изображения в генерируемый HTML? + +Aspose.OCR умеет встраивать оригинальное изображение как data‑URI в формате base‑64, если использовать `OutputFormat.HtmlWithLayoutAndImages`. Это удобно, когда нужен один HTML‑файл без внешних ресурсов. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Как обрабатывать большие партии файлов? + +Для пакетной обработки оберните логику в цикл `foreach` по списку путей к файлам. Повторное использование одного экземпляра `OcrEngine` уменьшает накладные расходы и ускоряет конвейер **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Советы для production‑кода + +- **Освобождение ресурсов**: и `OcrEngine`, и `OcrImage` реализуют `IDisposable`. Оборачивайте их в `using`, чтобы своевременно освобождать нативную память. +- **Обработка ошибок**: ловите `IOException` для проблем с файлами и `OcrException` для ошибок распознавания. +- **Производительность**: при обработке множества изображений рассмотрите возможность включения **parallelism** (`Parallel.ForEach`), но учитывайте нагрузку на CPU — OCR требует значительных вычислительных ресурсов. +- **Логирование**: интегрируйте логгер (например, Serilog) для записи оценок уверенности OCR (`recognitionResult.Confidence`) в целях контроля качества. + +## Заключение + +Мы только что рассмотрели, **как использовать Aspose** для **convert image to HTML**, **extract text from image** и **generate HTML from image** в несколько простых шагов. Полный пример кода показывает, как **ocr image to html** с сохранением макета, что делает его надёжной основой для любого проекта по оцифровке документов. + +Дальше вы можете: + +- Поэкспериментировать с различными вариантами `OutputFormat`, чтобы подобрать оптимальный для ваших нужд. +- Скомбинировать полученный HTML с CSS‑фреймворком для адаптивного оформления. +- Передать извлечённый текст в поисковый индекс или в конвейер машинного обучения. + +Попробуйте, настройте параметры и убедитесь, как легко Aspose превращает картинки в готовый к вебу контент. Если возникнут вопросы, оставляйте комментарий — приятного кодинга! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + + +## Что изучать дальше? + + +Следующие руководства охватывают тесно связанные темы, расширяющие техники, продемонстрированные в этом гайде. Каждый ресурс содержит полностью рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы в ваших проектах. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/russian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..099a81e50 --- /dev/null +++ b/ocr/russian/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-03 +description: Выполните OCR изображения и извлеките текст из него с помощью Aspose.OCR. + Узнайте, как обнаруживать орфографические ошибки и получать предложения по их исправлению + в одном демонстрационном примере на C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: ru +og_description: Выполните OCR изображения, чтобы извлечь текст, затем обнаружьте орфографические + ошибки и получите предложения по исправлению с помощью Aspose.OCR в C#. +og_title: Выполнить OCR изображения и обнаружить орфографические ошибки в C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Выполнить OCR изображения и обнаружить орфографические ошибки в C# +url: /ru/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Выполнение OCR на изображении и обнаружение орфографических ошибок в C# + +Задумывались когда‑нибудь, как **perform OCR on image** файлы, не теряя волосы? Вы не одиноки. Будь то оцифровка старых писем, сканирование чеков или создание умного документооборота, извлечение чистого текста из изображений — первая преграда. Хорошие новости? С Aspose.OCR вы можете собрать решение за считанные минуты, а бонус в том, что вы также можете **detect misspelled words** и **get spelling suggestions** за один запуск. + +В этом руководстве мы пройдем через полностью готовое к запуску консольное приложение C#, которое **extracts text from image**, запускает английский spell‑checker и выводит каждую ошибку с удобными вариантами исправления. К концу вы точно будете знать **how to extract text**, как подключить API проверки орфографии и как выглядит ожидаемый вывод в консоли. + +## Что вы построите + +- Загрузить bitmap (или PNG), содержащий типографические ошибки. +- Запустить Aspose.OCR для **perform OCR on image** и получить необработанные строковые данные. +- Инициализировать встроенный английский spell‑checker. +- **Detect misspelled words** и **get spelling suggestions** для каждого. +- Вывести аккуратный отчет в консоль. + +Без внешних сервисов, без сложных HTTP‑запросов — только один пакет NuGet и несколько строк кода. + +## Требования + +- .NET 6.0 SDK или новее (код также работает на .NET Framework 4.7+). +- Visual Studio 2022 (или любой другой редактор). +- NuGet‑пакет Aspose.OCR для .NET (`Aspose.OCR`). +- Файл изображения (`letter_with_typos.png`), размещённый в месте, откуда его можно ссылаться из проекта. + +Если вы никогда не использовали Aspose раньше, не волнуйтесь — установка пакета так же проста, как выполнить: + +```bash +dotnet add package Aspose.OCR +``` + +Теперь давайте погрузимся в реализацию. + +## Шаг 1: Создание проекта и установка Aspose.OCR + +Создайте новый консольный проект и подключите библиотеку OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +После завершения восстановления откройте `Program.cs`. Мы позже заменим содержимое по умолчанию полным демонстрационным кодом, но сначала расскажем, почему каждый неймспейс важен. + +- `Aspose.OCR` — ядро OCR‑движка и обработка изображений. +- `Aspose.OCR.SpellCheck` — утилиты проверки орфографии, поставляемые с библиотекой. +- `System` — стандартные базовые классы .NET (например, `Console`). + +## Шаг 2: Загрузка изображения и выполнение OCR на изображении + +Первая реальная работа — передать изображение OCR‑движку. Aspose.OCR читает множество форматов (PNG, JPEG, TIFF). Вот фрагмент кода, который делает всю тяжёлую работу: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Почему это важно:** `OcrImage.FromFile` абстрагирует детали уровня пикселей, а `OcrEngine.Recognize` запускает обученную нейронную модель, переводящую визуальные глифы в символы Unicode. Свойство `ocrResult.Text` теперь содержит необработанную строку — именно то, что вам нужно для **extract text from image**. +> **Полезный совет:** Если ваше изображение содержит несколько языков, вы можете установить `ocrEngine.Language = OcrLanguage.Multilingual;` перед вызовом `Recognize`. + +## Шаг 3: Инициализация английского Spell‑Checker + +Aspose.OCR поставляется со встроенным движком проверки орфографии, который сразу понимает английский. Инициализация занимает одну строку: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Почему этот шаг важен:** Вывод OCR может включать неправильно распознанные символы (например, “l” vs “1”) или реальные опечатки из исходного документа. Проверка орфографии просканирует строку, найдет подозрительные токены и предложит альтернативы. + +## Шаг 4: Обнаружение орфографических ошибок и получение предложений по исправлению + +Теперь передаем текст OCR в проверщик: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` — это коллекция, где каждая запись содержит ошибочное слово и массив возможных исправлений. + +## Шаг 5: Вывод результатов + +Наконец, мы проходим по коллекции и выводим человекочитаемый отчет: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Ожидаемый вывод в консоль + +Предположим, что `letter_with_typos.png` содержит предложение: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Запуск демо‑примера выдаст примерно следующее: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Обратите внимание, как каждая опечатка сопоставлена с несколькими правдоподобными исправлениями — именно то, что нужно при построении удобного пользовательского интерфейса исправления. + +## Полный рабочий пример + +Ниже представлена **полная, готовая к копированию** программа. Замените `YOUR_DIRECTORY` реальным путём к вашему файлу изображения. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Возможные граничные случаи** +> - **Empty Image:** Если OCR‑движок возвращает пустую строку, `spellChecker.Check` просто вернёт пустую коллекцию — без сбоя. +> - **Non‑English Text:** Замените `OcrLanguage.English` на `OcrLanguage.French` (или любой поддерживаемый язык), чтобы **detect misspelled words** в других локалях. +> - **Large Documents:** Для многостраничных PDF вы будете проходить по каждой странице, выполнять OCR, а затем агрегировать результаты перед проверкой орфографии. + +## Визуальный обзор (Alt‑текст изображения) + +![Схема, показывающая поток выполнения OCR на изображении, извлечение текста из изображения и последующее обнаружение орфографических ошибок с предложениями исправлений](perform-ocr-on-image-flow.png) + +*Эта схема иллюстрирует сквозной конвейер: изображение → OCR‑движок → необработанный текст → проверка орфографии → предложения.* + +## Часто задаваемые вопросы и профессиональные советы + +| Question | Answer | +|----------|--------| +| **Нужен ли мне доступ к интернету?** | Нет. Aspose.OCR работает полностью локально; идеально подходит для офлайн‑режима или защищённых окружений. | +| **Насколько точен проверщик орфографии?** | Он использует словарь из ~150 000 английских слов и нечеткое сопоставление, поэтому большинство распространённых опечаток обнаруживаются. | +| **Могу ли я настроить словарь?** | Да. `SpellChecker.AddUserDictionary("custom.txt")` позволяет загрузить термины, специфичные для домена (например, названия продуктов). | +| **Что делать, если изображение наклонено?** | OCR‑движок автоматически определяет ориентацию, но в сложных случаях можно вручную вызвать `ocrEngine.ImagePreprocessing.Rotate(angle)`. | +| **Можно ли подсветить предложения в пользовательском интерфейсе?** | После получения коллекции `misspellings` вы можете сопоставить каждое `entry.Word` с его позицией в `ocrResult.Text` и подчеркнуть его в RichTextBox или веб‑просмотре. | + +## Заключение + +Мы только что продемонстрировали вам **how to perform OCR on image**, **extract text from image**, а затем **detect misspelled words**, получая **get spelling suggestions** — всё это с помощью компактного консольного приложения C#. Основная идея проста: позволить Aspose.OCR выполнить тяжёлую работу по распознаванию символов, а затем встроенному проверщику орфографии очистить вывод. Отсюда вы можете расширить демонстрацию до полноценного сервиса обработки документов, интегрировать его с веб‑API или подключить к настольному редактору. + +Готовы к следующему шагу? Попробуйте переключить язык на испанский, обработать многостраничный PDF или создать небольшое WPF‑приложение, позволяющее пользователям кликать по слову, чтобы принять предложение. Основные блоки уже готовы — остаётся только экспериментировать. + +Если вы столкнулись с проблемами или у вас есть идеи для расширений, оставьте комментарий ниже. Счастливого кодинга! + +## Что вам стоит изучить дальше? + +Следующие руководства охватывают тесно связанные темы, построенные на техниках, продемонстрированных в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в собственных проектах. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/russian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..b9b82f874 --- /dev/null +++ b/ocr/russian/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: Выполните распознавание текста на изображении с помощью Aspose OCR в + C#. Узнайте, как загрузить изображение для OCR и извлечь хинди‑текст из изображения + офлайн, используя пошаговый код. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: ru +og_description: Выполните OCR изображения с помощью Aspose OCR на C#. Этот учебник + демонстрирует, как загрузить изображение для OCR и извлечь хинди‑текст из изображения + в автономном режиме, включая готовый к запуску код. +og_title: Выполнить OCR на изображении – руководство по Aspose OCR на хинди +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Выполнить OCR изображения с помощью Aspose OCR – руководство на хинди +url: /ru/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Выполнение OCR на изображении с Aspose OCR – Руководство на хинди + +Когда‑нибудь вам нужно было **выполнить OCR на изображении** файлов, но вы не знали, как получить из них хинди‑символы? Вы не одиноки — многие разработчики сталкиваются с этой проблемой, когда впервые пытаются читать нелатинские скрипты. Хорошая новость в том, что Aspose OCR делает это довольно просто, и вы можете даже делать это полностью офлайн. + +В этом руководстве мы **загрузим изображение для OCR**, укажем движку ваши локальные языковые пакеты и, наконец, **извлечём хинди‑текст из изображения** без обращения к интернету. К концу вы получите готовое к запуску консольное приложение C#, которое считывает хинди‑чек и выводит текст в консоль. + +## Что вам понадобится + +- **.NET 6.0** или новее (код также работает на .NET Framework 4.7+) +- **Aspose.OCR for .NET** пакет NuGet + `dotnet add package Aspose.OCR` +- Папка, содержащая **офлайн‑ресурсы хинди** (скачайте их с портала Aspose) +- Файл изображения с хинди‑текстом, например `receipt_hindi.png` + +Вот и всё — без внешних сервисов, без API‑ключей, просто прямой код. + +## Выполнение OCR на изображении — пошаговая реализация + +Ниже мы разбиваем процесс на семь чётких шагов. Каждый шаг объясняет **почему** он важен, а не только **что** нужно написать. + +### Шаг 1: Создать экземпляр OCR‑движка + +Движок — это сердце Aspose OCR. Его создание даёт вам доступ ко всем настройкам, которые вы будете менять позже. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Почему?** +> Без `OcrEngine` у вас нет объекта, на котором можно вызвать `Recognize`. Считайте его «камерой», которая позже будет сканировать ваше изображение. + +### Шаг 2: Указать движку путь к офлайн‑ресурсам + +Aspose поставляет языковые пакеты, которые вы можете хранить локально. Установка `ResourcesFolder` сообщает движку, где искать их. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Подсказка:** +> Используйте абсолютный путь во время разработки, а затем переключитесь на относительный путь или настройку конфигурации для продакшна. + +### Шаг 3: Принудительно включить офлайн‑режим + +Вы можете задаться вопросом: «Действительно ли нужно отключать онлайн‑поиск?» +Если вы работаете за файрволом или просто хотите детерминированные результаты, установите `UseOfflineResources` в `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Профессиональная подсказка:** +> Оставив этот флаг `false`, вы можете заставить движок загружать дополнительные данные, что увеличивает задержку и может нарушать политики безопасности. + +### Шаг 4: Выбрать хинди в качестве языка распознавания + +Здесь мы **извлекаем хинди‑текст из изображения**, указывая движку, какой язык ожидать. Это значительно повышает точность. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Почему это помогает:** +> OCR‑движки используют языко‑специфичные модели символов. Зафиксировав хинди, вы избегаете того, что движок будет угадывать среди десятков скриптов. + +### Шаг 5: Загрузить изображение для OCR + +Теперь мы действительно **загружаем изображение для OCR**. Метод `OcrImage.FromFile` читает битмап в формат, понятный движку. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Распространённая ошибка:** +> Указание пути с прямыми слешами в Windows работает, но использование `Path.Combine` делает ваш код кроссплатформенным. + +### Шаг 6: Запустить распознавание + +Когда всё настроено, мы наконец **выполняем OCR на изображении**, вызывая `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Что происходит?** +> Движок сканирует каждый пиксель, сопоставляет шаблоны с базой глифов хинди и формирует строку символов Unicode. + +### Шаг 7: Вывести распознанный текст + +Объект результата содержит свойство `Text`, в котором хранится извлечённая строка. Мы просто выводим её в консоль. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Ожидаемый вывод:** +> Если `receipt_hindi.png` содержит «भुगतान सफल», консоль выведет точно эту строку, сохраняя диакритические знаки. + +## Загрузка изображения для OCR — подготовка ресурса + +Если вы задаётесь вопросом, можно ли передать движку поток вместо файла, ответ — да. Замените `OcrImage.FromFile` на: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Зачем использовать поток?** +> Потоки позволяют работать с изображениями, хранящимися в базах данных, облачных блобах или встроенных ресурсах — идеально для масштабируемых сервисов. + +## Извлечение хинди‑текста из изображения — обработка граничных случаев + +1. **Отсутствует языковой пакет** — Если пакет хинди не найден, `Recognize` бросает исключение. Оберните вызов в try/catch и запишите дружелюбное сообщение. +2. **Низкое разрешение изображений** — Точность OCR падает ниже 300 dpi. Предобработайте изображение (измените размер, резкость) перед загрузкой. +3. **Документы с несколькими языками** — Вы можете включить несколько языков: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Эти настройки гарантируют, что ваш процесс **выполнения OCR на изображении** останется надёжным в продакшене. + +## Запуск полного примера + +Сохраните следующий файл как `Program.cs`, замените пути‑заполнители и запустите: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Когда вы выполните `dotnet run`, вы должны увидеть что‑то вроде: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Если вы получите пустую строку, дважды проверьте, что **ResourcesFolder** указывает на папку, содержащую `Hindi.traineddata`, и что изображение достаточно чёткое. + +## Заключение + +Мы прошли процесс **выполнения OCR на изображении** файлов с помощью Aspose OCR, охватив всё от **загрузки изображения для OCR** до **извлечения хинди‑текста из изображения** в полностью офлайн‑сценарии. Полный, исполняемый код выше даёт прочную основу, а подсказки по потокам, обработке ошибок и поддержке нескольких языков помогут адаптировать решение к реальным проектам. + +Готовы к следующему шагу? Попробуйте переключить язык на **OcrLanguage.Tamil** или подавать изображения из Azure Blob Storage. Вы также можете поэкспериментировать с настройками `ImagePreprocessing`, чтобы повысить точность на шумных чеках. + +Есть вопросы или возникли проблемы? Оставьте комментарий — счастливого кодинга! + +![Пример выполнения OCR на изображении + +## Что вам следует изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Извлечение текста из изображения C# с выбором языка с использованием Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Распознавание текста на изображении с Aspose OCR для нескольких языков](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Извлечение текста из изображения — оптимизация OCR с Aspose.OCR для .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/russian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..be0e264f0 --- /dev/null +++ b/ocr/russian/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Выполните OCR на PDF и преобразуйте отсканированный PDF в поисковый PDF + с помощью Aspose.OCR. Узнайте, как распознавать текст из PDF и создавать поисковые + PDF за считанные минуты. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: ru +og_description: Выполните OCR над PDF и мгновенно создайте PDF, доступный для поиска. + Этот учебник пошагово показывает, как распознавать текст из PDF с помощью Aspose.OCR. +og_title: Выполнить OCR в PDF – Полное руководство по C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Выполните OCR в PDF с помощью Aspose.OCR – Полное руководство по C# +url: /ru/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Выполнение OCR на PDF с Aspose.OCR – Полное руководство на C# + +Когда‑нибудь задавались вопросом, **как выполнить OCR на PDF** файлах без борьбы с десятками командных утилит? Вы не одиноки. Будь то оцифровка счетов, архивирование старых отчётов или просто необходимость в поисковой версии отсканированного контракта, преобразование статичного PDF в документ, по которому можно искать, меняет правила игры. + +В этом руководстве мы пройдемся по **созданию поисковых PDF** файлов из отсканированных PDF (и даже из обычных изображений) с использованием Aspose.OCR для .NET. К концу вы сможете **распознавать текст из PDF** с помощью нескольких строк кода на C#, а также поймёте причины каждого шага, чтобы адаптировать решение под свои проекты. + +> **Краткое резюме:** Весь процесс сводится к трем вещам — инициализации OCR‑движка, передаче ему источника (PDF или изображения) и сохранению результата в виде поискового PDF. Приступим. + +--- + +## Что вам понадобится + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6.0+** (or .NET Framework 4.6+) | Aspose.OCR ориентирован на современные среды выполнения; старые версии могут не поддерживать обновления API. | +| **Aspose.OCR for .NET** NuGet package | Предоставляет класс `OcrEngine` и утилиты для работы с PDF. | +| **A valid Aspose license** (or use the free evaluation) | Без лицензии вы столкнётесь с 30‑дневным ограничением оценки и водяными знаками. | +| **A scanned PDF** (or an image file) you want to make searchable | Это исходный документ для OCR. | +| **Visual Studio 2022** (or any C# editor) | Облегчает отладку, но любой IDE подходит. | + +Вы можете установить библиотеку с помощью следующей команды NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Совет профессионала:** Если вы работаете в CI‑конвейере, добавьте файл лицензии в артефакты сборки и загружайте его во время выполнения, чтобы избежать жёсткого кодирования путей. + +## Выполнение OCR на PDF — настройка Aspose.OCR + +Первое, что нам нужно, — свежий экземпляр `OcrEngine`. Считайте его мозгом, который будет читать ваш документ. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Зачем каждый раз создавать новый экземпляр? Движок хранит конфигурацию (например, настройки языка), которая может различаться для разных документов. Создание нового экземпляра для каждого запуска гарантирует чистый старт и избегает перекрестных взаимодействий между заданиями. + +## Как создать поисковый PDF — настройка паролей (необязательно) + +Если ваш PDF защищён, необходимо передать движку пароль, прежде чем он сможет читать страницы: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Пропуск этого шага для защищённого файла вызовет `PdfPasswordException`. Всегда оборачивайте его в try‑catch, если вы не уверены в статусе защиты. + +## Преобразование отсканированного PDF в поисковый PDF — загрузка источника + +Aspose.OCR работает с абстракцией `OcrImage`, которая может оборачивать PDF, TIFF, JPEG и т.д. Вот как загрузить отсканированный PDF в память: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Внутри `FromFile` разбирает каждую страницу в растровые изображения, которые может обрабатывать OCR‑движок. Если у вас многостраничный PDF, движок автоматически переберёт каждую страницу. + +## Распознавание текста из PDF — выполнение OCR + +Теперь основная часть руководства: попросите движок распознать текст и вывести поисковый PDF. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` указывает движку встраивать невидимый слой текста поверх оригинальных отсканированных изображений. Полученный PDF сохраняет визуальное качество скана, одновременно становясь полностью поисковым — именно то, что нужно для аудитов соответствия. + +## Преобразование изображения в поисковый PDF — сохранение результата + +Наконец, запишите бинарные данные на диск: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Свойство `Binary` содержит необработанные байты PDF. Вы также можете напрямую передать их в веб‑ответ, если создаёте API. + +![Диаграмма, показывающая процесс конвертации OCR для создания поискового PDF](https://example.com/ocr-flow.png "Схема процесса OCR на PDF") + +*Текст изображения: Схема процесса OCR на PDF, иллюстрирующая, как отсканированный PDF превращается в поисковый PDF.* + +## Особые случаи и практические советы + +### 1. Большие файлы и управление памятью +Если вы обрабатываете PDF размером более 100 МБ, рассмотрите возможность использования `OcrEngineSettings.MemoryLimit` для ограничения использования памяти. Кроме того, обрабатывайте страницы пакетами, чтобы избежать `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Поддержка языков +По умолчанию Aspose.OCR предполагает английский язык. Чтобы распознавать другие языки, установите свойство `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Сценарии с многопоточностью +`OcrEngine` **не** является потокобезопасным. Если требуется параллельная обработка, создавайте отдельный движок для каждого потока. + +### 4. Отладка точности OCR +Вы можете извлечь простой текст из `ocrResult` для отладки: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Если вывод выглядит искажённым, поэкспериментируйте с `PreprocessSettings` (например, выравнивание, удаление шумов), чтобы улучшить качество. + +### 5. Подводные камни лицензирования +При запуске оценочной версии Aspose добавляет водяной знак в результирующий PDF. Зарегистрируйте лицензию как можно раньше в приложении: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +## Полный рабочий пример — от начала до конца + +Ниже представлен полный, готовый к запуску пример программы, включающий все приведённые выше советы. Не стесняйтесь скопировать и вставить его в новый консольный проект. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Ожидаемый вывод:** После запуска вы увидите строку в консоли, подтверждающую расположение файла. Откройте `output.pdf` в любом PDF‑просмотрщике; попробуйте ввести слово, которое, как вы знаете, присутствует в оригинальном скане. Если текст будет подсвечен, вы успешно **выполнили OCR на PDF** и создали поисковый документ. + +## Часто задаваемые вопросы + +**В:** Можно ли использовать это для преобразования отдельного изображения (PNG/JPEG) в поисковый PDF? +**О:** Конечно. Замените `OcrImage.FromFile("input.pdf")` на путь к вашему файлу изображения. Движок растеризует изображение и также внедрит слой OCR. + +**В:** Что если мой PDF содержит как отсканированные страницы, так и нативный текст? +**О:** Движок наложит OCR‑текст поверх существующего содержимого, поэтому нативный текст останется выделяемым, а отсканированные страницы станут поисковыми. + +**В:** Насколько точен OCR? +**О:** Точность зависит от качества исходного материала. Чистые сканы высокого разрешения (>300 dpi) дают более 95 % точности. Для шумных документов включите `PreprocessSettings` (выравнивание, удаление шумов) перед вызовом `Recognize`. + +## Следующие шаги — расширение вашего OCR‑инструментария + +Теперь, когда вы можете **распознавать текст из PDF** и **преобразовывать отсканированный PDF в поисковый PDF**, рассмотрите следующие темы: + +- **Пакетная обработка**: Проходить по папке с PDF‑файлами и автоматически генерировать поисковые версии. +- **Извлечение текста**: Использовать `ocrResult.Text` для заполнения поискового индекса (например, Elasticsearch). +- **Пользовательские языковые пакеты**: Скачивать дополнительные языковые данные от Aspose для поддержки азиатских скриптов. +- **Соответствие PDF/A**: Комбинировать Aspose.PDF с результатами OCR для создания архивных PDF. + +Каждый из этих пунктов опирается на основные шаги, которые мы рассмотрели, поэтому вы хорошо подготовлены для расширения вашего решения. + +## Итоги + +Мы только что показали вам **как выполнять OCR на PDF** файлах с помощью Aspose.OCR, превратили отсканированные PDF в полностью поисковые PDF и даже рассмотрели преобразование обычных изображений в поисковые PDF. Код + +## Что вам следует изучить дальше? + +Следующие руководства охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс содержит полные рабочие примеры кода с пошаговыми объяснениями, помогающими освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Распознавание текста PDF — операции OCR с Aspose.OCR для Java](/ocr/english/java/ocr-operations/) +- [Как выполнить 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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/russian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..d40bbb64e --- /dev/null +++ b/ocr/russian/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Учебник по OCR субтитров видео, показывающий, как извлекать кадры из + видео и считывать текст из видеофайлов, таких как MP4, с помощью Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: ru +og_description: Изучите OCR субтитров видео с Aspose.OCR. Извлекайте кадры из видео, + считывайте текст из видео и извлекайте текст из MP4 за несколько минут. +og_title: Оптическое распознавание субтитров видео на C# – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR субтитров видео на C# – Полное руководство +url: /ru/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR субтитров видео на C# – Полное руководство + +Когда‑нибудь вам нужен был **video subtitle ocr**, но вы не знали, с чего начать? Вы не одиноки. Независимо от того, оцифровываете ли вы записи лекций, извлекаете субтитры из обучающих видео или просто хотите узнать, как читать текст из видео, этот учебник покажет вам, как сделать это с помощью C# и Aspose.OCR. + +В течение нескольких минут мы извлечём кадры из видео, запустим OCR на этих кадрах и в конце отобразим текст субтитров кадр за кадром. К концу вы сможете **читать текст из видео** файлы — включая MP4 — без поиска сторонних инструментов. + +## Что вы создадите + +1. Декодирует MP4 (или любой поддерживаемый формат) в отдельные кадры `Bitmap`. +2. Ограничивает область OCR до полосы субтитров, чтобы движок не отвлекался на всё изображение. +3. Обрабатывает каждый кадр с помощью `VideoOcrProcessor` от Aspose. +4. Выводит распознанный текст субтитров в консоль. + +Без лишних деталей, только рабочий сквозной пример, который вы можете добавить в реальный проект. + +## Предварительные требования + +- **.NET 6.0** или новее (код также работает на .NET Framework 4.7+). +- **Aspose.OCR for .NET** – установить через NuGet: `Install-Package Aspose.OCR`. +- Видео файл (MP4 отлично подходит). +- Средство для декодирования видеокадров — в демо используется заглушка, но вы можете подключить FFmpeg, OpenCV или любую библиотеку, возвращающую объекты `Bitmap`. + +> Совет: Если вы работаете в Windows, пакет `System.Drawing.Common` отлично подходит для `Bitmap`. На Linux/macOS понадобится нативная зависимость `libgdiplus`. + +## Шаг 1 – Извлечение кадров из видео + +Первая преграда — превратить движущееся изображение в отдельные статические кадры. Метод `GetVideoFrames` ниже намеренно оставлен пустым; замените его своим любимым декодером. Ниже быстрый набросок с использованием FFmpeg‑Core (только для иллюстрации структуры данных): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Почему это важно:** Извлечение кадров предоставляет OCR‑движку статическое изображение для обработки, что значительно повышает точность по сравнению с попыткой читать напрямую из видеопотока. + +## Шаг 2 – Настройка VideoOcrProcessor + +Теперь, когда у нас есть последовательность объектов `Bitmap`, мы можем передать их Aspose.OCR. `VideoOcrProcessor` позволяет задать **Region of Interest (ROI)** — идеально подходит для субтитров, которые обычно находятся в верхней или нижней части кадра. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Зачем ограничивать ROI?** Игнорируя остальную часть изображения, мы уменьшаем шум, сокращаем время обработки и избегаем ложных срабатываний от фоновой графики. + +## Шаг 3 – Запуск OCR на последовательности кадров + +Когда процессор готов, передача кадров сводится к одной строке кода. Метод `Process` возвращает перечисление объектов `OcrResult`, каждый из которых содержит распознанный текст для соответствующего кадра. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Что происходит под капотом?** Aspose.OCR внутренне нормализует каждый bitmap, запускает распознаватель на основе нейронной сети и затем постобрабатывает результат, улучшая пунктуацию и разрывы строк. + +## Шаг 4 – Отображение извлечённого текста + +Наконец, мы проходим по результатам и выводим каждую строку субтитров. Вы также можете записать их в файл SRT, базу данных или передать в сервис перевода. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Полный рабочий пример + +Объединив всё вместе, получаем автономную консольную программу: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Ожидаемый вывод (пример)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Если OCR будет затрудняться с определённым кадром, вы увидите пустую строку — это сигнал скорректировать ROI или увеличить частоту извлечения кадров. + +## Распространённые проблемы и способы их решения + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| **Непонятные символы** | Кадры низкого разрешения или сильное сжатие | Извлекайте кадры с более высоким битрейтом или увеличьте размер bitmap перед OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **Текст не возвращается** | ROI не покрывает полосу субтитров | Проверьте координаты прямоугольника (используйте инструмент скриншотов для измерения). | +| **Узкое место в производительности** | Обработка каждого кадра при 30 fps избыточна | Снизьте частоту до 1‑2 fps для большинства потоков субтитров; вы всё равно сможете захватить каждое изменение субтитров. | +| **FFmpeg не найден** | `ffmpeg.exe` не находится в `PATH` | Укажите полный путь в `ProcessStartInfo.FileName` или установите FFmpeg глобально. | + +## Расширение решения + +- **Export to SRT** – объединить метки времени с текстом OCR и записать файл SubRip. +- **Multi‑language support** – установить `ocrProcessor.Language = OcrLanguage.Spanish` (или любой поддерживаемый язык). +- **Real‑time processing** – передавать кадры напрямую из живого потока вместо чтения с диска. + +Все эти варианты по‑прежнему основываются на основных идеях **extract frames from video**, **read text from video**, и **extract text from mp4**. + +## Заключение + +Мы только что прошли полный рабочий процесс **video subtitle ocr** на C#. Извлекая кадры из видео, фокусируя OCR на полосе субтитров и проходя по результатам, вы можете надёжно **read text from video** файлы, такие как MP4. Код готов к копированию и вставке, а модульный дизайн позволяет заменить любой декодер кадров по вашему выбору. + +Следующие шаги? Попробуйте экспортировать результаты в файл SRT, поэкспериментировать с разными размерами ROI или передать субтитры в API перевода для многократных языков. Возможности безграничны, как только вы освоите основы извлечения текста из видео. + +Удачной разработки, и пусть ваши субтитры всегда будут кристально чистыми! + +## Что изучать дальше? + +Следующие учебники охватывают тесно связанные темы, которые развивают техники, продемонстрированные в этом руководстве. Каждый ресурс включает полные рабочие примеры кода с пошаговыми объяснениями, чтобы помочь вам освоить дополнительные возможности API и исследовать альтернативные подходы к реализации в ваших проектах. + +- [Извлечение текста из изображения C# с выбором языка с использованием Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Извлечение текста из изображения с помощью Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Извлечение текста из изображения – оптимизация 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/net/ocr-configuration/_index.md b/ocr/spanish/net/ocr-configuration/_index.md index 4a9277b33..77d0a717d 100644 --- a/ocr/spanish/net/ocr-configuration/_index.md +++ b/ocr/spanish/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Desbloquea el poder del reconocimiento de imágenes OCR en .NET con Aspose.OCR. Desbloquea potentes capacidades OCR con Aspose.OCR para .NET. Extrae texto de imágenes de forma fluida. ### [OCROperation con Lista en Reconocimiento de Imágenes OCR](./ocr-operation-with-list/) Desbloquea el potencial de Aspose.OCR para .NET. Realiza reconocimiento de imágenes OCR con listas de manera sencilla. Incrementa la productividad y la extracción de datos en tus aplicaciones. +### [Obtener la versión de Aspose OCR en C# – Guía completa](./get-aspose-ocr-version-in-c-complete-guide/) +Descubre cómo obtener la versión de Aspose OCR en C# con ejemplos claros y paso a paso. ### Casos de uso comunes - **Extraer texto de imágenes** de facturas escaneadas para contabilidad automatizada. @@ -102,4 +104,4 @@ R: Sí, el objeto `OcrResult` proporciona valores de confianza que puedes inspec {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/spanish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..67c7ff3e3 --- /dev/null +++ b/ocr/spanish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-03 +description: Obtén la versión de Aspose OCR en C# con un fragmento sencillo. Aprende + cómo recuperar la versión de la biblioteca Aspose OCR usando OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: es +og_description: Obtén rápidamente la versión de Aspose OCR en C#. Este tutorial muestra + exactamente cómo recuperar la versión de la biblioteca Aspose OCR usando OcrEngine + GetVersion. +og_title: Obtén la versión de Aspose OCR en C# – Guía completa +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Obtén la versión de Aspose OCR en C# – Guía completa +url: /es/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Obtener la versión de Aspose OCR en C# – Guía completa + +¿Alguna vez te has preguntado cómo **obtener la versión de Aspose OCR** desde tu proyecto .NET? Tal vez estés solucionando una discrepancia, o simplemente quieras registrar la versión exacta de la biblioteca que se está ejecutando en producción. Sea cual sea el motivo, has llegado al lugar correcto. + +En este tutorial recorreremos un pequeño programa autónomo en C# que llama a `OcrEngine.GetVersion()` y muestra el resultado. Al final sabrás no solo *cómo* obtener la versión, sino también *por qué* verificarla puede ahorrarte dolores de cabeza al actualizar la **biblioteca Aspose OCR**. + +## Lo que aprenderás + +- Añadir el paquete NuGet Aspose.OCR a un proyecto C# +- Usar el método `OcrEngine.GetVersion()` (el punto de entrada **ocrengine getversion**) +- Manejar posibles excepciones y verificar la salida +- Extender el fragmento para escenarios reales como registro de logs o conmutación condicional de funcionalidades + +No se requiere experiencia previa con OCR, solo un conocimiento básico de C# y Visual Studio (o tu IDE favorito). ¡Comencemos! + +--- + +## Paso 1: Configura el proyecto y agrega la biblioteca Aspose OCR + +Antes de poder llamar a cualquier API relacionada con OCR, necesitas que la **biblioteca Aspose OCR** esté referenciada en tu proyecto. + +1. Abre una terminal o la Consola del Administrador de paquetes en Visual Studio. +2. Ejecuta el siguiente comando para instalar la última versión estable: + +```bash +dotnet add package Aspose.OCR +``` + +> **Consejo profesional:** Si tu objetivo es .NET Framework en lugar de .NET Core, usa la UI del Administrador de paquetes NuGet y elige la versión que coincida con tu tiempo de ejecución. El paquete incluye la clase `OcrEngine` que utilizaremos más adelante. + +### Por qué es importante + +Al instalar el paquete, la versión del ensamblado en disco puede diferir de la versión que la biblioteca informa en tiempo de ejecución. Consultar la versión mediante código garantiza que estás leyendo la compilación exacta que el CLR cargó, lo cual es crucial para depuración y auditorías de cumplimiento. + +--- + +## Paso 2: Escribe el código mínimo para **Obtener la versión de Aspose OCR** + +Crea una nueva aplicación de consola (`dotnet new console -n OcrVersionDemo`) y reemplaza el `Program.cs` predeterminado con lo siguiente: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Explicación de cada parte** + +- `using Aspose.OCR;` introduce el espacio de nombres OCR, permitiéndonos llamar a `OcrEngine`. +- `OcrEngine.GetVersion()` es el método estático **ocrengine getversion** que devuelve una cadena como `"24.5.7"`. +- Envolver la llamada en un bloque `try/catch` te protege de sorpresas en tiempo de ejecución —por ejemplo, que los binarios nativos no se encuentren en la máquina de destino. +- La cadena interpolada `$"Aspose OCR version: {version}"` imprime una línea clara y legible para humanos. + +### Salida esperada + +Al ejecutar `dotnet run` dentro de la carpeta del proyecto, deberías ver algo similar a: + +``` +Aspose OCR version: 24.5.7 +``` + +Si la biblioteca no puede cargarse, la rama de error mostrará un mensaje conciso, ayudándote a identificar el problema rápidamente. + +--- + +## Paso 3: Verifica que la versión coincida con tu paquete NuGet + +Es fácil asumir que la versión de NuGet que instalaste es la que se está usando en tiempo de ejecución, pero pueden intervenir particularidades del entorno. Para confirmar: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Ejecutar este fragmento adicional imprimirá algo como: + +``` +Assembly file version: 24.5.7.0 +``` + +Si los dos valores difieren, podrías estar cargando un DLL más antiguo desde la Global Assembly Cache (GAC) o desde una carpeta de compilación previa. En ese caso, limpia tu solución (`dotnet clean`) y recompila. + +--- + +## Paso 4: Incluye la verificación de versión en el registro de producción + +La mayoría de las aplicaciones reales no solo imprimen en la consola; escriben en un archivo de registro o en un sistema de telemetría. Aquí tienes un ejemplo rápido usando `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Ahora la versión aparece en tus registros estructurados, facilitando el filtrado por `{Version}` más adelante. Este patrón es especialmente útil cuando tienes varios micro‑servicios que cada uno incorpora un DLL OCR potencialmente diferente. + +--- + +## Preguntas frecuentes y casos límite + +### ¿Qué pasa si `GetVersion()` devuelve una cadena vacía? + +Eso suele indicar una instalación corrupta o una dependencia nativa faltante. Reinstala el paquete NuGet y verifica que `Aspose.OCR.Native.dll` (o el binario específico de la plataforma) esté junto a tu ejecutable. + +### ¿El método funciona en .NET Core 2.0? + +Sí, **Aspose OCR** soporta .NET Standard 2.0 y superiores, por lo que cualquier versión de .NET Core que implemente ese estándar puede llamar a `OcrEngine.GetVersion()`. Solo asegúrate de referenciar los identificadores de tiempo de ejecución correctos (`win-x64`, `linux-x64`, etc.) si publicas una aplicación autocontenida. + +### ¿Puedo obtener la versión sin un archivo de licencia? + +Absolutamente. `GetVersion()` **no** requiere una licencia; simplemente informa el número de compilación de la biblioteca. Sin embargo, si intentas realizar OCR sin una licencia válida, obtendrás una excepción en tiempo de ejecución. Por eso el `try/catch` en nuestro fragmento es valioso: aísla la verificación de versión del flujo de ejecución de OCR. + +--- + +## Ejemplo completo (listo para copiar y pegar) + +A continuación tienes el programa completo, listo para colocar en un nuevo proyecto de consola. Incluye el bloque opcional de registro, de modo que puedas ver tanto la salida en consola como los logs estructurados en acción. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Ejecuta con `dotnet run` y verás dos líneas confirmando la versión, más una línea de depuración si habilitas `LogLevel.Debug`. + +--- + +## Conclusión + +Hemos cubierto todo lo necesario para **obtener la versión de Aspose OCR** en un entorno C# —desde instalar la **biblioteca Aspose OCR**, llamar al método **ocrengine getversion**, manejar errores, hasta incrustar el resultado en registros de nivel de producción. Con este conocimiento puedes verificar de forma fiable la compilación exacta de OCR que tu aplicación está usando, evitar errores relacionados con versiones y cumplir con requisitos de auditoría sin sudar. + +¿Próximos pasos? Prueba combinar esta verificación de versión con una llamada real a OCR (`OcrEngine` → `RecognizeImage`) y registra tanto la versión como el resultado del reconocimiento. También podrías explorar el patrón **retrieve aspose version** para otros productos Aspose (PDF, Slides, Cells) y mantener toda tu suite sincronizada. + +¡Feliz codificación, y que tus pipelines de OCR se mantengan afilados! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funcionalidades adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/spanish/net/ocr-optimization/_index.md index b9a9d4da6..83dc12aa3 100644 --- a/ocr/spanish/net/ocr-optimization/_index.md +++ b/ocr/spanish/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Explora Aspose.OCR para .NET. Aumenta la precisión del OCR con filtros de prepr Mejora la precisión del OCR con Aspose.OCR para .NET. Corrige ortografía, personaliza diccionarios y logra un reconocimiento de texto sin errores sin esfuerzo. ### [Guardar resultados multipágina como documento en Reconocimiento de Imágenes OCR](./save-multipage-result-as-document/) Desbloquea el potencial de Aspose.OCR para .NET. Guarda fácilmente resultados OCR multipágina como documentos con esta guía completa paso a paso. +### [Ejemplo de Aspose OCR en C# – Habilitar GPU, Establecer Límite de Memoria y Procesar Imágenes TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Aprende a activar la GPU, limitar la memoria y procesar archivos TIF con Aspose OCR en C# para mejorar el rendimiento. ## Preguntas frecuentes diff --git a/ocr/spanish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/spanish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..c5f6544a4 --- /dev/null +++ b/ocr/spanish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,286 @@ +--- +category: general +date: 2026-06-03 +description: Ejemplo de Aspose OCR en C# que muestra cómo establecer el límite de + memoria GPU, cargar una imagen para OCR y reconocer texto de archivos TIF con código + completo y consejos. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: es +og_description: 'Aprende un ejemplo completo de Aspose OCR en C#: habilita la GPU, + establece el límite de memoria de la GPU, carga una imagen para OCR y reconoce texto + de archivos TIF. Código completo incluido.' +og_title: Ejemplo de Aspose OCR en C# – Aceleración GPU, Límite de Memoria y Procesamiento + de TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Ejemplo de Aspose OCR en C# – Habilitar GPU, Establecer límite de memoria y + procesar imágenes TIF +url: /es/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ejemplo Aspose OCR C# – Habilitar GPU, Establecer Límite de Memoria y Procesar Imágenes TIF + +¿Alguna vez te has preguntado cómo exprimir el máximo rendimiento del código **Aspose OCR C# example** al trabajar con escaneos TIFF masivos? No estás solo. En muchos proyectos del mundo real —piensa en digitalizar archivos o extraer datos de recibos de alta resolución— el cuello de botella no es el algoritmo OCR en sí, sino la utilización del hardware. + +Aquí está el detalle: Aspose OCR admite aceleración GPU, pero debes indicarle exactamente cuánta memoria puede consumir, cargar el tipo de imagen correcto y, finalmente, extraer el texto reconocido de un archivo .tif. Este tutorial te guía paso a paso, desde la instalación del SDK hasta la afinación de la configuración de GPU, para que puedas ejecutar OCR a una velocidad vertiginosa sin agotar la RAM de tu GPU. + +También incluiremos algunos escenarios “qué pasa si” —como manejar TIFFs multipágina o volver a la CPU cuando no hay GPU disponible— para que termines con una solución robusta, no solo con un fragmento aislado. + +## Lo que Necesitarás + +| Requisito | Por qué es importante | +|--------------|----------------| +| **.NET 6 SDK** (o posterior) | Aspose OCR apunta a .NET Standard 2.0+, por lo que cualquier versión reciente de .NET funciona. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | La biblioteca central que proporciona `OcrEngine`, `GpuSettings`, etc. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Necesario para la aceleración GPU; el SDK verificará la presencia de un controlador compatible en tiempo de ejecución. | +| Una **GPU con al menos 2 GB VRAM** (estableceremos el límite en 2048 MB) | Sin suficiente memoria, el motor puede volver a la CPU silenciosamente. | +| Una imagen **TIFF de alta resolución** que desees procesar | Aspose OCR puede leer prácticamente cualquier formato raster, pero TIF es común para escaneos. | +| Visual Studio 2022 (o cualquier editor que prefieras) | Para compilar y depurar el proyecto C#. | + +Si falta alguno de estos elementos, el código seguirá compilando, pero no verás las mejoras de rendimiento que buscamos. + +## Paso 1: Crear el Motor del Ejemplo Aspose OCR C# + +Lo primero en cada **Aspose OCR C# example** es instanciar el motor OCR. Piensa en `OcrEngine` como el director de una película: coordina todo, desde la carga de la imagen hasta la extracción del texto. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Consejo profesional:** Si planeas procesar muchas imágenes consecutivamente, mantén un solo `OcrEngine` activo. Recrearlo por cada imagen añade una sobrecarga que puede eclipsar el tiempo de OCR. + +## Paso 2: Establecer Límite de Memoria GPU (y Habilitar Aceleración) + +Ahora llega la parte que suele complicar a la gente: **establecer el límite de memoria GPU**. Por defecto, Aspose OCR intentará usar toda la VRAM disponible, lo que en una estación de trabajo compartida puede dejar sin recursos a otras aplicaciones. El objeto `GpuSettings` te permite limitar esa asignación. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Por qué establecer un límite de memoria + +- **Estabilidad:** Evita bloqueos por falta de memoria al procesar imágenes gigantescas. +- **Coexistencia:** Permite que otras aplicaciones intensivas en GPU (p. ej., modelos TensorFlow) se ejecuten simultáneamente. +- **Previsibilidad:** Hace que las pruebas de rendimiento sean repetibles porque la GPU no comenzará a intercambiar memoria. + +Si omites `MemoryLimitMb`, Aspose asignará la cantidad que considere necesaria, lo cual puede estar bien en un servidor dedicado de inferencia, pero resulta arriesgado en un portátil de desarrollo. + +## Paso 3: Cargar Imagen para OCR + +Cargar el formato de archivo correcto es la siguiente pieza crucial. El método `OcrImage.FromFile` detecta automáticamente el tipo de imagen, pero aún debes verificar que el archivo exista y que sea una variante TIFF compatible (p. ej., comprimida con LZW o CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Manejo de TIFFs de varias páginas + +Si tu TIFF contiene varias páginas, Aspose OCR solo leerá la primera por defecto. Para procesar todas las páginas, puedes iterar sobre `image.Pages` (disponible en versiones más recientes del SDK) y alimentar cada página al motor por separado. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +El fragmento anterior muestra un patrón **cargar imagen para OCR** que funciona tanto para archivos de una sola página como para multipágina. + +## Paso 4: Reconocer Texto de TIF (o cualquier raster) + +Ahora que la imagen está en memoria, le pedimos a Aspose que haga su magia. El método `Recognize` devuelve un `OcrResult` que contiene el texto plano, puntuaciones de confianza e incluso información de cajas delimitadoras si la necesitas. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Por qué esto funciona bien con TIF + +- **Compresión sin pérdida:** TIFF suele almacenar datos de píxeles sin comprimir, proporcionando la mayor fidelidad al motor OCR. +- **Múltiples espacios de color:** Aspose puede manejar TIFF en escala de grises, RGB o incluso CMYK sin código de conversión adicional. + +Si necesitas ajustar paquetes de idioma (p. ej., francés o japonés), establece `ocrEngine.Settings.Language = "fr"` antes de llamar a `Recognize`. + +## Paso 5: Mostrar el Texto Reconocido + +Finalmente, imprimimos el texto en la consola. En una aplicación real podrías escribirlo en una base de datos, en un archivo JSON o pasar la cadena a una canalización NLP posterior. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Salida esperada + +Ejecutar el programa con un escaneo claro de 300 dpi de una página impresa suele producir algo como: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Si la imagen está borrosa o el límite de memoria GPU es demasiado bajo, podrías ver caracteres corruptos o un resultado truncado. Reducir `MemoryLimitMb` por debajo de la huella de la imagen (a menudo ~1 GB para un TIFF de 6000×8000 píxeles) puede hacer que el motor vuelva automáticamente a la CPU. + +## Ejemplo Completo Funcional + +A continuación tienes el programa completo, listo para ejecutar. Copia‑pega el código en un nuevo proyecto de Aplicación de Consola, reemplaza `YOUR_DIRECTORY/large_photo.tif` por la ruta de tu propio TIFF y pulsa **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Lista rápida de verificación + +- ✅ **Aspose OCR C# example** compilado sin errores. +- ✅ **GPU habilitada** (`Enable = true`). +- ✅ **Límite de memoria GPU** establecido en 2048 MB. +- ✅ **Imagen cargada** desde un archivo TIF. +- ✅ **Texto reconocido** e impreso. + +## Errores Comunes y Cómo Evitarlos + +| Síntoma | Causa probable | Solución | +|---------|----------------|----------| +| `System.DllNotFoundException: cudart64_110.dll` | Tiempo de ejecución de CUDA no instalado o versión incompatible. | Instala CUDA 11.x (o 12.x) que coincida con tu controlador. | +| OCR devuelve cadena vacía | La imagen es demasiado oscura o DPI < 150. | Pre‑procesa con `image.AdjustContrast()` o remuestrea a 300 dpi. | +| Bloqueo por falta de memoria en GPU | `MemoryLimitMb` demasiado bajo para la imagen. | Aumenta el límite o divide la imagen en mosaicos mediante `image.Crop`. | +| Error `Unsupported image format` | El TIFF usa una compresión exótica (p. ej., JPEG‑2000). | Convierte el TIFF a un formato compatible con ImageMagick antes de OCR. | + +## Extender la Demo + +Ahora que tienes un sólido **aspose ocr c# example**, podrías explorar: + +- **Procesamiento por lotes:** Recorrer una carpeta de TIFs, escribir cada resultado en un archivo `.txt`. +- **Paquetes de idioma:** `ocrEngine.Settings.Language = "es"` para español, o cargar diccionarios personalizados. +- **Cajas delimitadoras:** Usa `ocrResult.Regions` para obtener coordenadas de cada palabra—útil para herramientas de redacción. +- **Reversión a CPU:** Envuelve el bloque GPU en un try/catch; en caso de fallo, establece `ocrEngine.Settings.Gpu.Enable = false` y reintenta. + +Estas extensiones mantienen el patrón central intacto mientras añaden valor para casos de uso específicos. + +## ¿Qué Deberías Aprender a Continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer Texto de Imagen Usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extraer Texto de Imagen – Optimización OCR con Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Extraer texto de imagen 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/net/skew-angle-calculation/_index.md b/ocr/spanish/net/skew-angle-calculation/_index.md index 8e403633e..bfba451c5 100644 --- a/ocr/spanish/net/skew-angle-calculation/_index.md +++ b/ocr/spanish/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ Explore Aspose.OCR para .NET, una potente solución de OCR para un reconocimient Libere el poder de Aspose.OCR para .NET, una solución sólida para el reconocimiento de imágenes. Aprenda a calcular los ángulos de inclinación sin esfuerzo. ### [Calcule el ángulo de inclinación a partir de URI en el reconocimiento de imágenes OCR](./calculate-skew-angle-from-uri/) Explore Aspose.OCR para .NET para calcular sin esfuerzo ángulos de inclinación en el reconocimiento de imágenes OCR. Mejore sus proyectos con precisión y eficiencia. +### [Tutorial de documento OCR rotado – Corrección automática de sesgo y rotación en C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Aprenda a corregir documentos OCR rotados automáticamente, ajustando el sesgo y la rotación en C# con Aspose.OCR. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/spanish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..84a351660 --- /dev/null +++ b/ocr/spanish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,278 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial de OCR para documentos rotados que muestra cómo corregir automáticamente + la inclinación y detectar la rotación usando Aspose OCR en C#. Aprende paso a paso + con el código completo. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: es +og_description: El tutorial de OCR para documentos rotados te enseña cómo corregir + automáticamente la inclinación y detectar la rotación usando Aspose OCR en C#. Sigue + la guía completa. +og_title: Tutorial de OCR para documentos rotados – Corrección automática de sesgo + y rotación en C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Tutorial de OCR para Documentos Rotados – Corrección Automática de Inclinación + y Rotación en C# +url: /es/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial de Documento OCR Rotado – Guía Completa para Desarrolladores C# + +¿Alguna vez te has topado con un **ocr rotated document tutorial** cuando un formulario escaneado llega de lado o inclinado? No estás solo. Esas imágenes torcidas pueden arruinar una extracción de texto limpia, pero la buena noticia es que Aspose OCR puede enderezarlas automáticamente por ti. + +En esta guía paso a paso crearemos un `OcrEngine`, activaremos la **corrección automática de sesgo** y la **detección automática de rotación**, ejecutaremos el motor contra una imagen rotada y mostraremos el texto limpio. Al final sabrás exactamente por qué cada configuración es importante, cómo ajustarla para casos extremos y tendrás un programa C# listo para ejecutar. + +## Lo que aprenderás + +* Cómo instalar y referenciar **Aspose OCR** en un proyecto .NET. +* Por qué habilitar `AutoCorrectSkew` y `AutoDetectRotation` es la clave para un **ocr rotated document tutorial** fiable. +* Cómo cargar cualquier imagen (JPG, PNG, TIFF) y dejar que el motor haga el trabajo pesado. +* Consejos para manejar PDFs de varias páginas, escaneos de baja resolución y paquetes de idiomas personalizados. + +> **Requisitos previos:** Visual Studio 2022 (o cualquier IDE de C#), tiempo de ejecución .NET 6+ y una licencia válida de Aspose OCR (o la prueba gratuita). No se necesita experiencia previa en OCR. + +--- + +## Paso 1 – Instalar Aspose OCR y configurar el proyecto + +Lo primero. Obtén el paquete NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Consejo profesional:** Si utilizas una licencia de prueba, coloca el archivo `Aspose.OCR.lic` en la misma carpeta que tu ejecutable, o regístralo programáticamente con `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Crea una nueva aplicación de consola: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Ahora tienes un lienzo limpio para nuestro **ocr rotated document tutorial**. + +## Paso 2 – Inicializar el motor OCR + +El motor es el corazón del proceso. Piensa en él como una navaja suiza para la extracción de texto; solo necesitas indicarle qué trucos habilitar. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**¿Por qué estas configuraciones?** +* `AutoCorrectSkew` analiza la línea base de los caracteres y rota la imagen lo justo para que las líneas queden horizontales. +* `AutoDetectRotation` examina la orientación general (0°, 90°, 180°, 270°) y voltea la página si está al revés. Sin ellas, el motor leería “pɹᴉʍ” en lugar de “word”. + +## Paso 3 – Cargar la imagen que deseas procesar + +Aspose OCR funciona con cualquier formato raster común. Reemplaza la ruta de marcador de posición con la ubicación real de tu formulario rotado. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Caso extremo:** Si recibes un TIFF de varias páginas, usa `OcrImage.FromMultiPageTiff(filePath)` y recorre `image.Pages`. + +## Paso 4 – Ejecutar el reconocimiento + +Ahora el motor hace la magia. Primero enderezará la imagen (gracias a nuestras banderas de sesgo/rotación) y luego extraerá los caracteres. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Si necesitas soporte de idioma más allá del inglés, configúralo antes de llamar a `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Paso 5 – Mostrar el texto reconocido + +Finalmente, volca el texto limpio a la consola —o redirígelo a un archivo, una base de datos, lo que se ajuste a tu flujo de trabajo. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Salida esperada** (suponiendo que la imagen de ejemplo contiene “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Observa cómo el texto aparece correctamente aunque la imagen fuente estuviera rotada 90° y ligeramente sesgada. + +--- + +## Manejo de problemas comunes + +| Problema | Por qué ocurre | Solución | +|------|----------------|-----| +| **Salida en blanco** | Corrección de sesgo desactivada o imagen demasiado oscura. | Habilita `AutoCorrectSkew` (ya está activado) y aumenta el contraste de la imagen con `image.AdjustContrast(1.2)`. | +| **Caracteres basura** | Configuración de idioma incorrecta. | Establece `ocrEngine.Settings.Language` para que coincida con el idioma del documento. | +| **Retardo de rendimiento en PDFs grandes** | El motor procesa cada página secuencialmente. | Usa `Parallel.ForEach` en `image.Pages` para aprovechar CPUs multinúcleo. | +| **Excepción de licencia** | Prueba expirada. | Obtén una licencia permanente o mantente dentro de los límites de prueba (5 páginas por ejecución). | + +--- + +## Consejos profesionales para un tutorial de OCR Rotado robusto + +* **Procesamiento por lotes:** Envuelve todo el flujo en un método que acepte una ruta de carpeta, recorra cada imagen y escriba cada resultado en un archivo `.txt`. +* **Pre‑procesamiento:** A veces una escaneado ruidoso se beneficia de `image.Denoise()` antes del reconocimiento. +* **Post‑procesamiento:** Usa expresiones regulares para limpiar errores comunes de OCR, por ejemplo, reemplazar “0” por “O” solo cuando esté rodeado de letras. +* **Registro:** Aspose OCR proporciona `ocrEngine.Logger`; conéctalo a un logger de archivo para capturar advertencias sobre puntuaciones de baja confianza. + +--- + +## Código completo, listo para ejecutar + +Guarda lo siguiente como `Program.cs` dentro de tu proyecto de consola. Incluye todos los pasos, comentarios y un pequeño asistente para procesamiento por lotes. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Ejecuta: + +```bash +dotnet run +``` + +Deberías ver el texto limpio impreso en la consola, demostrando que nuestro **ocr rotated document tutorial** funciona de extremo a extremo. + +--- + +## Conclusión + +Ahora tienes un **ocr rotated document tutorial** completo que corrige automáticamente el sesgo, detecta la rotación y extrae texto limpio usando Aspose OCR en C#. ¿La lección clave? Habilitar `AutoCorrectSkew` **y** `AutoDetectRotation` convierte un escaneado peligrosamente inclinado en una salida perfectamente legible con solo unas pocas líneas de código. + +Desde aquí, puedes ampliar a trabajos por lotes, integrar paquetes de idiomas o alimentar los resultados a pipelines de análisis posteriores. ¿Quieres explorar más la **corrección automática de sesgo**? Consulta la API de pre‑procesamiento de imágenes de Aspose, o experimenta con umbrales personalizados para escaneos ruidosos. + +¿Tienes preguntas sobre el manejo de PDFs, TIFF de varias páginas o la integración con Azure Functions? Deja un comentario, ¡y feliz codificación! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/spanish/net/text-recognition/_index.md index 8f06dcbf8..8f47b9a30 100644 --- a/ocr/spanish/net/text-recognition/_index.md +++ b/ocr/spanish/net/text-recognition/_index.md @@ -15,7 +15,7 @@ url: /es/net/text-recognition/ ## Introducción -¿Estás listo para llevar tus aplicaciones .NET al siguiente nivel? Sumérgete en el mundo del reconocimiento de texto con Aspose.OCR y mejora tus proyectos con un reconocimiento preciso de caracteres y un procesamiento de imágenes perfecto. +¿Estás listo para llevar tus aplicaciones .NET al siguiente nivel? Sumérgete en el mundo del reconocimiento de texto con Aspose.OCR y mejore sus proyectos con un reconocimiento preciso de caracteres y un procesamiento de imágenes perfecto. ## Obtenga opciones para caracteres reconocidos en el reconocimiento de imágenes OCR @@ -27,7 +27,7 @@ Explore las capacidades de Aspose.OCR para .NET y transforme la forma en que man ## Obtenga resultados como JSON en el reconocimiento de imágenes OCR -Libere todo el potencial de Aspose.OCR para .NET aprendiendo cómo obtener resultados de OCR en formato JSON sin esfuerzo. Esta guía paso a paso garantiza un viaje sencillo hacia la mejora de sus capacidades de reconocimiento de imágenes. Aumente la eficiencia de su aplicación con las sólidas funciones y la tecnología líder en la industria de Aspose.OCR. +Libere todo el potencial de Aspose.OCR para .NET aprendiendo cómo obtener resultados OCR en formato JSON sin esfuerzo. Esta guía paso a paso garantiza un viaje sencillo hacia la mejora de sus capacidades de reconocimiento de imágenes. Aumente la eficiencia de su aplicación con las sólidas funciones y la tecnología líder en la industria de Aspose.OCR. ## Modo de detección de áreas OCR en reconocimiento de imágenes OCR @@ -45,19 +45,40 @@ Navegue por las complejidades del reconocimiento de tablas en el reconocimiento ## Tutoriales de reconocimiento de texto ### [Obtenga opciones para caracteres reconocidos en el reconocimiento de imágenes OCR](./get-choices-for-recognized-characters/) Mejore sus aplicaciones .NET con Aspose.OCR para un reconocimiento preciso de caracteres. Siga nuestra guía paso a paso para recuperar opciones de caracteres reconocidos en el reconocimiento de imágenes. + ### [Obtener el resultado del reconocimiento en el reconocimiento de imágenes OCR](./get-recognition-result/) -Explore Aspose.OCR para .NET, una potente solución de OCR para un reconocimiento perfecto de texto en imágenes. +Explore Aspose.OCR para .NET, una potente solución de OCR para un reconocimiento perfecto del texto en imágenes. + ### [Obtenga resultados como JSON en el reconocimiento de imágenes OCR](./get-result-as-json/) Libere el poder de Aspose.OCR para .NET. Aprenda a obtener resultados OCR en formato JSON sin esfuerzo. Mejore el reconocimiento de sus imágenes con esta guía paso a paso. + ### [Modo de detección de áreas OCR en reconocimiento de imágenes OCR](./ocr-detect-areas-mode/) Mejore sus aplicaciones .NET con Aspose.OCR para un reconocimiento eficiente del texto de las imágenes. Explore el modo de detección de áreas de OCR para obtener resultados precisos. + ### [Reconocer PDF en reconocimiento de imágenes OCR](./recognize-pdf/) Libere el potencial del OCR en .NET con Aspose.OCR. Extraiga texto de archivos PDF sin esfuerzo. Descárguelo ahora para disfrutar de una experiencia de integración perfecta. + +### [Realizar OCR en PDF con Aspose.OCR – Guía completa en C#](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Aprenda a ejecutar OCR en archivos PDF usando Aspose.OCR con una guía completa en C#. + ### [Reconocer tabla en reconocimiento de imágenes OCR](./recognize-table/) Descubra el potencial de Aspose.OCR para .NET con nuestra guía completa sobre cómo reconocer tablas en el reconocimiento de imágenes OCR. + +### [Realizar OCR en una imagen con Aspose OCR – Guía en hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Aprenda a ejecutar OCR en imágenes usando Aspose OCR con una guía paso a paso en hindi. + +### [Cómo usar Aspose: Convertir imagen a HTML con OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Aprenda a convertir imágenes a HTML usando Aspose OCR, obteniendo texto estructurado fácilmente. + +### [Realizar OCR en una imagen y detectar palabras mal escritas en C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Aprenda a ejecutar OCR en una imagen y detectar palabras con errores ortográficos usando Aspose.OCR en C#. + +### [OCR de subtítulos de video en C# – Guía completa](./video-subtitle-ocr-in-c-complete-guide/) +Aprenda a extraer subtítulos de video usando Aspose.OCR en C#. Guía paso a paso para reconocer texto en archivos de video. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/spanish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..c70beab6a --- /dev/null +++ b/ocr/spanish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,276 @@ +--- +category: general +date: 2026-06-03 +description: Cómo usar Aspose para convertir una imagen a HTML y extraer texto de + la imagen en C#. Aprende a generar HTML a partir de una imagen y a hacer OCR de + la imagen a HTML rápidamente. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: es +og_description: Cómo usar Aspose para convertir una imagen a HTML, extraer texto de + la imagen y generar HTML a partir de la imagen con OCR en C#. Sigue esta guía completa. +og_title: 'Cómo usar Aspose: Convertir imagen a HTML con OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Cómo usar Aspose: convertir imagen a HTML con OCR' +url: /es/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo usar Aspose: Convertir imagen a HTML con OCR + +¿Alguna vez te has preguntado **cómo usar Aspose** para convertir una foto escaneada en un HTML ordenado? Tal vez tengas una página de revista, un recibo o una nota manuscrita y necesites que el texto y el diseño se conserven para la publicación web. La buena noticia es que no necesitas escribir un analizador personalizado ni lidiar con procesamiento de imágenes de bajo nivel—Aspose.OCR hace el trabajo pesado por ti. + +En este tutorial recorreremos un **ejemplo completo y ejecutable** que muestra cómo **convertir imagen a HTML**, **extraer texto de una imagen**, y **generar HTML a partir de una imagen** usando la biblioteca Aspose OCR en C#. Al final tendrás una pequeña aplicación de consola que produce un archivo HTML con el diseño original de la página intacto, listo para integrarse en cualquier sitio web. + +## Requisitos previos + +- **.NET 6.0 SDK** o posterior (el código funciona tanto con .NET Core como con .NET Framework). +- **Visual Studio 2022** (o cualquier editor que prefieras). +- **Aspose.OCR for .NET** – instalar vía NuGet: `dotnet add package Aspose.OCR`. +- Un archivo de imagen (JPEG/PNG) que deseas transformar, por ejemplo, `magazine_page.jpg`. + +No se necesitan archivos de configuración adicionales; la biblioteca incluye todo lo necesario para OCR y generación de diseños HTML. + +## Paso 1: Configurar el proyecto y agregar Aspose.OCR + +Primero, crea un nuevo proyecto de consola y agrega el paquete Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Consejo profesional:** Si estás usando Visual Studio, simplemente haz clic derecho en el proyecto → *Manage NuGet Packages* → busca **Aspose.OCR** e instálalo. Este paso asegura que puedas **ocr image to html** sin referencias faltantes. + +## Paso 2: Inicializar el motor OCR + +El núcleo del proceso es la clase `OcrEngine`. Piensa en ella como el cerebro que lee la imagen y decide cómo generar el resultado. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Aquí instanciamos `OcrEngine`. No necesitas proporcionar credenciales para la versión gratuita; la biblioteca usará sus modelos de reconocimiento incorporados. + +## Paso 3: Cargar la imagen de origen + +A continuación, indica al motor el archivo que deseas procesar. Aspose ofrece el método conveniente `OcrImage.FromFile` que maneja la mayoría de los formatos de imagen. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Reemplaza `YOUR_DIRECTORY` con la ruta absoluta o relativa donde se encuentra tu imagen. Si la imagen está en la misma carpeta que el ejecutable, puedes usar simplemente `"magazine_page.jpg"`. + +## Paso 4: Reconocer y solicitar HTML con diseño + +Este es el corazón del tutorial. Al pasar `OutputFormat.HtmlWithLayout` le indicamos a Aspose que **genere HTML a partir de la imagen** mientras preserva la posición original de bloques de texto, imágenes y tablas. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +La propiedad `recognitionResult.Text` ahora contiene un documento HTML completo. Si solo necesitaras texto plano, podrías usar `OutputFormat.Text`, pero nos centramos en **convert image to html** con fidelidad de diseño. + +## Paso 5: Guardar el archivo HTML + +Finalmente, escribe la cadena HTML en disco. Esto te brinda un archivo listo para usar que puedes abrir en cualquier navegador. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Ejecutar el programa producirá `magazine.html`. Ábrelo y verás el texto de la página original posicionado exactamente como aparecía en la imagen fuente—perfecto para archivado o publicación web. + +## Ejemplo completo y funcional + +A continuación se muestra el programa **completo, listo para copiar y pegar**. No se omiten partes, por lo que puedes compilar y ejecutarlo inmediatamente después de establecer las rutas correctas. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Salida esperada + +Cuando abras `magazine.html` en un navegador, deberías ver algo similar a esto (simplificado para ilustración): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Los atributos exactos de `style` variarán según la imagen original, pero la estructura garantiza que **extract text from image** y **generate html from image** ocurran en un solo paso sin interrupciones. + +## Preguntas frecuentes y casos límite + +### ¿Qué pasa si la imagen tiene baja resolución? + +Aspose.OCR funciona mejor con imágenes que tengan al menos **300 DPI**. Si tu archivo está borroso, intenta preprocesarlo con una biblioteca de mejora de imágenes (p.ej., ImageSharp) antes de enviarlo al motor OCR. La baja calidad puede afectar tanto la precisión de **extract text from image** como la fidelidad del diseño HTML generado. + +### ¿Puedo controlar el idioma del OCR? + +Sí. Configura la propiedad `Language` en el `OcrEngine` antes de llamar a `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Esto mejora el reconocimiento al trabajar con caracteres que no son en inglés. + +### ¿Cómo obtengo texto plano en lugar de HTML? + +Si solo necesitas la cadena cruda, reemplaza `OutputFormat.HtmlWithLayout` por `OutputFormat.Text`. Entonces `recognitionResult.Text` contendrá únicamente los caracteres extraídos. + +### ¿Hay una forma de incrustar imágenes en el HTML generado? + +Aspose.OCR puede incrustar la imagen original como un URI de datos base‑64 cuando usas `OutputFormat.HtmlWithLayoutAndImages`. Esto es útil cuando deseas un único archivo HTML sin recursos externos. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### ¿Qué pasa con el procesamiento de lotes grandes? + +Para procesamiento por lotes, envuelve la lógica en un bucle `foreach` sobre una lista de rutas de archivo. Reutilizar la misma instancia de `OcrEngine` reduce la sobrecarga y acelera la canalización de **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Consejos para código listo para producción + +- **Dispose resources**: Tanto `OcrEngine` como `OcrImage` implementan `IDisposable`. Envuélvelos en sentencias `using` para liberar la memoria nativa rápidamente. +- **Error handling**: Captura `IOException` para problemas relacionados con archivos y `OcrException` para problemas de reconocimiento. +- **Performance**: Si procesas muchas imágenes, considera habilitar **parallelism** (`Parallel.ForEach`) pero ten en cuenta el uso de CPU—OCR es intensivo en CPU. +- **Logging**: Integra un logger (p.ej., Serilog) para capturar los puntajes de confianza del OCR (`recognitionResult.Confidence`) para el monitoreo de calidad. + +## Conclusión + +Acabamos de cubrir **cómo usar Aspose** para **convertir imagen a HTML**, **extraer texto de una imagen**, y **generar HTML a partir de una imagen** en unos pocos pasos sencillos. El ejemplo de código completo muestra cómo **ocr image to html** preservando el diseño, lo que lo convierte en una base sólida para cualquier proyecto de digitalización de documentos. + +Desde aquí podrías: + +- Experimentar con diferentes opciones de `OutputFormat` para adaptarlas a tus necesidades. +- Combinar la salida HTML con un framework CSS para un estilo responsivo. +- Alimentar el texto extraído a un índice de búsqueda o a una canalización de aprendizaje automático. + +Pruébalo, ajusta la configuración y observa cómo Aspose convierte fácilmente las imágenes en contenido listo para la web. Si encuentras algún problema, deja un comentario—¡feliz codificación! + +![Diagrama que muestra la canalización OCR de imagen a diseño HTML – cómo usar Aspose](/images/ocr-pipeline.png "cómo usar aspose") + +--- + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer texto de imagen C# con selección de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convertir imagen a texto – Realizar OCR en una imagen desde URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Reconocer texto en 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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/spanish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..f74f730e6 --- /dev/null +++ b/ocr/spanish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-03 +description: Realiza OCR en una imagen y extrae el texto de la imagen usando Aspose.OCR. + Aprende cómo detectar palabras mal escritas y obtener sugerencias de ortografía + en una única demostración en C#. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: es +og_description: Realiza OCR en una imagen para extraer el texto, luego detecta palabras + mal escritas y obtén sugerencias de ortografía con Aspose.OCR en C#. +og_title: Realizar OCR en una imagen y detectar palabras mal escritas en C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Realizar OCR en una imagen y detectar palabras mal escritas en C# +url: /es/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR en Imagen y Detectar Palabras Mal Escritas en C# + +¿Alguna vez te has preguntado cómo **perform OCR on image** sin volverte loco? No eres el único. Ya sea que estés digitalizando cartas antiguas, escaneando recibos o construyendo un flujo de trabajo inteligente de documentos, extraer texto limpio de las fotos es el primer obstáculo. ¿La buena noticia? Con Aspose.OCR puedes montar una solución en minutos, y lo mejor es que también puedes **detect misspelled words** y **get spelling suggestions** en la misma ejecución. + +En este tutorial recorreremos una aplicación de consola C# completa y lista para ejecutar que **extracts text from image**, ejecuta un corrector ortográfico en inglés y muestra cada error con útiles ideas de corrección. Al final sabrás exactamente **how to extract text**, cómo conectar la API de corrección ortográfica y cómo se ve la salida esperada en la consola. + +## Qué Construirás + +- Cargar un bitmap (o PNG) que contenga errores tipográficos. +- Ejecutar Aspose.OCR para **perform OCR on image** y obtener datos de cadena sin procesar. +- Inicializar el corrector ortográfico integrado en inglés. +- **Detect misspelled words** y **get spelling suggestions** para cada una. +- Imprimir un informe ordenado en la consola. + +Sin servicios externos, sin llamadas HTTP complicadas, solo un paquete NuGet y unas cuantas líneas de código. + +## Requisitos Previos + +- .NET 6.0 SDK o posterior (el código también funciona en .NET Framework 4.7+). +- Visual Studio 2022 (o cualquier editor que prefieras). +- Paquete NuGet Aspose.OCR para .NET (`Aspose.OCR`). +- Un archivo de imagen (`letter_with_typos.png`) colocado en una ubicación a la que puedas referenciar desde el proyecto. + +Si nunca has usado Aspose antes, no te preocupes: instalar el paquete es tan fácil como ejecutar: + +```bash +dotnet add package Aspose.OCR +``` + +Ahora vamos a sumergirnos en la implementación. + +## Paso 1: Configurar el Proyecto e Instalar Aspose.OCR + +Crea un nuevo proyecto de consola e incorpora la biblioteca OCR: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Cuando termine la restauración, abre `Program.cs`. Reemplazaremos el contenido predeterminado con el código completo de la demo más adelante, pero primero hablemos de por qué cada espacio de nombres es importante. + +- `Aspose.OCR` – Motor OCR central y manejo de imágenes. +- `Aspose.OCR.SpellCheck` – Utilidades de corrección ortográfica que vienen con la biblioteca. +- `System` – Clases base estándar de .NET (p. ej., `Console`). + +## Paso 2: Cargar la Imagen y Realizar OCR en Imagen + +El primer trabajo real es alimentar la imagen al motor OCR. Aspose.OCR lee muchos formatos (PNG, JPEG, TIFF). Aquí tienes el fragmento que hace el trabajo pesado: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Por qué es importante:** `OcrImage.FromFile` abstrae los detalles a nivel de píxel, mientras que `OcrEngine.Recognize` ejecuta el modelo neuronal entrenado que traduce glifos visuales a caracteres Unicode. La propiedad `ocrResult.Text` ahora contiene la cadena cruda, exactamente lo que necesitas para **extract text from image**. + +> **Consejo profesional:** Si tu imagen contiene varios idiomas, puedes establecer `ocrEngine.Language = OcrLanguage.Multilingual;` antes de llamar a `Recognize`. + +## Paso 3: Inicializar el Corrector Ortográfico en Inglés + +Aspose.OCR incluye un motor de corrección ortográfica incorporado que entiende inglés de forma predeterminada. Inicializarlo es una sola línea: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Por qué este paso es crucial:** La salida del OCR puede incluir caracteres mal reconocidos (p. ej., “l” vs “1”) o errores tipográficos reales del documento original. El corrector ortográfico escaneará la cadena, localizará tokens sospechosos y sugerirá alternativas. + +## Paso 4: Detectar Palabras Mal Escritas y Obtener Sugerencias Ortográficas + +Ahora alimentamos el texto OCR al corrector: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` es una colección donde cada entrada contiene la palabra errónea y una matriz de correcciones posibles. + +## Paso 5: Mostrar los Resultados + +Finalmente, iteramos sobre la colección e imprimimos un informe legible: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Salida Esperada en la Consola + +Suponiendo que `letter_with_typos.png` contiene la frase: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Ejecutar la demo producirá algo como: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Observa cómo cada error tipográfico se empareja con un puñado de correcciones plausibles, justo lo que necesitas al crear una interfaz de corrección amigable. + +## Ejemplo Completo y Funcional + +A continuación tienes el programa **completo, listo para copiar y pegar**. Sustituye `YOUR_DIRECTORY` por la ruta real a tu archivo de imagen. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Casos Límite a Considerar** +> - **Imagen Vacía:** Si el motor OCR devuelve una cadena vacía, `spellChecker.Check` simplemente retornará una colección vacía—sin fallos. +> - **Texto No Inglés:** Cambia `OcrLanguage.English` por `OcrLanguage.French` (o cualquier idioma soportado) para **detect misspelled words** en otras configuraciones regionales. +> - **Documentos Grandes:** Para PDFs de varias páginas, deberías iterar sobre cada página, ejecutar OCR y luego agregar los resultados antes de la corrección ortográfica. + +## Visión General Visual (Texto Alternativo) + +![Diagrama que muestra el flujo para perform OCR on image, extract text from image y luego detect misspelled words con spelling suggestions](perform-ocr-on-image-flow.png) + +*El diagrama anterior ilustra la canalización de extremo a extremo: imagen → motor OCR → texto crudo → corrector ortográfico → sugerencias.* + +## Preguntas Frecuentes y Consejos Profesionales + +| Pregunta | Respuesta | +|----------|-----------| +| **¿Necesito conexión a internet?** | No. Aspose.OCR se ejecuta completamente de forma local; perfecto para entornos offline o seguros. | +| **¿Qué tan preciso es el corrector ortográfico?** | Utiliza un diccionario de ~150 k palabras en inglés y coincidencia difusa, por lo que la mayoría de los errores comunes son detectados. | +| **¿Puedo personalizar el diccionario?** | Sí. `SpellChecker.AddUserDictionary("custom.txt")` te permite cargar términos específicos de dominio (p. ej., nombres de productos). | +| **¿Qué pasa si la imagen está sesgada?** | El motor OCR detecta automáticamente la orientación, pero puedes llamar manualmente a `ocrEngine.ImagePreprocessing.Rotate(angle)` para casos rebeldes. | +| **¿Hay forma de resaltar sugerencias en la UI?** | Después de obtener la colección `misspellings`, puedes mapear cada `entry.Word` a su posición en `ocrResult.Text` y subrayarla en un RichTextBox o vista web. | + +## Conclusión + +Acabamos de mostrarte **how to perform OCR on image**, **extract text from image**, y luego **detect misspelled words** mientras **get spelling suggestions**, todo con una concisa aplicación de consola C#. La idea central es simple: dejar que Aspose.OCR haga el trabajo pesado de reconocer caracteres y luego usar su corrector ortográfico incorporado para limpiar la salida. Desde aquí puedes ampliar la demo a un servicio completo de procesamiento de documentos, integrarlo con una API web o conectarlo a un editor de escritorio. + +¿Listo para el siguiente paso? Prueba cambiar el idioma a español, procesa un PDF de varias páginas o crea una pequeña interfaz WPF que permita a los usuarios hacer clic en una palabra para aceptar una sugerencia. Los bloques de construcción ya están listos—solo sigue experimentando. + +Si encontraste algún inconveniente o tienes ideas para extensiones, deja un comentario abajo. ¡Feliz codificación! + +## ¿Qué Deberías Aprender a Continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/spanish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..0a2fdfbd8 --- /dev/null +++ b/ocr/spanish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: Realiza OCR en una imagen usando Aspose OCR en C#. Aprende cómo cargar + la imagen para OCR y extraer texto en hindi de la imagen sin conexión con código + paso a paso. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: es +og_description: Realiza OCR en una imagen con Aspose OCR en C#. Este tutorial muestra + cómo cargar una imagen para OCR y extraer texto en hindi de la imagen sin conexión, + con código ejecutable. +og_title: Realizar OCR en una imagen – Guía de Aspose OCR en hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Realizar OCR en una imagen con Aspose OCR – Guía en hindi +url: /es/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR en Imagen con Aspose OCR – Guía en Hindi + +¿Alguna vez necesitaste **realizar OCR en imagen** archivos pero te quedaste atascado en cómo obtener los caracteres en hindi de ellos? No estás solo—muchos desarrolladores se topan con esa barrera cuando intentan leer scripts no latinos por primera vez. La buena noticia es que Aspose OCR lo hace bastante sencillo, y puedes incluso hacerlo completamente sin conexión. + +En esta guía **cargaremos la imagen para OCR**, apuntaremos el motor a tus paquetes de idioma offline y, finalmente, **extraeremos texto en hindi de la imagen** sin tocar nunca internet. Al final tendrás una aplicación de consola C# lista para ejecutar que lee un recibo en hindi y muestra el texto en la consola. + +## Lo que Necesitarás + +- **.NET 6.0** o posterior (el código también funciona en .NET Framework 4.7+) +- **Aspose.OCR for .NET** paquete NuGet + `dotnet add package Aspose.OCR` +- Una carpeta que contenga los **recursos de idioma Hindi offline** (descargar desde el portal de Aspose) +- Un archivo de imagen con texto en hindi, por ejemplo, `receipt_hindi.png` + +Eso es todo—sin servicios externos, sin claves API, solo código directo. + +## Realizar OCR en Imagen – Implementación Paso a Paso + +A continuación dividimos el proceso en siete pasos claros. Cada paso se explica **por qué** es importante, no solo **qué** escribir. + +### Paso 1: Crear la Instancia del Motor OCR + +El motor es el corazón de Aspose OCR. Instanciarlo te da acceso a todas las configuraciones que ajustarás más adelante. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +**¿Por qué?** +> Sin un `OcrEngine` no tienes un objeto al que llamar `Recognize`. Piensa en él como la “cámara” que más tarde escaneará tu imagen. + +### Paso 2: Apuntar el Motor a los Recursos Offline + +Aspose incluye paquetes de idioma que puedes almacenar localmente. Configurar `ResourcesFolder` indica al motor dónde buscar. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +**Consejo:** +> Usa una ruta absoluta durante el desarrollo, luego cambia a una ruta relativa o a una configuración para producción. + +### Paso 3: Forzar el Modo Offline + +Podrías preguntarte, “¿Realmente necesito desactivar la búsqueda en línea?” +Si trabajas detrás de un firewall o simplemente deseas resultados determinísticos, establece `UseOfflineResources` a `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +**Consejo profesional:** +> Dejar esta bandera en `false` puede hacer que el motor descargue datos adicionales, lo que añade latencia y puede violar políticas de seguridad. + +### Paso 4: Seleccionar Hindi como el Idioma de Reconocimiento + +Aquí **extraemos texto en hindi de la imagen** indicando al motor qué idioma esperar. Esto mejora drásticamente la precisión. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +**Por qué ayuda:** +> Los motores OCR usan modelos de caracteres específicos por idioma. Al fijar Hindi, evitas que el motor adivine entre docenas de scripts. + +### Paso 5: Cargar Imagen para OCR + +Ahora realmente **cargamos la imagen para OCR**. El método `OcrImage.FromFile` lee el bitmap en un formato que el motor entiende. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +**Error común:** +> Proveer una ruta con barras diagonales hacia adelante en Windows funciona, pero usar `Path.Combine` hace que tu código sea independiente de la plataforma. + +### Paso 6: Ejecutar el Reconocimiento + +Con todo configurado, finalmente **realizamos OCR en la imagen** llamando a `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +**¿Qué está pasando?** +> El motor escanea cada píxel, compara patrones contra la base de datos de glifos Hindi y construye una cadena de caracteres Unicode. + +### Paso 7: Mostrar el Texto Reconocido + +El objeto de resultado contiene una propiedad `Text` que almacena la cadena extraída. Simplemente la escribimos en la consola. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +**Salida esperada:** +> Si `receipt_hindi.png` contiene “भुगतान सफल”, la consola imprimirá exactamente esa línea, preservando los diacríticos. + +## Cargar Imagen para OCR – Preparando el Recurso + +Si te preguntas si puedes proporcionar al motor un stream en lugar de un archivo, la respuesta es sí. Reemplaza `OcrImage.FromFile` por: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +**¿Por qué usar un stream?** +> Los streams te permiten trabajar con imágenes almacenadas en bases de datos, blobs en la nube o recursos incrustados—perfecto para servicios escalables. + +## Extraer Texto en Hindi de la Imagen – Manejo de Casos Extremes + +1. **Paquete de idioma faltante** – Si el paquete Hindi no se encuentra, `Recognize` lanza una excepción. Envuelve la llamada en un try/catch y registra un mensaje amigable. +2. **Imágenes de baja resolución** – La precisión del OCR disminuye por debajo de 300 dpi. Preprocesa la imagen (redimensiona, nitida) antes de cargarla. +3. **Documentos multilingües** – Puedes habilitar varios idiomas: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Estos ajustes garantizan que tu rutina de **realizar OCR en imagen** sea robusta en producción. + +## Ejecutando el Ejemplo Completo + +Guarda el siguiente archivo como `Program.cs`, reemplaza las rutas de marcador de posición y ejecuta: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Cuando ejecutes `dotnet run`, deberías ver algo como: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Si obtienes una cadena vacía, verifica que el **ResourcesFolder** apunte a la carpeta que contiene `Hindi.traineddata` y que la imagen sea lo suficientemente clara. + +## Conclusión + +Hemos recorrido cómo **realizar OCR en archivos de imagen** con Aspose OCR, cubriendo todo desde **cargar imagen para OCR** hasta **extraer texto en hindi de la imagen** en un escenario completamente offline. El código completo y ejecutable anterior te brinda una base sólida, y los consejos sobre streams, manejo de errores y soporte multilingüe te ayudarán a adaptar la solución a proyectos del mundo real. + +¿Listo para el siguiente paso? Prueba cambiar el idioma a **OcrLanguage.Tamil** o proporcionar imágenes desde un almacenamiento Azure Blob. También puedes experimentar con la configuración `ImagePreprocessing` para mejorar la precisión en recibos ruidosos. + +¿Tienes preguntas o encontraste un problema? Deja un comentario—¡feliz codificación! + +![Ejemplo de OCR en imagen + +## ¿Qué Deberías Aprender a Continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar funciones adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extraer texto de imagen 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/) +- [Extraer Texto de Imagen – Optimización OCR con Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/spanish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..48c55199c --- /dev/null +++ b/ocr/spanish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-06-03 +description: Realiza OCR en PDF y convierte PDF escaneado en PDF buscable usando Aspose.OCR. + Aprende cómo reconocer texto de PDF y crear PDFs buscables en minutos. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: es +og_description: Realiza OCR en PDF y crea instantáneamente un PDF buscable. Este tutorial + muestra paso a paso cómo reconocer texto de PDF usando Aspose.OCR. +og_title: Realizar OCR en PDF – Guía completa de C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Realizar OCR en PDF con Aspose.OCR – Guía completa de C# +url: /es/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Realizar OCR en PDF con Aspose.OCR – Guía completa en C# + +¿Alguna vez te has preguntado **cómo realizar OCR en archivos PDF** sin lidiar con docenas de herramientas de línea de comandos? No estás solo. Ya sea que estés digitalizando facturas, archivando informes antiguos o simplemente necesites una versión buscable de un contrato escaneado, convertir un PDF estático en algo que realmente puedas buscar es un cambio de juego. + +En esta guía recorreremos **cómo crear archivos PDF buscables** a partir de PDFs escaneados (e incluso imágenes simples) usando Aspose.OCR para .NET. Al final podrás **reconocer texto de PDF** con unas pocas líneas de código C#, y comprenderás el porqué de cada paso para que puedas adaptar la solución a tus propios proyectos. + +> **Resumen rápido:** Todo el proceso se reduce a tres cosas: inicializar el motor OCR, alimentarlo con la fuente (PDF o imagen) y guardar la salida PDF buscable. Vamos al detalle. + +--- + +## Lo que necesitarás + +Antes de comenzar, asegúrate de tener: + +| Prerrequisito | Por qué es importante | +|--------------|------------------------| +| **.NET 6.0+** (o .NET Framework 4.6+) | Aspose.OCR apunta a runtimes modernos; versiones más antiguas pueden carecer de actualizaciones de API. | +| **Paquete NuGet Aspose.OCR para .NET** | Proporciona la clase `OcrEngine` y utilidades para manejar PDF. | +| **Una licencia válida de Aspose** (o usa la evaluación gratuita) | Sin licencia alcanzarás el límite de evaluación de 30 días y marcas de agua. | +| **Un PDF escaneado** (o un archivo de imagen) que quieras hacer buscable | Este es el documento fuente para el OCR. | +| **Visual Studio 2022** (o cualquier editor C#) | Facilita la depuración, pero cualquier IDE sirve. | + +Puedes instalar la biblioteca con el siguiente comando NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Consejo profesional:** Si trabajas en una canalización CI, agrega el archivo de licencia a los artefactos de compilación y cárgalo en tiempo de ejecución para evitar rutas codificadas. + +--- + +## Realizar OCR en PDF – Configurando Aspose.OCR + +Lo primero que necesitamos es una nueva instancia de `OcrEngine`. Piensa en ella como el cerebro que leerá tu documento. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +¿Por qué una nueva instancia cada vez? El motor mantiene configuraciones (como el idioma) que pueden variar por documento. Instanciarlo por ejecución garantiza una pizarra limpia y evita interferencias entre trabajos. + +--- + +## Cómo crear PDF buscable – Configurando contraseñas (Opcional) + +Si tu PDF está protegido, debes indicar la contraseña al motor antes de que pueda leer las páginas: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Omitir este paso en un archivo protegido lanzará una `PdfPasswordException`. Siempre envuélvelo en un try‑catch si no estás seguro del estado de protección. + +--- + +## Convertir PDF escaneado a PDF buscable – Cargando la fuente + +Aspose.OCR trabaja con la abstracción `OcrImage`, que puede envolver PDFs, TIFFs, JPEGs, etc. Así es como cargas un PDF escaneado en memoria: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Detrás de escena, `FromFile` analiza cada página en imágenes raster que el motor OCR puede procesar. Si tienes un PDF de varias páginas, el motor iterará automáticamente sobre cada una. + +--- + +## Reconocer texto de PDF – Ejecutando el OCR + +Ahora el núcleo del tutorial: pedir al motor que reconozca el texto y genere un PDF buscable. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` indica al motor que incruste una capa de texto invisible sobre las imágenes escaneadas originales. El PDF resultante conserva la fidelidad visual del escaneo mientras se vuelve totalmente buscable—exactamente lo que necesitas para auditorías de cumplimiento. + +--- + +## Convertir imagen a PDF buscable – Guardando el resultado + +Finalmente, escribe los datos binarios en disco: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +La propiedad `Binary` contiene los bytes crudos del PDF. También podrías transmitirlos directamente a una respuesta web si estás construyendo una API. + +--- + +![Diagrama que muestra el flujo de conversión OCR para crear PDF buscable](https://example.com/ocr-flow.png "Diagrama del flujo de OCR en PDF") + +*Texto alternativo de la imagen: Diagrama del flujo de OCR en PDF que ilustra cómo un PDF escaneado se convierte en un PDF buscable.* + +--- + +## Casos límite y consejos prácticos + +### 1. Archivos grandes y gestión de memoria +Si procesas PDFs mayores de 100 MB, considera usar `OcrEngineSettings.MemoryLimit` para limitar el uso de memoria. Además, procesa las páginas en lotes para evitar `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Soporte de idiomas +Por defecto Aspose.OCR asume inglés. Para reconocer otros idiomas, establece la propiedad `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Escenarios multihilo +`OcrEngine` **no** es seguro para hilos. Si necesitas procesamiento paralelo, crea un motor separado por hilo. + +### 4. Depuración de precisión OCR +Puedes extraer el texto plano de `ocrResult` para depurar: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Si la salida se ve distorsionada, experimenta con `PreprocessSettings` (p. ej., deskew, despeckle) para mejorar la calidad. + +### 5. Trucos de licenciamiento +Cuando ejecutas la versión de evaluación, Aspose agrega una marca de agua al PDF de salida. Registra tu licencia al inicio de la aplicación: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Ejemplo completo – De principio a fin + +A continuación tienes el programa completo, listo para ejecutar, que incorpora todos los consejos anteriores. Siéntete libre de copiar‑pegarlo en un nuevo proyecto de consola. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Salida esperada:** Después de ejecutar, verás una línea en la consola confirmando la ubicación del archivo. Abre `output.pdf` en cualquier visor de PDF; intenta escribir una palabra que sepas que aparece en el escaneo original. Si el texto se resalta, has **realizado OCR en PDF** y creado un documento buscable con éxito. + +--- + +## Preguntas frecuentes + +**P: ¿Puedo usar esto para convertir una sola imagen (PNG/JPEG) a PDF buscable?** +R: Absolutamente. Reemplaza `OcrImage.FromFile("input.pdf")` por la ruta a tu archivo de imagen. El motor rasterizará la imagen e incrustará la capa OCR de la misma manera. + +**P: ¿Qué pasa si mi PDF tiene páginas escaneadas y texto nativo?** +R: El motor superpondrá el texto OCR sobre el contenido existente, de modo que el texto nativo sigue siendo seleccionable mientras que las páginas escaneadas se vuelven buscables. + +**P: ¿Qué tan precisa es la OCR?** +R: La precisión depende de la calidad de la fuente. Escaneos limpios y de alta resolución (>300 dpi) ofrecen >95 % de precisión. Para documentos ruidosos, habilita `PreprocessSettings` (deskew, despeckle) antes de llamar a `Recognize`. + +--- + +## Próximos pasos – Ampliando tu kit de herramientas OCR + +Ahora que puedes **reconocer texto de PDF** y **convertir PDF escaneado a PDF buscable**, considera estos temas de seguimiento: + +- **Procesamiento por lotes**: recorre una carpeta de PDFs y genera versiones buscables automáticamente. +- **Extracción de texto**: usa `ocrResult.Text` para alimentar un índice de búsqueda (p. ej., Elasticsearch). +- **Paquetes de idioma personalizados**: descarga datos de idioma adicionales de Aspose para soportar escrituras asiáticas. +- **Cumplimiento PDF/A**: combina Aspose.PDF con la salida OCR para crear PDFs listos para archivo. + +Cada uno de estos se basa en los pasos centrales que cubrimos, así que estás bien posicionado para expandir tu solución. + +--- + +## Conclusión + +Acabamos de mostrarte **cómo realizar OCR en archivos PDF** usando Aspose.OCR, convertir PDFs escaneados en PDFs totalmente buscables, y también cubrir la conversión de imágenes simples a PDFs buscables. El código + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que amplían las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Reconocer texto en PDF – Operaciones OCR con Aspose.OCR para Java](/ocr/english/java/ocr-operations/) +- [Cómo hacer OCR en 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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/spanish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..6f13894b9 --- /dev/null +++ b/ocr/spanish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Tutorial de OCR de subtítulos de video que muestra cómo extraer fotogramas + de un video y leer texto de archivos de video como MP4 usando Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: es +og_description: Aprende OCR de subtítulos de video con Aspose.OCR. Extrae fotogramas + de video, lee texto del video y extrae texto de MP4 en pocos minutos. +og_title: OCR de subtítulos de video en C# – Guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR de subtítulos de video en C# – Guía completa +url: /es/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Guía completa de OCR de subtítulos de video en C# + +¿Alguna vez necesitaste **video subtitle ocr** pero no sabías por dónde empezar? No estás solo. Ya sea que estés digitalizando grabaciones de conferencias, extrayendo subtítulos de videos de entrenamiento, o simplemente tengas curiosidad por leer texto de un video, este tutorial te muestra exactamente cómo hacerlo con C# y Aspose.OCR. + +En los próximos minutos extraeremos fotogramas del video, ejecutaremos OCR en esos fotogramas y, finalmente, mostraremos el texto de los subtítulos fotograma a fotograma. Al final podrás **leer texto de video** archivos —incluyendo MP4— sin buscar herramientas de terceros. + +## Lo que construirás + +Crearemos una pequeña aplicación de consola que: + +1. Decodifica un MP4 (o cualquier formato compatible) en fotogramas `Bitmap` individuales. +2. Limita la región de OCR a la banda de subtítulos para que el motor no se distraiga con toda la imagen. +3. Procesa cada fotograma con `VideoOcrProcessor` de Aspose. +4. Imprime el texto de subtítulos reconocido en la consola. + +Sin rodeos, solo un ejemplo funcional de extremo a extremo que puedes incorporar en un proyecto real. + +## Requisitos previos + +- **.NET 6.0** o posterior (el código también funciona en .NET Framework 4.7+). +- **Aspose.OCR for .NET** – instalar vía NuGet: `Install-Package Aspose.OCR`. +- Un archivo de video (MP4 funciona muy bien). +- Una forma de decodificar fotogramas de video – la demo usa un método de marcador de posición, pero puedes conectar FFmpeg, OpenCV o cualquier biblioteca que devuelva objetos `Bitmap`. + +> Consejo profesional: Si estás en Windows, el paquete `System.Drawing.Common` funciona bien para `Bitmap`. En Linux/macOS necesitarás la dependencia nativa `libgdiplus`. + +## Paso 1 – Extraer fotogramas del video + +La primera barrera es convertir una imagen en movimiento en imágenes fijas. El método `GetVideoFrames` a continuación se deja deliberadamente vacío; reemplázalo con tu decodificador favorito. Aquí tienes un boceto rápido usando FFmpeg‑Core (solo para ilustrar la forma de los datos): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Por qué es importante:** Extraer fotogramas le brinda al motor OCR una imagen estática con la que trabajar, lo que mejora drásticamente la precisión en comparación con intentar leer directamente de una transmisión de video. + +## Paso 2 – Configurar el VideoOcrProcessor + +Ahora que tenemos una secuencia de objetos `Bitmap`, podemos entregarlos a Aspose.OCR. El `VideoOcrProcessor` nos permite definir una **Region of Interest (ROI)** – perfecta para subtítulos que normalmente se encuentran en la parte superior o inferior del fotograma. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **¿Por qué limitar la ROI?** Al ignorar el resto de la imagen reducimos el ruido, disminuimos el tiempo de procesamiento y evitamos falsos positivos provenientes de gráficos de fondo. + +## Paso 3 – Ejecutar OCR en la secuencia de fotogramas + +Con el procesador listo, alimentar los fotogramas es una sola línea. El método `Process` devuelve un enumerable de objetos `OcrResult`, cada uno con el texto reconocido para su fotograma correspondiente. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **¿Qué ocurre detrás de escena?** Aspose.OCR normaliza internamente cada bitmap, ejecuta un reconocedor basado en redes neuronales y luego post‑procesa la salida para mejorar la puntuación y los saltos de línea. + +## Paso 4 – Mostrar el texto extraído + +Finalmente, iteramos sobre los resultados e imprimimos cada línea de subtítulo. También podrías escribirlos en un archivo SRT, una base de datos o enviarlos a un servicio de traducción. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Ejemplo completo funcional + +Al juntar todo, obtenemos un programa de consola autónomo: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Salida esperada (ejemplo)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Si el OCR tiene dificultades con un fotograma en particular, verás una cadena vacía – eso indica que debes ajustar la ROI o aumentar la tasa de extracción de fotogramas. + +## Problemas comunes y cómo solucionarlos + +| Problema | Por qué ocurre | Solución | +|----------|----------------|----------| +| **Caracteres basura** | Fotogramas de baja resolución o compresión pesada | Extrae fotogramas a mayor bitrate, o aumenta la escala del bitmap antes del OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No se devuelve texto** | La ROI no cubre realmente la banda de subtítulos | Verifica las coordenadas del rectángulo (usa una herramienta de captura de pantalla para medir). | +| **Cuello de botella de rendimiento** | Procesar cada fotograma a 30 fps es excesivo | Muestrea a 1‑2 fps para la mayoría de los flujos de subtítulos; aún puedes capturar cada cambio de subtítulo. | +| **FFmpeg no encontrado** | `ffmpeg.exe` no está en el `PATH` | Proporciona la ruta completa en `ProcessStartInfo.FileName` o instala FFmpeg globalmente. | + +## Extender la solución + +- **Exportar a SRT** – concatenar las marcas de tiempo con el texto OCR y escribir un archivo SubRip. +- **Soporte multilingüe** – establecer `ocrProcessor.Language = OcrLanguage.Spanish` (o cualquier idioma compatible). +- **Procesamiento en tiempo real** – canalizar los fotogramas directamente desde una transmisión en vivo en lugar de leer desde disco. + +Todas estas variaciones siguen girando en torno a las ideas principales de **extract frames from video**, **read text from video**, y **extract text from mp4**. + +## Conclusión + +Hemos recorrido un flujo de trabajo completo de **video subtitle ocr** en C#. Al extraer fotogramas del video, centrar el OCR en la banda de subtítulos e iterar sobre los resultados, puedes leer de forma fiable **read text from video** archivos como MP4. El código está listo para copiar y pegar, y el diseño modular te permite intercambiar cualquier decodificador de fotogramas que prefieras. + +¿Próximos pasos? Intenta exportar los resultados a un archivo SRT, experimenta con diferentes tamaños de ROI, o envía los subtítulos a una API de traducción para subtítulos multilingües. El cielo es el límite una vez que domines los conceptos básicos de extracción de texto de video. + +¡Feliz codificación, y que tus subtítulos siempre sean cristalinos! + +## ¿Qué deberías aprender a continuación? + +Los siguientes tutoriales cubren temas estrechamente relacionados que se basan en las técnicas demostradas en esta guía. Cada recurso incluye ejemplos de código completos y funcionales con explicaciones paso a paso para ayudarte a dominar características adicionales de la API y explorar enfoques de implementación alternativos en tus propios proyectos. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/swedish/net/ocr-configuration/_index.md index 7431b04a2..3a3c17c5b 100644 --- a/ocr/swedish/net/ocr-configuration/_index.md +++ b/ocr/swedish/net/ocr-configuration/_index.md @@ -61,6 +61,8 @@ Lås upp kraften i OCR‑bildigenkänning i .NET med Aspose.OCR. Extrahera text Lås upp kraftfulla OCR‑funktioner med Aspose.OCR för .NET. Extrahera text från bilder sömlöst. ### [OCROoperation med lista i OCR-bildigenkänning](./ocr-operation-with-list/) Lås upp potentialen i Aspose.OCR för .NET. Utför OCR‑bildigenkänning med listor utan ansträngning. Öka produktivitet och datautdragning i dina applikationer. +### [Hämta Aspose OCR-version i C# – Komplett guide](./get-aspose-ocr-version-in-c-complete-guide/) +Lär dig hur du programatiskt får reda på vilken version av Aspose OCR som används i din C#‑applikation. ### Vanliga användningsfall - **Extrahera textbilder** från skannade fakturor för automatiserad bokföring. @@ -99,4 +101,4 @@ A: Ja, `OcrResult`‑objektet ger förtroendevärden som du kan inspektera progr {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/swedish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..40618a083 --- /dev/null +++ b/ocr/swedish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: Hämta Aspose OCR-version i C# med ett enkelt kodexempel. Lär dig hur + du hämtar Aspose OCR‑bibliotekets version med OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: sv +og_description: Hämta Aspose OCR-version i C# snabbt. Den här handledningen visar + exakt hur du hämtar Aspose OCR-bibliotekets version med OcrEngine GetVersion. +og_title: Hämta Aspose OCR-version i C# – Komplett guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Hämta Aspose OCR-version i C# – Komplett guide +url: /sv/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hämta Aspose OCR-version i C# – Komplett guide + +Har du någonsin undrat hur du **hämta Aspose OCR-version** från ditt .NET‑projekt? Kanske felsöker du en versionstvist, eller så vill du bara logga den exakta biblioteksversionen som körs i produktion. Oavsett anledning har du hamnat på rätt ställe. + +I den här handledningen går vi igenom ett litet, fristående C#‑program som anropar `OcrEngine.GetVersion()` och skriver ut resultatet. I slutet vet du inte bara *hur* du hämtar versionen, utan också *varför* kontroll av versionen kan spara dig huvudvärk vid uppgradering av **Aspose OCR library**. + +## Vad du kommer att lära dig + +- Lägg till Aspose.OCR NuGet‑paketet i ett C#‑projekt +- Använd metoden `OcrEngine.GetVersion()` (ingångspunkten **ocrengine getversion**) +- Hantera möjliga undantag och verifiera utskriften +- Utöka kodsnutten för verkliga scenarier som loggning eller villkorliga funktionsväxlar + +Ingen förkunskap om OCR krävs—bara en grundläggande förståelse för C# och Visual Studio (eller din favorit‑IDE). Låt oss börja. + +--- + +## Steg 1: Ställ in projektet och hämta Aspose OCR‑biblioteket + +Innan du kan anropa några OCR‑relaterade API:er måste du ha **Aspose OCR library** refererad i ditt projekt. + +1. Öppna en terminal eller Package Manager Console i Visual Studio. +2. Kör följande kommando för att installera den senaste stabila versionen: + +```bash +dotnet add package Aspose.OCR +``` + +> **Proffstips:** Om du riktar dig mot .NET Framework istället för .NET Core, använd NuGet Package Manager‑gränssnittet och välj den version som matchar din runtime. Paketet innehåller klassen `OcrEngine` som vi kommer att använda senare. + +### Varför detta är viktigt + +När du installerar paketet kan versionen på disken skilja sig från den version som biblioteket rapporterar vid körning. Att fråga efter versionen via kod säkerställer att du läser exakt den build som CLR laddade, vilket är avgörande för felsökning och för regelefterlevnadsgranskningar. + +--- + +## Steg 2: Skriv minimal kod för att **hämta Aspose OCR-version** + +Skapa en ny konsolapp (`dotnet new console -n OcrVersionDemo`) och ersätt standard‑`Program.cs` med följande: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Förklaring av varje del** + +- `using Aspose.OCR;` importerar OCR‑namnrymden, så att vi kan anropa `OcrEngine`. +- `OcrEngine.GetVersion()` är den statiska metoden **ocrengine getversion** som returnerar en sträng som exempelvis "24.5.7". +- Att omsluta anropet i ett `try/catch`‑block skyddar dig mot oväntade körningsfel—kanske de inhemska binärerna inte finns på målmaskinen. +- Den interpolerade strängen `$"Aspose OCR version: {version}"` skriver ut en tydlig, människoläsbar rad. + +### Förväntad utskrift + +När du kör `dotnet run` i projektmappen bör du se något liknande: + +``` +Aspose OCR version: 24.5.7 +``` + +Om biblioteket inte kan laddas kommer felgrenen att skriva ut ett kort meddelande, vilket hjälper dig att snabbt identifiera problemet. + +--- + +## Steg 3: Verifiera att versionen matchar ditt NuGet‑paket + +Det är lätt att anta att den NuGet‑version du installerade är den som används vid körning, men miljöegenskaper kan påverka. För att dubbelkolla: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Att köra detta extra kodstycke kommer att skriva ut något liknande: + +``` +Assembly file version: 24.5.7.0 +``` + +Om de två värdena skiljer sig kan du ladda en äldre DLL från Global Assembly Cache (GAC) eller från en tidigare byggmapp. I så fall, rensa din lösning (`dotnet clean`) och bygg om. + +--- + +## Steg 4: Lägg in versionskontrollen i produktionsloggning + +De flesta verkliga applikationer skriver inte bara till konsolen; de skriver till en loggfil eller ett telemetrisystem. Här är ett snabbt exempel med `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Nu visas versionen i dina strukturerade loggar, vilket gör det enkelt att filtrera på `{Version}` senare. Detta mönster är särskilt praktiskt när du har flera mikrotjänster som var och en hämtar en potentiellt annan OCR‑DLL. + +--- + +## Vanliga frågor & kantfall + +### Vad händer om `GetVersion()` returnerar en tom sträng? + +Det indikerar vanligtvis en korrupt installation eller en saknad inhemsk beroende. Installera om NuGet‑paketet och verifiera att `Aspose.OCR.Native.dll` (eller den plattforms‑specifika binären) ligger bredvid din körbara fil. + +### Fungerar metoden på .NET Core 2.0? + +Ja, **Aspose OCR** stödjer .NET Standard 2.0 och högre, så alla .NET Core‑versioner som implementerar den standarden kan anropa `OcrEngine.GetVersion()`. Se bara till att du refererar rätt runtime‑identifierare (`win-x64`, `linux-x64` osv.) om du publicerar en fristående app. + +### Kan jag hämta versionen utan licensfil? + +Absolut. `GetVersion()` **kräver inte** en licens; den rapporterar bara bibliotekets byggnummer. Men om du försöker utföra OCR utan en giltig licens får du ett körningsundantag. Det är därför `try/catch`‑blocket i vårt kodexempel är värdefullt—det isolerar versionskontrollen från OCR‑exekveringsflödet. + +--- + +## Fullständigt fungerande exempel (klistra in och kör) + +Nedan är hela programmet, redo att klistras in i ett nytt konsolprojekt. Det inkluderar det valfria loggblocket, så du kan se både konsolutskrift och strukturerade loggar i aktion. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Kör det med `dotnet run` så ser du två rader som bekräftar versionen, samt en debug‑rad om du aktiverar `LogLevel.Debug`. + +--- + +## Slutsats + +Vi har gått igenom allt du behöver för att **hämta Aspose OCR-version** i en C#‑miljö—från att installera **Aspose OCR library**, anropa **ocrengine getversion**‑metoden, hantera fel, till att bädda in resultatet i produktionsloggning. Beväpnad med denna kunskap kan du nu på ett pålitligt sätt verifiera exakt vilken OCR‑build din applikation använder, undvika versionsrelaterade buggar och uppfylla regelefterlevnad utan att svettas. + +Nästa steg? Prova att kombinera denna versionskontroll med ett faktiskt OCR‑anrop (`OcrEngine` → `RecognizeImage`) och logga både versionen och igenkänningsresultatet. Du kan också utforska **retrieve aspose version**‑mönstret för andra Aspose‑produkter (PDF, Slides, Cells) för att hålla hela sviten synkroniserad. + +Lycka till med kodandet, och må dina OCR‑pipelines förbli skarpa! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i denna guide. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/swedish/net/ocr-optimization/_index.md index c5eb6aaed..fc78d9db1 100644 --- a/ocr/swedish/net/ocr-optimization/_index.md +++ b/ocr/swedish/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Utforska Aspose.OCR för .NET. Öka OCR‑noggrannheten med förbehandlingsfilte Förbättra OCR‑noggrannheten med Aspose.OCR för .NET. Korrigera stavningar, anpassa ordböcker och uppnå felfri textigenkänning utan ansträngning. ### [Spara flersidigt resultat som dokument i OCR Image Recognition](./save-multipage-result-as-document/) Lås upp potentialen i Aspose.OCR för .NET. Spara enkelt flersidiga OCR‑resultat som dokument med denna omfattande steg‑för‑steg‑guide. +### [Aspose OCR C#‑exempel – Aktivera GPU, sätt minnesgräns och bearbeta TIF‑bilder](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Lär dig hur du aktiverar GPU‑acceleration, begränsar minnesanvändning och bearbetar TIF‑bilder med Aspose OCR i C#. ## Vanliga frågor diff --git a/ocr/swedish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/swedish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..6ecf97630 --- /dev/null +++ b/ocr/swedish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C#-exempel som visar hur man ställer in GPU‑minnesgräns, laddar + bild för OCR och känner igen text från TIF‑filer med fullständig kod och tips. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: sv +og_description: 'Lär dig ett komplett Aspose OCR C#-exempel: aktivera GPU, ange GPU‑minnesgräns, + ladda en bild för OCR och känna igen text från TIF‑filer. Fullständig kod inkluderad.' +og_title: Aspose OCR C#-exempel – GPU-acceleration, minnesgräns och TIF-bearbetning +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C#-exempel – Aktivera GPU, ange minnesgräns och bearbeta TIF‑bilder +url: /sv/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – Aktivera GPU, Sätt Minnesgräns & Bearbeta TIF‑bilder + +Har du någonsin funderat på hur du får ut maximal prestanda ur **Aspose OCR C# example**‑koden när du hanterar massiva TIFF‑skanningar? Du är inte ensam. I många verkliga projekt—tänk dig att digitalisera arkiv eller extrahera data från högupplösta kvitton—är flaskhalsen inte OCR‑algoritmen i sig, utan hårdvaruanvändningen. + +Här är grejen: Aspose OCR stödjer GPU‑acceleration, men du måste berätta exakt hur mycket minne den får använda, ladda rätt bildtyp och slutligen hämta den igenkända texten från en .tif‑fil. Den här handledningen guidar dig genom varje steg, från installation av SDK till justering av GPU‑inställningarna, så att du kan köra OCR i blixtsnabb hastighet utan att tömma ditt GPU‑RAM. + +Vi kommer också att ströa in några “vad händer om”‑scenarier—som att hantera flersidiga TIFF‑filer eller falla tillbaka till CPU när ingen GPU finns—så att du får en robust lösning, inte bara ett engångssnutt. + +## Vad du behöver + +Innan vi dyker ner, se till att du har följande på din maskin: + +| Förutsättning | Varför det är viktigt | +|---------------|-----------------------| +| **.NET 6 SDK** (eller senare) | Aspose OCR riktar sig mot .NET Standard 2.0+, så vilken modern .NET‑version som helst fungerar. | +| **Aspose.OCR NuGet‑paket** (`Install-Package Aspose.OCR`) | Huvudbiblioteket som tillhandahåller `OcrEngine`, `GpuSettings` osv. | +| **CUDA 11+** (NVIDIA) **eller ROCm 5+** (AMD) | Krävs för GPU‑acceleration; SDK:n kontrollerar kompatibel drivrutin vid körning. | +| En **GPU med minst 2 GB VRAM** (vi sätter gränsen till 2048 MB) | Utan tillräckligt minne kan motorn tyst falla tillbaka till CPU. | +| En **högupplöst TIFF‑bild** du vill bearbeta | Aspose OCR kan läsa i princip alla rasterformat, men TIF är vanligt för skanningar. | +| Visual Studio 2022 (eller någon annan editor du föredrar) | För att bygga och debugga C#‑projektet. | + +Om någon av dessa saknas kommer koden fortfarande att kompilera, men du får inte de prestandafördelar vi siktar på. + +## Steg 1: Skapa Aspose OCR C# Example‑motorn + +Det första i varje **Aspose OCR C# example** är att instansiera OCR‑motorn. Tänk på `OcrEngine` som filmregissören—den koordinerar allt från bildladdning till textutdragning. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Proffstips:** Om du planerar att bearbeta många bilder i rad, håll en enda `OcrEngine` levande. Att återskapa den per bild ger overhead som kan överskugga OCR‑tiden. + +## Steg 2: Sätt GPU‑minnesgräns (och aktivera acceleration) + +Nu kommer delen som ofta får folk att snubbla: **sätt GPU‑minnesgräns**. Som standard försöker Aspose OCR använda så mycket VRAM som möjligt, vilket på en delad arbetsstation kan svälta andra program. Objektet `GpuSettings` låter dig begränsa allokeringen. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Varför sätta en minnesgräns? + +- **Stabilitet:** Förhindrar krascher på grund av minnesbrist när enorma bilder bearbetas. +- **Samspelet:** Gör att andra GPU‑tunga appar (t.ex. TensorFlow‑modeller) kan köras samtidigt. +- **Förutsägbarhet:** Gör prestandatester reproducerbara eftersom GPU:n inte börjar byta ut minne. + +Om du utelämnar `MemoryLimitMb` allokerar Aspose vad den anser nödvändigt, vilket kan vara okej på en dedikerad inferensserver men riskabelt på en utvecklar‑laptop. + +## Steg 3: Ladda bild för OCR + +Att ladda rätt filformat är nästa kritiska steg. Metoden `OcrImage.FromFile` upptäcker automatiskt bildtypen, men du bör ändå verifiera att filen finns och att den är en stödjande TIFF‑variant (t.ex. LZW‑komprimerad eller CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Hantera flersidiga TIFF‑filer + +Om din TIFF innehåller flera sidor läser Aspose OCR bara den första som standard. För att bearbeta alla sidor kan du loopa över `image.Pages` (tillgängligt i nyare SDK‑versioner) och skicka varje sida till motorn separat. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Snutten ovan demonstrerar ett **load image for OCR**‑mönster som fungerar för både enkel‑ och flersidiga filer. + +## Steg 4: Känn igen text från TIF (eller någon raster) + +Nu när bilden lever i minnet ber vi Aspose utföra sin magi. Metoden `Recognize` returnerar ett `OcrResult` som innehåller ren text, förtroendescore och till och med bound‑box‑information om du behöver den. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Varför detta fungerar bra med TIF + +- **Förlustfri kompression:** TIFF lagrar ofta råa pixeldata, vilket ger OCR‑motorn högsta möjliga detaljrikedom. +- **Flera färgrymder:** Aspose kan hantera gråskala, RGB eller till och med CMYK‑TIFF utan extra konverteringskod. + +Om du behöver justera språkpaket (t.ex. franska eller japanska), sätt `ocrEngine.Settings.Language = "fr"` innan du anropar `Recognize`. + +## Steg 5: Visa den igenkända texten + +Till sist skriver vi ut texten till konsolen. I en riktig applikation kanske du skriver till en databas, en JSON‑fil eller matar strängen in i en efterföljande NLP‑pipeline. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Förväntad utskrift + +Att köra programmet på en klar, 300 dpi‑skanning av en tryckt sida ger vanligtvis något i stil med: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Om bilden är suddig eller GPU‑minnesgränsen är för låg kan du se förvrängda tecken eller ett avklippt resultat. Att sänka `MemoryLimitMb` under bildens fotavtryck (ofta ~1 GB för en 6000×8000 pixel‑TIFF) kan få motorn att automatiskt falla tillbaka till CPU. + +## Fullt fungerande exempel + +Nedan är det kompletta, färdiga programmet. Kopiera‑klistra in det i ett nytt Console‑App‑projekt, ersätt `YOUR_DIRECTORY/large_photo.tif` med sökvägen till din egen TIFF och tryck **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Snabb checklista + +- ✅ **Aspose OCR C# example** kompilerad utan fel. +- ✅ **GPU aktiverad** (`Enable = true`). +- ✅ **GPU‑minnesgräns** satt till 2048 MB. +- ✅ **Bild laddad** från en TIF‑fil. +- ✅ **Text igenkänd** och skriven ut. + +## Vanliga fallgropar & hur du undviker dem + +| Symtom | Trolig orsak | Åtgärd | +|--------|--------------|--------| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA‑runtime saknas eller fel version. | Installera CUDA 11.x (eller 12.x) som matchar din drivrutin. | +| OCR returnerar tom sträng | Bilden är för mörk eller DPI < 150. | Förbehandla med `image.AdjustContrast()` eller resampla till 300 dpi. | +| Minneskrasch på GPU | `MemoryLimitMb` för låg för bilden. | Höj gränsen eller dela upp bilden i kakel via `image.Crop`. | +| `Unsupported image format`‑fel | TIFF använder en exotisk kompression (t.ex. JPEG‑2000). | Konvertera TIFF till ett stödjande format med ImageMagick innan OCR. | + +## Utöka demonstrationen + +Nu när du har ett stabilt **aspose ocr c# example**, kan du utforska: + +- **Batch‑bearbetning:** Loopa över en mapp med TIF‑filer, skriv varje resultat till en `.txt`‑fil. +- **Språkpaket:** `ocrEngine.Settings.Language = "es"` för spanska, eller ladda egna ordböcker. +- **Bound‑boxes:** Använd `ocrResult.Regions` för att få koordinater för varje ord—praktiskt för redigeringsverktyg. +- **CPU‑fallback:** Omge GPU‑blocket med try‑catch; vid fel, sätt `ocrEngine.Settings.Gpu.Enable = false` och försök igen. + +Dessa tillägg behåller kärnmönstret samtidigt som de ger extra värde för specifika användningsfall. + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna i den här guiden. Varje resurs innehåller kompletta kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra fler API‑funktioner och utforska alternativa implementeringssätt i egna projekt. + +- [Extrahera text från bild med Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extrahera text från bild – OCR‑optimering med Aspose.OCR för .NET](/ocr/english/net/ocr-optimization/) +- [Extrahera bildtext i C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/skew-angle-calculation/_index.md b/ocr/swedish/net/skew-angle-calculation/_index.md index 37d018aa2..d575197d6 100644 --- a/ocr/swedish/net/skew-angle-calculation/_index.md +++ b/ocr/swedish/net/skew-angle-calculation/_index.md @@ -23,15 +23,17 @@ Skevvinkel spelar en avgörande roll i OCR-bildigenkänning, vilket säkerställ ## [Beräkna skevningsvinkel i OCR-bildigenkänning](./calculate-skew-angle/) Ge dig ut på en resa för att bemästra skevvinkelberäkning i OCR-bildigenkänning med Aspose.OCR för .NET. Vår handledning förenklar processen och gör den tillgänglig för utvecklare på alla nivåer. Öka din textigenkänningsnoggrannhet och effektivitet idag! -## Enkel bildigenkänning med Aspose.OCR för .NET -Våra handledningar sträcker sig bortom teorin och går in i praktisk implementering. Lär dig hur du släpper lös kraften i Aspose.OCR för .NET, en robust lösning för bildigenkänning. Från strömbaserade beräkningar till enkel URI-integration, vi har dig täckt. - ## [Beräkna skevningsvinkel från Stream i OCR-bildigenkänning](./calculate-skew-angle-from-stream/) Utforska funktionerna i Aspose.OCR för .NET när vi guidar dig genom att beräkna snedvinklar från strömmar. Lyft dina bildigenkänningsprojekt med denna omfattande handledning. Precision och effektivitet är bara ett klick bort! ## [Beräkna skevningsvinkel från URI i OCR-bildigenkänning](./calculate-skew-angle-from-uri/) Integrera Aspose.OCR för .NET enkelt i dina projekt och förbättra OCR-bildigenkänningen. Vår handledning om att beräkna snedvinklar från URI:er ger dig möjlighet att ta precision och effektivitet i framkant. Håll dig framme i din utvecklingsresa! +## [OCR-roterad dokumenthandledning – Automatisk korrigering av snedvinkel och rotation i C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) + +## Enkel bildigenkänning med Aspose.OCR för .NET +Våra handledningar sträcker sig bortom teorin och går in i praktisk implementering. Lär dig hur du släpper lös kraften i Aspose.OCR för .NET, en robust lösning för bildigenkänning. Från strömbaserade beräkningar till enkel URI-integration, vi har dig täckt. + Sammanfattningsvis fungerar våra guider för beräkning av skevvinkel som din kompass inom området för OCR-bildigenkänning. Oavsett om du är en C#-entusiast eller en Java-entusiast, utrustar Aspose.OCR dig med verktygen för att erövra snedvinklar och lyfta dina projekt till nya höjder. Utforska, lär dig och revolutionera din utvecklingsresa med oss! ## Instruktioner för beräkning av sned vinkel ### [Beräkna skevningsvinkel i OCR-bildigenkänning](./calculate-skew-angle/) @@ -40,9 +42,10 @@ Utforska Aspose.OCR för .NET, en kraftfull OCR-lösning för korrekt textigenk Släpp lös kraften i Aspose.OCR för .NET, en robust lösning för bildigenkänning. Lär dig hur du beräknar snedvinklar utan ansträngning. ### [Beräkna skevningsvinkel från URI i OCR-bildigenkänning](./calculate-skew-angle-from-uri/) Utforska Aspose.OCR för .NET för att enkelt beräkna snedvinklar i OCR-bildigenkänning. Förbättra dina projekt med precision och effektivitet. +### [OCR-roterad dokumenthandledning – Automatisk korrigering av snedvinkel och rotation i C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/swedish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..1fb5f44dc --- /dev/null +++ b/ocr/swedish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: OCR‑handledning för roterade dokument som visar hur man automatiskt korrigerar + snedvridning och upptäcker rotation med Aspose OCR i C#. Lär dig steg för steg med + fullständig kod. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: sv +og_description: OCR-handledning för roterade dokument lär dig hur du automatiskt korrigerar + skevhet och upptäcker rotation med Aspose OCR i C#. Följ den kompletta guiden. +og_title: OCR roterat dokumenthandledning – Automatisk lutningskorrigering och rotationsfix + i C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR-handledning för roterade dokument – Automatisk snedjustering och rotationskorrigering + i C# +url: /sv/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR-roterad dokumenthandledning – Fullständig guide för C#-utvecklare + +Har du någonsin stött på en **ocr rotated document tutorial** när ett skannat formulär kom in sidledes eller snett? Du är inte ensam. De där sneda bilderna kan förstöra en ren textutvinning, men den goda nyheten är att Aspose OCR kan räta upp dem automatiskt för dig. + +I den här steg‑för‑steg‑guiden kommer vi att starta en `OcrEngine`, aktivera **automatisk skevkorrektion** och **automatisk rotationsdetektering**, köra motorn mot en roterad bild och skriva ut den rena texten. I slutet kommer du att veta exakt varför varje inställning är viktig, hur du justerar den för kantfall, och du kommer att ha ett färdigt C#‑program. + +## Vad du kommer att lära dig + +* Hur du installerar och refererar **Aspose OCR** i ett .NET‑projekt. +* Varför aktivering av `AutoCorrectSkew` och `AutoDetectRotation` är nyckeln till en pålitlig **ocr rotated document tutorial**. +* Hur du laddar vilken bild som helst (JPG, PNG, TIFF) och låter motorn göra det tunga arbetet. +* Tips för att hantera flersidiga PDF‑filer, lågupplösta skanningar och anpassade språkpaket. + +> **Förutsättningar:** Visual Studio 2022 (eller någon C#‑IDE), .NET 6+‑runtime och en giltig Aspose OCR‑licens (eller gratis provversion). Ingen tidigare OCR‑erfarenhet krävs. + +--- + +## Steg 1 – Installera Aspose OCR och konfigurera projektet + +Först och främst. Hämta NuGet‑paketet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Proffstips:** Om du använder en provlicens, placera filen `Aspose.OCR.lic` i samma mapp som din körbara fil, eller registrera den programatiskt med `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Skapa en ny konsolapp: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Nu har du en ren start för vår **ocr rotated document tutorial**. + +## Steg 2 – Initiera OCR‑motorn + +Motorn är hjärtat i processen. Tänk på den som en schweizisk armékniv för textutvinning; du behöver bara berätta vilka funktioner som ska aktiveras. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Varför dessa inställningar?** +* `AutoCorrectSkew` analyserar tecknens baslinje och roterar bilden tillräckligt för att göra raderna horisontella. +* `AutoDetectRotation` tittar på den övergripande orienteringen (0°, 90°, 180°, 270°) och vänder sidan om den är upp och ner. Utan dem skulle motorn läsa “pɹᴉʍ” istället för “word”. + +## Steg 3 – Ladda bilden du vill bearbeta + +Aspose OCR fungerar med alla vanliga rasterformat. Ersätt platshållarens sökväg med den faktiska platsen för ditt roterade formulär. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Kantfall:** Om du får en flersidig TIFF, använd `OcrImage.FromMultiPageTiff(filePath)` och loopa igenom `image.Pages`. + +## Steg 4 – Kör igenkänning + +Nu gör motorn magin. Den kommer först att räta upp bilden (tack vare våra skev‑/rotationsflaggor) och sedan hämta ut tecknen. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Om du behöver språkstöd utöver engelska, ställ in det innan du anropar `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Steg 5 – Skriv ut den igenkända texten + +Till sist, skriv ut den rena texten till konsolen — eller skicka den till en fil, en databas, vad som helst som passar ditt arbetsflöde. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Förväntad output** (förutsatt att exempelbilden innehåller “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Observera hur texten visas korrekt även om källbilden var roterad 90° och något skev. + +--- + +## Hantera vanliga fallgropar + +| Problem | Varför det händer | Lösning | +|------|----------------|-----| +| **Tom output** | Skevkorrektion inaktiverad eller bilden för mörk. | Aktivera `AutoCorrectSkew` (redan på) och öka bildkontrasten via `image.AdjustContrast(1.2)`. | +| **Skräptecken** | Fel språkinställning. | Ställ in `ocrEngine.Settings.Language` så att den matchar dokumentets språk. | +| **Prestandafördröjning på stora PDF‑filer** | Motorn bearbetar varje sida sekventiellt. | Använd `Parallel.ForEach` på `image.Pages` för att utnyttja fler‑kärniga CPU:er. | +| **Licensundantag** | Provperioden har gått ut. | Skaffa en permanent licens eller håll dig inom provgränserna (5 sidor per körning). | + +## Proffstips för en robust OCR‑roterad dokumenthandledning + +* **Batch‑bearbetning:** Packa in hela flödet i en metod som accepterar en mappväg, loopar över varje bild och skriver varje resultat till en `.txt`‑fil. +* **Förbehandling:** Ibland gynnas en brusig skanning av `image.Denoise()` innan igenkänning. +* **Efterbehandling:** Använd reguljära uttryck för att rensa vanliga OCR‑fel, t.ex. ersätt “0” med “O” endast när den omges av bokstäver. +* **Loggning:** Aspose OCR tillhandahåller `ocrEngine.Logger` – anslut den till en filloggare för att fånga varningar om låga förtroendesiffror. + +## Komplett, körklar kod + +Spara följande som `Program.cs` i ditt konsolprojekt. Den innehåller alla steg, kommentarer och en liten hjälpfunktion för batch‑bearbetning. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Kör den: + +```bash +dotnet run +``` + +Du bör se den rensade texten skrivas ut i konsolen, vilket bevisar att vår **ocr rotated document tutorial** fungerar från början till slut. + +## Slutsats + +Du har nu en komplett **ocr rotated document tutorial** som automatiskt korrigerar skevhet, upptäcker rotation och extraherar ren text med Aspose OCR i C#. Huvudpoängen? Att aktivera `AutoCorrectSkew` **och** `AutoDetectRotation` förvandlar en hopplöst lutande skanning till perfekt läsbar output med bara några rader kod. + +Härifrån kan du expandera till batch‑jobb, integrera språkpaket eller mata resultaten in i efterföljande analys‑pipelines. Vill du utforska **automatisk skevkorrektion** vidare? Kolla in Asposes bild‑förbehandlings‑API, eller experimentera med anpassade tröskelvärden för brusiga skanningar. + +Har du frågor om hantering av PDF‑filer, flersidiga TIFF‑filer eller integration med Azure Functions? Lämna en kommentar, och lycka till med kodandet! + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementeringsmetoder i dina egna projekt. + +- [ocr-dokumentläge – Detektera områdesläge i OCR‑bildigenkänning](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR‑handledning – Optisk teckenigenkänning](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/swedish/net/text-recognition/_index.md index fbefcc10b..231bdebfa 100644 --- a/ocr/swedish/net/text-recognition/_index.md +++ b/ocr/swedish/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Släpp lös kraften i Aspose.OCR för .NET. Lär dig att få OCR-resultat i JSON Förbättra dina .NET-applikationer med Aspose.OCR för effektiv bildtextigenkänning. Utforska OCR Detect Areas Mode för exakta resultat. ### [Känn igen PDF i OCR-bildigenkänning](./recognize-pdf/) Lås upp potentialen för OCR i .NET med Aspose.OCR. Extrahera text från PDF-filer utan ansträngning. Ladda ner nu för en sömlös integrationsupplevelse. +### [Utför OCR på PDF med Aspose.OCR – Komplett C#-guide](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Lär dig steg-för-steg hur du använder Aspose.OCR för att OCR:a PDF-filer i C#, för smidig textutvinning i dina .NET-applikationer. ### [Identifiera tabell i OCR-bildigenkänning](./recognize-table/) Lås upp potentialen hos Aspose.OCR för .NET med vår omfattande guide om att känna igen tabeller i OCR-bildigenkänning. +### [Utför OCR på bild med Aspose OCR – Hindi-guide](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Lär dig hur du utför OCR på en bild med Aspose OCR, med fokus på hindi-språket. +### [Hur man använder Aspose: Konvertera bild till HTML med OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Lär dig konvertera en bild till HTML med OCR med Aspose i en steg-för-steg-guide. +### [Utför OCR på bild och upptäck felstavade ord i C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Lär dig hur du med Aspose.OCR utför OCR på en bild och identifierar felstavade ord i C# för förbättrad textanalys. +### [Video Undertext OCR i C# – Komplett guide](./video-subtitle-ocr-in-c-complete-guide/) +Lär dig hur du använder Aspose.OCR i C# för att extrahera undertexter från video och konvertera dem till text. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/swedish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..ebd6b55a3 --- /dev/null +++ b/ocr/swedish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Hur man använder Aspose för att konvertera bild till HTML och extrahera + text från bild i C#. Lär dig att snabbt generera HTML från bild och OCR:a bild till + HTML. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: sv +og_description: Hur man använder Aspose för att konvertera bild till HTML, extrahera + text från bild och generera HTML från bild med OCR i C#. Följ den här kompletta + guiden. +og_title: 'Hur du använder Aspose: Konvertera bild till HTML med OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Så här använder du Aspose: Konvertera bild till HTML med OCR' +url: /sv/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man använder Aspose: Konvertera bild till HTML med OCR + +Har du någonsin undrat **hur man använder Aspose** för att förvandla en skannad bild till prydlig HTML? Kanske har du en magasin‑sida, ett kvitto eller en handskriven anteckning och du behöver texten och layouten bevarade för webbpublicering. Den goda nyheten är att du inte behöver skriva en egen parser eller kämpa med låg‑nivå bildbehandling—Aspose.OCR sköter det tunga arbetet åt dig. + +I den här handledningen går vi igenom ett **komplett, körbart exempel** som visar hur du **konverterar bild till HTML**, **extraherar text från bild**, och **genererar HTML från bild** med Aspose OCR‑biblioteket i C#. I slutet har du en liten konsolapp som skapar en HTML‑fil med den ursprungliga sidlayouten intakt, redo att placeras på vilken webbplats som helst. + +## Förutsättningar + +Innan vi dyker ner, se till att du har följande på din maskin: + +- **.NET 6.0 SDK** eller senare (koden fungerar med .NET Core och .NET Framework lika väl). +- **Visual Studio 2022** (eller någon annan editor du föredrar). +- **Aspose.OCR for .NET** – installera via NuGet: `dotnet add package Aspose.OCR`. +- En bildfil (JPEG/PNG) som du vill omvandla, t.ex. `magazine_page.jpg`. + +Inga extra konfigurationsfiler behövs; biblioteket levereras med allt som krävs för OCR och generering av HTML‑layout. + +## Steg 1: Skapa projektet och lägg till Aspose.OCR + +Först, skapa ett nytt konsolprojekt och hämta Aspose OCR‑paketet. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Proffstips:** Om du använder Visual Studio, högerklicka bara på projektet → *Manage NuGet Packages* → sök efter **Aspose.OCR** och installera det. Detta steg säkerställer att du kan **ocr image to html** utan några saknade referenser. + +## Steg 2: Initiera OCR‑motorn + +Kärnan i processen är klassen `OcrEngine`. Tänk på den som hjärnan som läser bilden och bestämmer hur resultatet ska levereras. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Här instansierar vi `OcrEngine`. Du behöver inte ange några autentiseringsuppgifter för den fria versionen; biblioteket använder sina inbyggda igenkänningsmodeller. + +## Steg 3: Ladda källbilden + +Nästa steg, peka motorn mot filen du vill bearbeta. Aspose tillhandahåller en bekväm metod `OcrImage.FromFile` som hanterar de flesta bildformat. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Byt ut `YOUR_DIRECTORY` mot den absoluta eller relativa sökvägen där din bild finns. Om bilden ligger i samma mapp som den körbara filen kan du bara använda `"magazine_page.jpg"`. + +## Steg 4: Känn igen och begär HTML med layout + +Detta är kärnan i handledningen. Genom att skicka `OutputFormat.HtmlWithLayout` talar vi om för Aspose att **generera HTML från bild** samtidigt som den ursprungliga placeringen av textblock, bilder och tabeller bevaras. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text`‑egenskapen innehåller nu ett komplett HTML‑dokument. Om du bara behövde ren text kunde du använda `OutputFormat.Text`, men vi fokuserar på **convert image to html** med layout‑fidelitet. + +## Steg 5: Spara HTML‑filen + +Till sist, skriv HTML‑strängen till disk. Detta ger dig en färdigfil som du kan öppna i vilken webbläsare som helst. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +När du kör programmet kommer `magazine.html` att skapas. Öppna den, så ser du att sidans text är placerad exakt som den såg ut i källbilden—perfekt för arkivering eller webbpublicering. + +## Fullständigt fungerande exempel + +Nedan är det **kompletta, kopiera‑och‑klistra‑klara** programmet. Inga delar har utelämnats, så du kan kompilera och köra det omedelbart efter att du har angett rätt sökvägar. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Förväntad utdata + +När du öppnar `magazine.html` i en webbläsare bör du se något liknande detta (förenklat för illustration): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +De exakta `style`‑attributen kommer att skilja sig beroende på originalbilden, men strukturen garanterar att **extract text from image** och **generate html from image** sker i ett enda, sömlöst steg. + +## Vanliga frågor & kantfall + +### Vad händer om bilden har låg upplösning? + +Aspose.OCR fungerar bäst med bilder som har minst **300 DPI**. Om din fil är suddig, försök förbehandla den med ett bildförbättringsbibliotek (t.ex. ImageSharp) innan du skickar den till OCR‑motorn. Låg kvalitet kan påverka både **extract text from image**‑noggrannheten och troheten i den genererade HTML‑layouten. + +### Kan jag styra OCR‑språket? + +Ja. Ställ in egenskapen `Language` på `OcrEngine` innan du anropar `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Detta förbättrar igenkänning när du hanterar icke‑engelska tecken. + +### Hur får jag ren text istället för HTML? + +Om du bara behöver den råa strängen, ersätt `OutputFormat.HtmlWithLayout` med `OutputFormat.Text`. Samma `recognitionResult.Text` kommer då bara att innehålla de extraherade tecknen. + +### Finns det ett sätt att bädda in bilder i den genererade HTML‑filen? + +Aspose.OCR kan bädda in den ursprungliga bilden som en base‑64‑data‑URI när du använder `OutputFormat.HtmlWithLayoutAndImages`. Detta är praktiskt när du vill ha en enda HTML‑fil utan externa resurser. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Hur hanterar man stora batcher? + +För batch‑bearbetning, omslut logiken i en `foreach`‑loop över en lista med filsökvägar. Att återanvända samma `OcrEngine`‑instans minskar overhead och snabbar upp **convert image to html**‑pipeline. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Tips för produktionsklar kod + +- **Dispose resources**: Både `OcrEngine` och `OcrImage` implementerar `IDisposable`. Omslut dem i `using`‑satser för att snabbt frigöra native‑minne. +- **Error handling**: Fånga `IOException` för filrelaterade problem och `OcrException` för igenkänningsproblem. +- **Performance**: Om du bearbetar många bilder, överväg att aktivera **parallelism** (`Parallel.ForEach`) men var medveten om CPU‑användning—OCR är CPU‑intensivt. +- **Logging**: Integrera en logger (t.ex. Serilog) för att fånga OCR‑tillförlitlighetspoäng (`recognitionResult.Confidence`) för kvalitetsövervakning. + +## Slutsats + +Vi har precis gått igenom **hur man använder Aspose** för att **konvertera bild till HTML**, **extrahera text från bild**, och **generera HTML från bild** i några enkla steg. Det kompletta kodexemplet visar hur du **ocr image to html** samtidigt som layouten bevaras, vilket gör det till en solid grund för alla dokument‑digitaliseringsprojekt. + +Från här kan du: + +- Experimentera med olika `OutputFormat`‑alternativ för att passa dina behov. +- Kombinera HTML‑utdata med ett CSS‑ramverk för responsiv styling. +- Mata in den extraherade texten i ett sökindex eller en maskininlärnings‑pipeline. + +Prova det, justera inställningarna, och se hur enkelt Aspose förvandlar bilder till webb‑klart innehåll. Om du stöter på problem, lämna en kommentar—lycklig kodning! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närbesläktade ämnen som bygger på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Konvertera bild till text – Utför OCR på bild från URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [Känna igen text i bild 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/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/swedish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..6b3da4514 --- /dev/null +++ b/ocr/swedish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,243 @@ +--- +category: general +date: 2026-06-03 +description: Utför OCR på bild och extrahera text från bilden med Aspose.OCR. Lär + dig hur du upptäcker felstavade ord och får stavningsförslag i en enda C#‑demo. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: sv +og_description: Utför OCR på en bild för att extrahera text från bilden, upptäck sedan + felstavade ord och få stavningsförslag med Aspose.OCR i C#. +og_title: Utför OCR på bild och upptäck felstavade ord i C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Utför OCR på bild och upptäck felstavade ord i C# +url: /sv/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utför OCR på bild och upptäck felstavade ord i C# + +Har du någonsin funderat på hur man **perform OCR on image**‑filer utan att dra i håret? Du är inte ensam. Oavsett om du digitaliserar gamla brev, skannar kvitton eller bygger ett smart dokumentflöde, är det första hindret att extrahera ren text från bilder. Den goda nyheten? Med Aspose.OCR kan du sätta ihop en lösning på några minuter, och bonusen är att du också kan **detect misspelled words** och **get spelling suggestions** i samma körning. + +I den här handledningen går vi igenom en komplett, färdig‑körbar C#‑konsolapp som **extracts text from image**, kör en engelsk stavningskontroll och skriver ut varje fel med praktiska korrigeringsförslag. När du är klar vet du exakt **how to extract text**, hur du ansluter stavnings‑API:t och hur den förväntade konsolutmatningen ser ut. + +## Vad du kommer att bygga + +- Ladda en bitmap (eller PNG) som innehåller typografiska fel. +- Kör Aspose.OCR för att **perform OCR on image** och få råa strängdata. +- Initiera den inbyggda engelska stavningskontrollen. +- **Detect misspelled words** och **get spelling suggestions** för varje ord. +- Skriv en snygg rapport till konsolen. + +Inga externa tjänster, inga krångliga HTTP‑anrop—bara ett enda NuGet‑paket och ett fåtal kodrader. + +## Förutsättningar + +- .NET 6.0 SDK eller senare (koden fungerar också på .NET Framework 4.7+). +- Visual Studio 2022 (eller någon annan editor du föredrar). +- Aspose.OCR för .NET NuGet‑paket (`Aspose.OCR`). +- En bildfil (`letter_with_typos.png`) placerad någonstans där du kan referera till den från projektet. + +Om du aldrig har använt Aspose tidigare, oroa dig inte—installationen av paketet är lika enkelt som att köra: + +```bash +dotnet add package Aspose.OCR +``` + +Nu dyker vi ner i implementationen. + +## Steg 1: Skapa projektet och installera Aspose.OCR + +Skapa ett nytt konsolprojekt och hämta OCR‑biblioteket: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +När återställningen är klar, öppna `Program.cs`. Vi kommer att ersätta standardinnehållet med hela demokoden senare, men först förklarar vi varför varje namnrymd är viktig. + +- `Aspose.OCR` – Kärnmotorn för OCR och bildhantering. +- `Aspose.OCR.SpellCheck` – Stavningskontrollverktyg som följer med biblioteket. +- `System` – Standard‑.NET‑basklasser (t.ex. `Console`). + +## Steg 2: Ladda bilden och utför OCR på bild + +Det första riktiga arbetet är att mata in bilden i OCR‑motorn. Aspose.OCR läser många format (PNG, JPEG, TIFF). Här är kodsnutten som gör det tunga lyftet: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Varför detta är viktigt:** `OcrImage.FromFile` abstraherar bort pixel‑nivådetaljer, medan `OcrEngine.Recognize` kör den tränade neurala modellen som översätter visuella glyfer till Unicode‑tecken. `ocrResult.Text`‑egenskapen innehåller nu den råa strängen—precis vad du behöver för att **extract text from image**. + +> **Proffstips:** Om din bild innehåller flera språk kan du sätta `ocrEngine.Language = OcrLanguage.Multilingual;` innan du anropar `Recognize`. + +## Steg 3: Initiera den engelska stavningskontrollen + +Aspose.OCR levereras med en inbyggd stavningskontroll som förstår engelska direkt ur lådan. Initieringen är en enradare: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Varför detta steg är avgörande:** OCR‑utdata kan innehålla felaktigt igenkända tecken (t.ex. “l” vs “1”) eller faktiska skrivfel från källdokumentet. Stavningskontrollen skannar strängen, lokaliserar misstänkta token och föreslår alternativ. + +## Steg 4: Upptäck felstavade ord och hämta stavningsförslag + +Nu matar vi OCR‑texten till kontrollen: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` är en samling där varje post innehåller det felaktiga ordet och en array med möjliga korrigeringar. + +## Steg 5: Skriv ut resultaten + +Till sist itererar vi över samlingen och skriver en mänskligt läsbar rapport: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Förväntad konsolutmatning + +Om `letter_with_typos.png` innehåller meningen: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Kommer demon att producera något i stil med: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Lägg märke till hur varje felstavning paras ihop med ett antal rimliga korrigeringar—precis vad du behöver när du bygger ett användarvänligt korrigerings‑UI. + +## Fullt fungerande exempel + +Nedan är det **kompletta, kopiera‑och‑klistra‑klara** programmet. Ersätt `YOUR_DIRECTORY` med den faktiska sökvägen till din bildfil. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Edge Cases att beakta** +> - **Tom bild:** Om OCR‑motorn returnerar en tom sträng kommer `spellChecker.Check` helt enkelt att returnera en tom samling—ingen krasch. +> - **Icke‑engelsk text:** Byt `OcrLanguage.English` mot `OcrLanguage.French` (eller något annat stödjert språk) för att **detect misspelled words** på andra språk. +> - **Stora dokument:** För flersidiga PDF‑filer skulle du loopa över varje sida, utföra OCR och sedan samla resultaten innan stavningskontrollen. + +## Visuell översikt (Bild‑alt‑text) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*Diagrammet ovan illustrerar den end‑to‑end‑pipeline som går från bild → OCR‑motor → råtext → stavningskontroll → förslag.* + +## Vanliga frågor & Proffstips + +| Fråga | Svar | +|----------|--------| +| **Behöver jag internetuppkoppling?** | Nej. Aspose.OCR körs helt lokalt; perfekt för offline‑ eller säkra miljöer. | +| **Hur exakt är stavningskontrollen?** | Den använder en ordlista med ~150 000 engelska ord och fuzzy‑matching, så de flesta vanliga skrivfel fångas. | +| **Kan jag anpassa ordlistan?** | Ja. `SpellChecker.AddUserDictionary("custom.txt")` låter dig ladda domänspecifika termer (t.ex. produktnamn). | +| **Vad händer om bilden är sned?** | OCR‑motorn upptäcker automatiskt orientering, men du kan manuellt anropa `ocrEngine.ImagePreprocessing.Rotate(angle)` för envisa fall. | +| **Finns det ett sätt att markera förslag i UI?** | När du har `misspellings`‑samlingen kan du mappa varje `entry.Word` tillbaka till dess position i `ocrResult.Text` och understryka det i en RichTextBox eller webbvy. | + +## Slutsats + +Vi har just visat dig **how to perform OCR on image**, **extract text from image**, och sedan **detect misspelled words** samt **get spelling suggestions**—allt med en koncis C#‑konsolapp. Kärnidén är enkel: låt Aspose.OCR göra det tunga arbetet med att känna igen tecken, och låt den inbyggda stavningskontrollen rensa upp resultatet. Därefter kan du bygga vidare till en fullständig dokumentbehandlingstjänst, integrera med ett webb‑API eller koppla in i en skrivbordsredigerare. + +Redo för nästa steg? Prova att byta språk till spanska, mata in en flersidig PDF eller bygga ett litet WPF‑gränssnitt som låter användare klicka på ett ord för att acceptera ett förslag. Byggstenarna finns redan på plats—fortsätt bara experimentera. + +Om du stöter på problem eller har idéer för utökningar, lämna en kommentar nedan. Lycka till med kodandet! + + +## Vad bör du lära dig härnäst? + + +Följande handledningar täcker närliggande ämnen som bygger vidare på teknikerna i den här guiden. Varje resurs innehåller kompletta kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra fler API‑funktioner och utforska alternativa implementeringssätt i dina egna projekt. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/swedish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..55d8fa22c --- /dev/null +++ b/ocr/swedish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Utför OCR på en bild med Aspose OCR i C#. Lär dig hur du laddar en bild + för OCR och extraherar hindi‑text från en bild offline med steg‑för‑steg‑kod. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: sv +og_description: Utför OCR på bild med Aspose OCR i C#. Denna handledning visar hur + du laddar en bild för OCR och extraherar hindi‑text från en bild offline, komplett + med körbar kod. +og_title: Utför OCR på bild – Aspose OCR Hindi‑guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Utför OCR på bild med Aspose OCR – Hindi‑guide +url: /sv/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utför OCR på bild med Aspose OCR – Hindi‑guide + +Har du någonsin behövt **utföra OCR på bild**‑filer men fastnat på hur du får ut Hindi‑tecken från dem? Du är inte ensam – många utvecklare stöter på detta hinder när de först försöker läsa icke‑latinska skript. Den goda nyheten är att Aspose OCR gör det ganska enkelt, och du kan till och med göra det helt offline. + +I den här guiden kommer vi att **ladda bild för OCR**, peka mot dina offline‑språkpaket och slutligen **extrahera Hindi‑text från bild** utan att någonsin röra internet. När du är klar har du en färdig C#‑konsolapp som läser ett Hindi‑kvitto och skriver ut texten i konsolen. + +## Vad du behöver + +- **.NET 6.0** eller senare (koden fungerar även på .NET Framework 4.7+) +- **Aspose.OCR for .NET** NuGet‑paket + `dotnet add package Aspose.OCR` +- En mapp som innehåller **offline‑språkresurser för Hindi** (ladda ner från Asposes portal) +- En bildfil med Hindi‑text, t.ex. `receipt_hindi.png` + +Det är allt – inga externa tjänster, inga API‑nycklar, bara rak kod. + +## Utför OCR på bild – Steg‑för‑steg‑implementation + +Nedan delar vi upp processen i sju tydliga steg. Varje steg förklaras **varför** det är viktigt, inte bara **vad** du ska skriva. + +### Steg 1: Skapa en OCR‑motorinstans + +Motorn är hjärtat i Aspose OCR. Att instansiera den ger dig åtkomst till alla inställningar du kommer att justera senare. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Varför?** +> Utan en `OcrEngine` har du inget objekt att anropa `Recognize` på. Tänk på den som “kameran” som senare skannar din bild. + +### Steg 2: Peka mot offline‑resurser + +Aspose levererar språkpaket som du kan lagra lokalt. Att sätta `ResourcesFolder` talar om för motorn var den ska leta. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Tips:** +> Använd en absolut sökväg under utveckling, byt sedan till en relativ sökväg eller en konfigurationsinställning för produktion. + +### Steg 3: Tvinga offline‑läge + +Du kanske undrar, “Behöver jag verkligen inaktivera online‑uppslag?” +Om du arbetar bakom en brandvägg eller bara vill ha deterministiska resultat, sätt `UseOfflineResources` till `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro‑tips:** +> Att låta flaggan vara `false` kan få motorn att ladda ner extra data, vilket ökar latensen och kan bryta mot säkerhetspolicyn. + +### Steg 4: Välj Hindi som igenkänningsspråk + +Här **extraherar vi Hindi‑text från bild** genom att tala om för motorn vilket språk som förväntas. Detta förbättrar noggrannheten avsevärt. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Varför det hjälper:** +> OCR‑motorer använder språk‑specifika teckenmodeller. Genom att låsa till Hindi undviker du att motorn gissar bland dussintals skript. + +### Steg 5: Ladda bild för OCR + +Nu **laddar vi bild för OCR**. Metoden `OcrImage.FromFile` läser bitmapen till ett format som motorn förstår. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Vanligt fallgropp:** +> Att ange en sökväg med snedstreck på Windows fungerar, men att använda `Path.Combine` gör din kod plattforms‑agnostisk. + +### Steg 6: Kör igenkänningen + +När allt är konfigurerat kör vi äntligen **utför OCR på bild** genom att anropa `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Vad händer?** +> Motorn skannar varje pixel, matchar mönster mot Hindi‑glyph‑databasen och bygger en sträng av Unicode‑tecken. + +### Steg 7: Skriv ut den igenkända texten + +Resultatobjektet innehåller en egenskap `Text` som håller den extraherade strängen. Vi skriver helt enkelt ut den i konsolen. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Förväntad utskrift:** +> Om `receipt_hindi.png` innehåller “भुगतान सफल”, kommer konsolen att skriva exakt den raden, med diakritiska tecken bevarade. + +## Ladda bild för OCR – Förbered resursen + +Om du undrar om du kan mata motorn med en ström istället för en fil, svaret är ja. Byt ut `OcrImage.FromFile` mot: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Varför använda en ström?** +> Strömmar låter dig arbeta med bilder lagrade i databaser, moln‑blobs eller inbäddade resurser – perfekt för skalbara tjänster. + +## Extrahera Hindi‑text från bild – Hantera kantfall + +1. **Saknat språkpaket** – Om Hindi‑paketet inte hittas kastar `Recognize` ett undantag. Omge anropet med try/catch och logga ett vänligt meddelande. +2. **Lågdpi‑bilder** – OCR‑noggrannheten sjunker under 300 dpi. Förbehandla bilden (ändra storlek, skärp) innan du laddar den. +3. **Blandade språk‑dokument** – Du kan aktivera flera språk: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Dessa justeringar säkerställer att ditt **utför OCR på bild**‑rutinskript förblir robust i produktion. + +## Köra hela exemplet + +Spara följande fil som `Program.cs`, ersätt platshållarsökvägarna och kör: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +När du kör `dotnet run` bör du se något liknande: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Om du får en tom sträng, dubbelkolla att **ResourcesFolder** pekar på mappen som innehåller `Hindi.traineddata` och att bilden är tillräckligt tydlig. + +## Slutsats + +Vi har gått igenom hur du **utför OCR på bild**‑filer med Aspose OCR, från **ladda bild för OCR** till **extrahera Hindi‑text från bild** i ett helt offline‑scenario. Den kompletta, körbara koden ovan ger dig en solid grund, och tipsen om strömmar, felhantering och flerspråkigt stöd hjälper dig att anpassa lösningen till verkliga projekt. + +Redo för nästa steg? Prova att byta språk till **OcrLanguage.Tamil** eller mata in bilder från en Azure Blob‑lagring. Du kan också experimentera med `ImagePreprocessing`‑inställningarna för att öka noggrannheten på brusiga kvitton. + +Har du frågor eller stött på problem? Lämna en kommentar – happy coding! + +![Perform OCR on image example + + +## Vad bör du lära dig härnäst? + + +Följande handledningar täcker nära besläktade ämnen som bygger vidare på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/swedish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..65cebd854 --- /dev/null +++ b/ocr/swedish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Utför OCR på PDF och konvertera skannad PDF till sökbar PDF med Aspose.OCR. + Lär dig hur du känner igen text från PDF och skapar sökbara PDF-filer på några minuter. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: sv +og_description: Utför OCR på PDF och skapa omedelbart en sökbar PDF. Den här handledningen + visar steg för steg hur du känner igen text från PDF med hjälp av Aspose.OCR. +og_title: Utför OCR på PDF – Komplett C#‑guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Utför OCR på PDF med Aspose.OCR – Komplett C#‑guide +url: /sv/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utför OCR på PDF med Aspose.OCR – Komplett C#-guide + +Har du någonsin undrat **hur man utför OCR på PDF**‑filer utan att kämpa med dussintals kommandoradsverktyg? Du är inte ensam. Oavsett om du digitaliserar fakturor, arkiverar gamla rapporter eller bara behöver en sökbar version av ett skannat kontrakt, så är det en spelväxlare att omvandla en statisk PDF till något du faktiskt kan söka i. + +I den här guiden går vi igenom **hur man skapar sökbara PDF**‑filer från skannade PDF‑filer (och även vanliga bilder) med Aspose.OCR för .NET. I slutet kommer du att kunna **läsa av text från PDF** med några rader C#‑kod, och du kommer att förstå varför varje steg behövs så att du kan anpassa lösningen till dina egna projekt. + +> **Snabb sammanfattning:** Hela processen reduceras till tre saker—initiera OCR‑motorn, mata in källan (PDF eller bild) och spara den sökbara PDF‑utdata. Låt oss dyka ner. + +--- + +## Vad du behöver + +| Förutsättning | Varför det är viktigt | +|--------------|----------------| +| **.NET 6.0+** (eller .NET Framework 4.6+) | Aspose.OCR riktar sig mot moderna runtime‑miljöer; äldre versioner kan sakna API‑uppdateringar. | +| **Aspose.OCR for .NET** NuGet‑paket | Tillhandahåller `OcrEngine`‑klassen och verktyg för PDF‑hantering. | +| **En giltig Aspose‑licens** (eller använd den kostnadsfria utvärderingen) | Utan licens får du en 30‑dagars utvärderingsgräns och vattenstämplar. | +| **En skannad PDF** (eller en bildfil) som du vill göra sökbar | Detta är källdokumentet för OCR. | +| **Visual Studio 2022** (eller någon C#‑redigerare) | Gör felsökning enklare, men alla IDE fungerar. | + +Du kan installera biblioteket med följande NuGet‑kommando: + +```bash +dotnet add package Aspose.OCR +``` + +> **Proffstips:** Om du arbetar i en CI‑pipeline, lägg till licensfilen i byggartefakterna och ladda den vid körning för att undvika hårdkodade sökvägar. + +## Utför OCR på PDF – Konfigurera Aspose.OCR + +Det första vi behöver är en ny `OcrEngine`‑instans. Tänk på den som hjärnan som kommer att läsa ditt dokument. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Varför en ny instans varje gång? Motorn håller konfiguration (som språkinställningar) som kan skilja sig åt per dokument. Att skapa en ny instans per körning garanterar en ren start och undviker korsprat mellan jobb. + +## Så skapar du sökbar PDF – Konfigurera lösenord (valfritt) + +Om din PDF är skyddad måste du ange lösenordet till motorn innan den kan läsa sidorna: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Att hoppa över detta steg på en skyddad fil kommer att kasta ett `PdfPasswordException`. Omslut alltid med try‑catch om du är osäker på skyddstatusen. + +## Konvertera skannad PDF till sökbar PDF – Ladda källan + +Aspose.OCR arbetar med abstraktionen `OcrImage`, som kan omfatta PDF‑filer, TIFF, JPEG osv. Så här hämtar du en skannad PDF till minnet: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Bakom kulisserna parsar `FromFile` varje sida till rasterbilder som OCR‑motorn kan bearbeta. Om du har en flersidig PDF kommer motorn automatiskt att iterera över varje sida. + +## Läs av text från PDF – Utför OCR + +Nu är vi i tutorialens kärna: be motorn att känna igen texten och skapa en sökbar PDF. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` instruerar motorn att bädda in ett osynligt textlager ovanpå de ursprungliga skannade bilderna. Den resulterande PDF‑filen behåller skannings bildkvalitet samtidigt som den blir fullt sökbar—precis vad du behöver för regelefterlevnadsgranskningar. + +## Konvertera bild till sökbar PDF – Spara resultatet + +Sist, skriv de binära data till disk: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary`‑egenskapen innehåller de råa PDF‑bytena. Du kan också strömma dem direkt till ett webbsvar om du bygger ett API. + +![Diagram som visar OCR‑konverteringsflödet för att skapa sökbar PDF](https://example.com/ocr-flow.png "Flödesdiagram för att utföra OCR på PDF") + +*Bildtext: Flödesdiagram för att utföra OCR på PDF som illustrerar hur en skannad PDF omvandlas till en sökbar PDF.* + +## Särskilda fall & Praktiska tips + +### 1. Stora filer & minneshantering +Om du bearbetar PDF‑filer som är större än 100 MB, överväg att använda `OcrEngineSettings.MemoryLimit` för att begränsa minnesanvändningen. Dessutom, bearbeta sidor i batcher för att undvika `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Språkstöd +Som standard antar Aspose.OCR engelska. För att känna igen andra språk, sätt `Language`‑egenskapen: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Multi‑trådade scenarier +`OcrEngine` är **inte** trådsäker. Om du behöver parallell bearbetning, skapa en separat motor per tråd. + +### 4. Felsökning av OCR‑noggrannhet +Du kan extrahera ren text från `ocrResult` för felsökning: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Om utskriften ser förvrängd ut, experimentera med `PreprocessSettings` (t.ex. räta upp, avlägsna fläckar) för att förbättra kvaliteten. + +### 5. Licensrelaterade fallgropar +När du kör utvärderingsversionen lägger Aspose till en vattenstämpel i den genererade PDF‑filen. Registrera din licens tidigt i applikationen: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +## Fullt fungerande exempel – Från början till slut + +Nedan är det kompletta, färdiga programmet som inkluderar alla tips ovan. Känn dig fri att kopiera och klistra in det i ett nytt konsolprojekt. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Förväntad output:** Efter körning kommer du att se en konsollinje som bekräftar filens plats. Öppna `output.pdf` i någon PDF‑visare; försök skriva ett ord du vet finns i den ursprungliga skanningen. Om texten markeras har du framgångsrikt **utfört OCR på PDF** och skapat ett sökbart dokument. + +## Vanliga frågor + +**Q: Kan jag använda detta för att konvertera en enskild bild (PNG/JPEG) till en sökbar PDF?** +A: Absolut. Ersätt `OcrImage.FromFile("input.pdf")` med sökvägen till din bildfil. Motorn rasteriserar bilden och bäddar in OCR‑lagret på samma sätt. + +**Q: Vad händer om min PDF har både skannade sidor och inbyggd text?** +A: Motorn lägger OCR‑texten ovanpå befintligt innehåll, så inbyggd text förblir markerbar medan skannade sidor blir sökbara. + +**Q: Hur exakt är OCR‑en?** +A: Noggrannheten beror på källans kvalitet. Rena, högupplösta skanningar (>300 dpi) ger >95 % noggrannhet. För brusiga dokument, aktivera `PreprocessSettings` (räta upp, avlägsna fläckar) innan du anropar `Recognize`. + +## Nästa steg – Utöka ditt OCR‑verktyg + +Nu när du kan **läsa av text från PDF** och **konvertera skannad PDF till sökbar PDF**, överväg dessa uppföljande ämnen: + +- **Batch‑behandling**: Loopa igenom en mapp med PDF‑filer och generera automatiskt sökbara versioner. +- **Textutdrag**: Använd `ocrResult.Text` för att fylla ett sökindex (t.ex. Elasticsearch). +- **Anpassade språkpaket**: Ladda ner ytterligare språkdatan från Aspose för att stödja asiatiska skript. +- **PDF/A‑kompatibilitet**: Kombinera Aspose.PDF med OCR‑utdata för att skapa arkiveringsklara PDF‑filer. + +Var och en av dessa bygger på de grundläggande stegen vi gick igenom, så du är väl förberedd att utöka din lösning. + +## Sammanfattning + +Vi har just visat dig **hur man utför OCR på PDF**‑filer med Aspose.OCR, omvandlat skannade PDF‑filer till fullt sökbara PDF‑filer, och även gått igenom hur man konverterar vanliga bilder till sökbara PDF‑filer. Koden + +## Vad bör du lära dig härnäst? + +Följande handledningar täcker närliggande ämnen som bygger på teknikerna som demonstrerats i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Känn igen PDF‑text – OCR‑operationer med Aspose.OCR för Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/swedish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..3690c8c92 --- /dev/null +++ b/ocr/swedish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Videoundertitel‑OCR‑handledning som visar hur man extraherar bildrutor + från video och läser text från videofiler som MP4 med Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: sv +og_description: Lär dig OCR för videounderrubriker med Aspose.OCR. Extrahera bildrutor + från video, läs text från video och extrahera text från MP4 på några minuter. +og_title: Video‑undertext‑OCR i C# – Steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: Videoundertexter OCR i C# – Komplett guide +url: /sv/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Video Undertext OCR i C# – Komplett Guide + +Har du någonsin behövt **video subtitle ocr** men varit osäker på var du ska börja? Du är inte ensam. Oavsett om du digitaliserar föreläsningsinspelningar, hämtar undertexter från träningsvideor, eller bara är nyfiken på att läsa text från video, så visar den här handledningen exakt hur du gör det med C# och Aspose.OCR. + +Under de kommande minuterna kommer vi att extrahera bildrutor från video, köra OCR på dessa bildrutor och slutligen visa undertexten bildruta för bildruta. I slutet kommer du att kunna **read text from video**‑filer — inklusive MP4 — utan att leta efter tredjepartsverktyg. + +## Vad du kommer att bygga + +1. Avkodar en MP4 (eller något annat stödd format) till enskilda `Bitmap`‑bildrutor. +2. Begränsar OCR‑området till undertextbandet så att motorn inte blir distraherad av hela bilden. +3. Bearbetar varje bildruta med Aspose’s `VideoOcrProcessor`. +4. Skriver ut den igenkända undertexten till konsolen. + +Ingen onödig fluff, bara ett fungerande end‑to‑end‑exempel som du kan använda i ett riktigt projekt. + +## Förutsättningar + +- **.NET 6.0** eller senare (koden fungerar också på .NET Framework 4.7+). +- **Aspose.OCR for .NET** – installera via NuGet: `Install-Package Aspose.OCR`. +- En videofil (MP4 fungerar utmärkt). +- Ett sätt att avkoda videobildrutor – demon använder en platshållarmetod, men du kan ansluta FFmpeg, OpenCV eller något bibliotek som returnerar `Bitmap`‑objekt. + +> Pro‑tips: Om du kör Windows fungerar paketet `System.Drawing.Common` bra för `Bitmap`. På Linux/macOS behöver du den inhemska `libgdiplus`‑beroendet. + +## Steg 1 – Extrahera bildrutor från video + +Det första hindret är att omvandla en rörlig bild till stillbilder. Metoden `GetVideoFrames` nedan är avsiktligt tom; ersätt den med din favoravkodare. Här är en snabb skiss med FFmpeg‑Core (bara för att illustrera datans form): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Varför detta är viktigt:** Att extrahera bildrutor ger OCR‑motorn en statisk bild att arbeta med, vilket dramatiskt förbättrar noggrannheten jämfört med att försöka läsa direkt från en videoström. + +## Steg 2 – Ställ in VideoOcrProcessor + +Nu när vi har en sekvens av `Bitmap`‑objekt kan vi skicka dem till Aspose.OCR. `VideoOcrProcessor` låter oss definiera ett **Region of Interest (ROI)** – perfekt för undertexter som vanligtvis sitter högst upp eller längst ner i bildrutan. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Varför begränsa ROI?** Genom att ignorera resten av bilden minskar vi brus, reducerar bearbetningstiden och undviker falska positiva resultat från bakgrundsgrafik. + +## Steg 3 – Kör OCR på bildsekvensen + +Med processorn klar är det en‑raders att mata in bildrutorna. `Process`‑metoden returnerar en enumerabel av `OcrResult`‑objekt, var och en innehållande den igenkända texten för motsvarande bildruta. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Vad händer under huven?** Aspose.OCR normaliserar internt varje bitmap, kör en neuronnätsbaserad igenkännare och efterbehandlar sedan resultatet för att förbättra interpunktion och radbrytningar. + +## Steg 4 – Visa den extraherade texten + +Till sist itererar vi över resultaten och skriver ut varje undertextrad. Du kan också skriva dem till en SRT‑fil, en databas eller skicka dem till en översättningstjänst. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Fullt fungerande exempel + +När allt sätts ihop får du ett självständigt konsolprogram: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Förväntad output (exempel)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Om OCR har problem med en viss bildruta kommer du att se en tom sträng – det är en signal om att justera ROI eller öka bildrutsextraktionsfrekvensen. + +## Vanliga fallgropar & hur du åtgärdar dem + +| Problem | Varför det händer | Åtgärd | +|-------|----------------|-----| +| **Garbage characters** | Lågre lösning eller kraftig komprimering | Extrahera bildrutor med högre bitrate, eller skala upp bitmap innan OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI täcker faktiskt inte undertextbandet | Verifiera rektangelkoordinaterna (använd ett skärmdumpsverktyg för att mäta). | +| **Performance bottleneck** | Bearbetning av varje bildruta vid 30 fps är överdrivet | Down‑sampla till 1‑2 fps för de flesta undertextströmmar; du kan fortfarande fånga varje undertextändring. | +| **FFmpeg not found** | `ffmpeg.exe` finns inte i `PATH` | Ange hela sökvägen i `ProcessStartInfo.FileName` eller installera FFmpeg globalt. | + +## Utöka lösningen + +- **Export to SRT** – sammanfoga tidsstämplarna med OCR‑texten och skriv en SubRip‑fil. +- **Multi‑language support** – sätt `ocrProcessor.Language = OcrLanguage.Spanish` (eller något annat stödd språk). +- **Real‑time processing** – pipra bildrutor direkt från en live‑ström istället för att läsa från disk. + +Alla dessa variationer kretsar fortfarande kring kärnidén **extract frames from video**, **read text from video**, och **extract text from mp4**. + +## Slutsats + +Vi har just gått igenom ett komplett **video subtitle ocr**‑arbetsflöde i C#. Genom att extrahera bildrutor från video, fokusera OCR på undertextbandet och iterera över resultaten kan du på ett pålitligt sätt **read text from video**‑filer såsom MP4. Koden är klar för copy‑paste, och den modulära designen låter dig byta ut vilken bildrutsavkodare du föredrar. + +Nästa steg? Prova att exportera resultaten till en SRT‑fil, experimentera med olika ROI‑storlekar, eller skicka undertexterna till ett översättnings‑API för flerspråkiga bildtexter. Himlen är gränsen när du har bemästrat grunderna i att extrahera text från video. + +Happy coding, and may your subtitles always be crystal‑clear! + +## Vad bör du lära dig härnäst? + +De följande handledningarna täcker närbesläktade ämnen som bygger vidare på teknikerna som demonstreras i den här guiden. Varje resurs innehåller kompletta fungerande kodexempel med steg‑för‑steg‑förklaringar för att hjälpa dig bemästra ytterligare API‑funktioner och utforska alternativa implementationsmetoder i dina egna projekt. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/thai/net/ocr-configuration/_index.md index 24051f2c0..c6059abc2 100644 --- a/ocr/thai/net/ocr-configuration/_index.md +++ b/ocr/thai/net/ocr-configuration/_index.md @@ -65,6 +65,9 @@ weight: 24 ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) ปลดล็อกศักยภาพของ Aspose.OCR for .NET ทำการจดจำภาพด้วย OCR ผ่านรายการได้อย่างง่ายดาย เพิ่มผลผลิตและการสกัดข้อมูลในแอปพลิเคชันของคุณ +### [รับเวอร์ชัน Aspose OCR ใน C# – คู่มือฉบับสมบูรณ์](./get-aspose-ocr-version-in-c-complete-guide/) +เรียนรู้วิธีดึงข้อมูลเวอร์ชันของ Aspose.OCR ในโค้ด C# อย่างละเอียดและง่ายดาย + ### การใช้งานทั่วไป - **ดึงข้อความจากภาพ** ของใบแจ้งหนี้ที่สแกนเพื่อการบัญชีอัตโนมัติ. - ทำดัชนีอาร์ไคฟ์เอกสารขนาดใหญ่เพื่อเป็นคลังข้อมูลที่ค้นหาได้. @@ -100,4 +103,4 @@ A: มี, วัตถุ `OcrResult` จะให้ค่าความเ {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/thai/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9bb7b4c64 --- /dev/null +++ b/ocr/thai/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: รับเวอร์ชัน Aspose OCR ใน C# ด้วยโค้ดสั้น ๆ เรียนรู้วิธีดึงเวอร์ชันของไลบรารี + Aspose OCR โดยใช้ OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: th +og_description: รับเวอร์ชัน Aspose OCR ใน C# อย่างรวดเร็ว บทเรียนนี้จะแสดงอย่างชัดเจนว่าต้องดึงเวอร์ชันของไลบรารี + Aspose OCR ด้วย OcrEngine GetVersion อย่างไร +og_title: รับเวอร์ชัน Aspose OCR ใน C# – คู่มือฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: รับเวอร์ชัน Aspose OCR ใน C# – คู่มือฉบับสมบูรณ์ +url: /th/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# รับเวอร์ชัน Aspose OCR ใน C# – คู่มือเต็ม + +เคยสงสัยไหมว่า **จะดึงเวอร์ชัน Aspose OCR** จากโปรเจกต์ .NET ของคุณได้อย่างไร? บางทีคุณอาจกำลังแก้ไขปัญหาความไม่ตรงกัน, หรือแค่ต้องการบันทึกหมายเลขบิลด์ของไลบรารีที่กำลังทำงานในสภาพแวดล้อม production ไม่ว่าด้วยเหตุผลใด คุณมาถูกที่แล้ว + +ในบทแนะนำนี้เราจะพาไปผ่านโปรแกรม C# ขนาดเล็กที่ทำงานอิสระซึ่งเรียก `OcrEngine.GetVersion()` แล้วพิมพ์ผลลัพธ์ออกมา เมื่อจบคุณจะรู้ไม่เพียง *วิธี* ดึงเวอร์ชัน, แต่ยัง *เหตุผล* ที่การตรวจสอบเวอร์ชันสามารถช่วยลดปัญหาเมื่ออัปเกรด **Aspose OCR library** ได้อีกด้วย + +## สิ่งที่คุณจะได้เรียน + +- เพิ่มแพคเกจ Aspose.OCR NuGet ลงในโปรเจกต์ C# +- ใช้เมธอด `OcrEngine.GetVersion()` (จุดเริ่มต้น **ocrengine getversion**) +- จัดการกับข้อยกเว้นที่อาจเกิดขึ้นและตรวจสอบผลลัพธ์ +- ขยายโค้ดตัวอย่างสำหรับสถานการณ์จริง เช่น การบันทึกลงล็อกหรือการเปิด/ปิดฟีเจอร์ตามเงื่อนไข + +ไม่จำเป็นต้องมีประสบการณ์กับ OCR มาก่อน—แค่มีพื้นฐาน C# และ Visual Studio (หรือ IDE ที่คุณชอบ) ก็พอ เริ่มกันเลย + +--- + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และดึงไลบรารี Aspose OCR + +ก่อนที่คุณจะเรียกใช้ API ที่เกี่ยวกับ OCR ใด ๆ คุณต้องอ้างอิง **Aspose OCR library** ในโปรเจกต์ของคุณก่อน + +1. เปิดเทอร์มินัลหรือ Package Manager Console ใน Visual Studio +2. รันคำสั่งต่อไปนี้เพื่อติดตั้งเวอร์ชันล่าสุดที่เสถียร: + +```bash +dotnet add package Aspose.OCR +``` + +> **เคล็ดลับ:** หากคุณกำลังทำงานกับ .NET Framework แทน .NET Core ให้ใช้ NuGet Package Manager UI แล้วเลือกเวอร์ชันที่ตรงกับ runtime ของคุณ แพคเกจนี้จะรวมคลาส `OcrEngine` ที่เราจะใช้ต่อไป + +### ทำไมจึงสำคัญ + +เมื่อคุณติดตั้งแพคเกจ เวอร์ชันของ assembly บนดิสก์อาจแตกต่างจากเวอร์ชันที่ไลบรารีรายงานขณะรันโค้ด การสอบถามเวอร์ชันผ่านโค้ดจึงทำให้คุณมั่นใจว่าได้อ่านบิลด์ที่ CLR โหลดจริง ซึ่งสำคัญต่อการดีบักและการตรวจสอบความสอดคล้อง + +--- + +## ขั้นตอนที่ 2: เขียนโค้ดขั้นต่ำเพื่อ **รับเวอร์ชัน Aspose OCR** + +สร้างแอปคอนโซลใหม่ (`dotnet new console -n OcrVersionDemo`) แล้วแทนที่ไฟล์ `Program.cs` เริ่มต้นด้วยโค้ดต่อไปนี้: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**คำอธิบายแต่ละส่วน** + +- `using Aspose.OCR;` นำเนมสเปซ OCR เข้ามาในสโคป ทำให้เราสามารถเรียก `OcrEngine` ได้ +- `OcrEngine.GetVersion()` คือเมธอดสแตติก **ocrengine getversion** ที่คืนค่าเป็นสตริงเช่น `"24.5.7"` +- การห่อเมธอดด้วยบล็อก `try/catch` ปกป้องคุณจากความประหลาดใจระหว่างรัน—เช่น ไฟล์ไบนารีเนทีฟไม่พบบนเครื่องเป้าหมาย +- สตริงอินเทอร์โพลิเต็ด `$"Aspose OCR version: {version}"` พิมพ์บรรทัดที่อ่านง่ายสำหรับมนุษย์ + +### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณรัน `dotnet run` ภายในโฟลเดอร์โปรเจกต์ คุณควรเห็นข้อความคล้ายดังนี้: + +``` +Aspose OCR version: 24.5.7 +``` + +หากไลบรารีไม่สามารถโหลดได้ โค้ดส่วนแสดงข้อผิดพลาดจะพิมพ์ข้อความสั้น ๆ ช่วยให้คุณระบุสาเหตุได้อย่างรวดเร็ว + +--- + +## ขั้นตอนที่ 3: ตรวจสอบว่าเวอร์ชันตรงกับแพคเกจ NuGet ของคุณ + +หลายคนอาจคิดว่าเวอร์ชัน NuGet ที่ติดตั้งคือเวอร์ชันที่ใช้งานขณะรัน แต่สภาพแวดล้อมบางอย่างอาจทำให้แตกต่างได้ เพื่อยืนยันอีกครั้ง: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +การรันสคริปต์เสริมนี้จะพิมพ์อะไรบางอย่างเช่น: + +``` +Assembly file version: 24.5.7.0 +``` + +หากสองค่าต่างกัน คุณอาจกำลังโหลด DLL เก่าจาก Global Assembly Cache (GAC) หรือจากโฟลเดอร์บิลด์เก่า ในกรณีนั้นให้ทำความสะอาดโซลูชัน (`dotnet clean`) แล้วคอมไพล์ใหม่ + +--- + +## ขั้นตอนที่ 4: นำการตรวจสอบเวอร์ชันไปใส่ในล็อกของ Production + +แอปพลิเคชันจริงส่วนใหญ่ไม่ได้พิมพ์แค่คอนโซลเท่านั้น แต่จะบันทึกลงไฟล์ล็อกหรือระบบ telemetry ตัวอย่างสั้น ๆ ด้านล่างใช้ `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +ตอนนี้เวอร์ชันจะปรากฏในล็อกที่มีโครงสร้าง ทำให้คุณสามารถกรองตาม `{Version}` ได้ง่ายในภายหลัง รูปแบบนี้มีประโยชน์มากเมื่อคุณมีหลาย micro‑service ที่อาจดึง DLL OCR ที่แตกต่างกัน + +--- + +## คำถามที่พบบ่อย & กรณีขอบ + +### ถ้า `GetVersion()` คืนค่าว่างล่ะ? + +โดยปกติหมายถึงการติดตั้งเสียหายหรือขาด dependency เนทีฟ ให้ติดตั้ง NuGet ใหม่และตรวจสอบให้ `Aspose.OCR.Native.dll` (หรือไบนารีเฉพาะแพลตฟอร์ม) อยู่เคียงข้างไฟล์ executable ของคุณ + +### เมธอดนี้ทำงานบน .NET Core 2.0 ได้หรือไม่? + +ได้, **Aspose OCR** รองรับ .NET Standard 2.0 ขึ้นไป ดังนั้น .NET Core ใด ๆ ที่ทำตามมาตรฐานนั้นก็เรียก `OcrEngine.GetVersion()` ได้ เพียงตรวจสอบให้ระบุ Runtime Identifier ที่ถูกต้อง (`win-x64`, `linux-x64` เป็นต้น) หากคุณเผยแพร่แอปแบบ self‑contained + +### สามารถดึงเวอร์ชันได้โดยไม่ต้องมีไฟล์ไลเซนส์หรือไม่? + +ทำได้แน่นอน `GetVersion()` **ไม่ต้อง** ไลเซนส์; มันเพียงรายงานหมายเลขบิลด์ของไลบรารีเท่านั้น อย่างไรก็ตาม หากคุณพยายามทำ OCR โดยไม่มีไลเซนส์ที่ถูกต้อง จะเกิดข้อยกเว้นระหว่างรัน นั่นคือเหตุผลที่ `try/catch` ในตัวอย่างของเรามีประโยชน์—มันแยกการตรวจสอบเวอร์ชันออกจากกระบวนการ OCR จริง + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ (Copy‑Paste Ready) + +ต่อไปนี้คือโปรแกรมทั้งหมดพร้อมวางลงในโปรเจกต์คอนโซลใหม่ มันรวมบล็อกล็อกแบบเลือกใช้ด้วย ทำให้คุณเห็นทั้งผลลัพธ์บนคอนโซลและล็อกที่มีโครงสร้างพร้อมกัน + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +รันด้วย `dotnet run` แล้วคุณจะเห็นสองบรรทัดยืนยันเวอร์ชัน พร้อมบรรทัด debug หากเปิด `LogLevel.Debug` + +--- + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **รับเวอร์ชัน Aspose OCR** ในสภาพแวดล้อม C# — ตั้งแต่การติดตั้ง **Aspose OCR library**, การเรียกเมธอด **ocrengine getversion**, การจัดการข้อผิดพลาด, จนถึงการฝังผลลัพธ์ลงในล็อกระดับ production ด้วยความเข้าใจนี้ คุณสามารถตรวจสอบบิลด์ OCR ที่แอปของคุณใช้อยู่ได้อย่างแม่นยำ ป้องกันบั๊กที่เกี่ยวกับเวอร์ชัน และตอบสนองข้อกำหนดการปฏิบัติตามโดยไม่ต้องกังวล + +ขั้นตอนต่อไป? ลองผสานการตรวจสอบเวอร์ชันนี้กับการเรียก OCR จริง (`OcrEngine` → `RecognizeImage`) แล้วบันทึกทั้งเวอร์ชันและผลการจดจำลงในล็อก คุณอาจอยากสำรวจรูปแบบ **retrieve aspose version** สำหรับผลิตภัณฑ์ Aspose อื่น ๆ (PDF, Slides, Cells) เพื่อให้ชุดเครื่องมือทั้งหมดของคุณสอดคล้องกัน + +Happy coding, and may your OCR pipelines stay sharp! + +## สิ่งที่คุณควรเรียนต่อไป + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [วิธีดึงผล OCR ด้วย Aspose.OCR สำหรับ .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [แยกข้อความจากภาพ C# พร้อมเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [วิธีทำ Batch OCR รูปภาพด้วย List ใน Aspose.OCR สำหรับ .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/thai/net/ocr-optimization/_index.md index f298064cd..268bf64b8 100644 --- a/ocr/thai/net/ocr-optimization/_index.md +++ b/ocr/thai/net/ocr-optimization/_index.md @@ -73,6 +73,9 @@ weight: 25 ### [บันทึกผลลัพธ์หลายหน้าเป็นเอกสารใน OCR Image Recognition](./save-multipage-result-as-document/) ปลดล็อกศักยภาพของ Aspose.OCR สำหรับ .NET บันทึกผลลัพธ์ OCR หลายหน้าเป็นเอกสารได้อย่างง่ายดายด้วยคู่มือขั้นตอนต่อขั้นตอนที่ครอบคลุมนี้. +### [ตัวอย่าง Aspose OCR C# – เปิดใช้งาน GPU, ตั้งค่าขีดจำกัดหน่วยความจำ & ประมวลผลภาพ TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +เรียนรู้วิธีใช้ GPU, กำหนดขีดจำกัดหน่วยความจำ และประมวลผลไฟล์ TIF ด้วย Aspose OCR ใน C# + ## คำถามที่พบบ่อย **Q:** ฉันสามารถแยกข้อความจากไฟล์ภาพที่มีหลายภาษาได้หรือไม่? diff --git a/ocr/thai/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/thai/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..d177a3a0a --- /dev/null +++ b/ocr/thai/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-03 +description: ตัวอย่าง Aspose OCR ด้วย C# แสดงวิธีตั้งค่าขีดจำกัดหน่วยความจำ GPU, โหลดภาพสำหรับ + OCR และจดจำข้อความจากไฟล์ TIF พร้อมโค้ดเต็มและเคล็ดลับ +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: th +og_description: 'เรียนรู้ตัวอย่าง Aspose OCR C# อย่างครบถ้วน: เปิดใช้งาน GPU, ตั้งค่าขีดจำกัดหน่วยความจำของ + GPU, โหลดภาพสำหรับ OCR และจดจำข้อความจากไฟล์ TIF. มีโค้ดเต็มรวมอยู่' +og_title: ตัวอย่าง Aspose OCR C# – การเร่งความเร็วด้วย GPU, ขีดจำกัดหน่วยความจำ และการประมวลผล + TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: ตัวอย่าง Aspose OCR C# – เปิดใช้งาน GPU, ตั้งค่าขีดจำกัดหน่วยความจำ และประมวลผลภาพ + TIF +url: /th/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Example – เปิดใช้งาน GPU, ตั้งค่าขีดจำกัดหน่วยความจำ & ประมวลผลภาพ TIF + +เคยสงสัยไหมว่าจะแสวงหาประสิทธิภาพสูงสุดจากโค้ด **Aspose OCR C# example** อย่างไรเมื่อต้องจัดการกับสแกน TIFF ขนาดใหญ่? คุณไม่ได้เป็นคนเดียว ในหลายโครงการจริง—เช่นการดิจิไทซ์เอกสารหรือการดึงข้อมูลจากใบเสร็จความละเอียดสูง—คอขวดไม่ได้อยู่ที่อัลกอริทึม OCR เอง แต่เป็นการใช้ฮาร์ดแวร์ + +สิ่งที่ต้องรู้คือ: Aspose OCR รองรับการเร่งความเร็วด้วย GPU แต่คุณต้องบอกให้มันทราบว่าต้องการใช้หน่วยความจำเท่าไหร่ โหลดประเภทภาพที่ถูกต้อง และสุดท้ายดึงข้อความที่รู้จำจากไฟล์ .tif การสอนนี้จะพาคุณผ่านทุกขั้นตอน ตั้งแต่การติดตั้ง SDK ไปจนถึงการปรับตั้งค่า GPU เพื่อให้คุณรัน OCR ด้วยความเร็วสูงโดยไม่ทำให้ RAM ของ GPU ระเบิด + +เราจะใส่สถานการณ์ “ถ้าเป็นอย่างนี้” บางอย่างเข้าไปด้วย—เช่นการจัดการกับ TIFF หลายหน้า หรือการย้อนกลับไปใช้ CPU เมื่อไม่มี GPU—เพื่อให้คุณได้โซลูชันที่แข็งแรง ไม่ใช่แค่โค้ดสั้น ๆ ครั้งเดียว + +## สิ่งที่คุณต้องการ + +| ข้อกำหนดเบื้องต้น | เหตุผลที่สำคัญ | +|--------------|----------------| +| **.NET 6 SDK** (or later) | Aspose OCR รองรับ .NET Standard 2.0+ ดังนั้นเวอร์ชัน .NET ใด ๆ ที่ใหม่ก็ทำงานได้ | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | ไลบรารีหลักที่ให้ `OcrEngine`, `GpuSettings`, เป็นต้น | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | จำเป็นสำหรับการเร่งความเร็วด้วย GPU; SDK จะตรวจสอบไดรเวอร์ที่เข้ากันได้ในขณะรัน | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | หากไม่มีหน่วยความจำเพียงพอ เอนจินอาจย้อนกลับไปใช้ CPU อย่างเงียบ ๆ | +| A **high‑resolution TIFF** image you want to process | Aspose OCR สามารถอ่านรูปแบบแรสเตอร์ได้เกือบทั้งหมด แต่ TIF เป็นรูปแบบที่พบบ่อยสำหรับการสแกน | +| Visual Studio 2022 (or any editor you like) | สำหรับการสร้างและดีบักโปรเจค C# | + +หากขาดรายการใดรายการหนึ่ง โค้ดยังคงคอมไพล์ได้ แต่คุณจะไม่เห็นประสิทธิภาพที่เราต้องการ + +## ขั้นตอนที่ 1: สร้าง Aspose OCR C# Example Engine + +สิ่งแรกในทุก **Aspose OCR C# example** คือการสร้างอินสแตนซ์ของ OCR engine คิดว่า `OcrEngine` เหมือนผู้กำกับภาพยนตร์—มันประสานงานทุกอย่างตั้งแต่การโหลดภาพจนถึงการสกัดข้อความ + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **เคล็ดลับ:** หากคุณวางแผนจะประมวลผลหลายภาพต่อเนื่อง ให้คง `OcrEngine` ตัวเดียวไว้ การสร้างใหม่ต่อภาพจะเพิ่มภาระที่อาจทำให้เวลา OCR ลดลงอย่างมาก + +## ขั้นตอนที่ 2: ตั้งค่าขีดจำกัดหน่วยความจำ GPU (และเปิดการเร่งความเร็ว) + +ต่อมาคือส่วนที่มักทำให้หลายคนสับสน: **ตั้งค่าขีดจำกัดหน่วยความจำ GPU** โดยค่าเริ่มต้น Aspose OCR จะพยายามใช้ VRAM ให้มากที่สุด ซึ่งบนเครื่องทำงานร่วมกันอาจทำให้แอปพลิเคชันอื่นขาดแคลน `GpuSettings` ช่วยให้คุณจำกัดการจัดสรรได้ + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### ทำไมต้องตั้งค่าขีดจำกัดหน่วยความจำ? + +- **ความเสถียร:** ป้องกันการล่มจากหน่วยความจำเต็มเมื่อประมวลผลภาพขนาดมหาศาล +- **การทำงานร่วมกัน:** ให้แอปที่ใช้ GPU หนักอื่น (เช่นโมเดล TensorFlow) ทำงานเคียงข้างได้ +- **ความคาดการณ์ได้:** ทำให้การทดสอบประสิทธิภาพทำซ้ำได้ เพราะ GPU จะไม่เริ่มสวอป + +หากคุณละเว้น `MemoryLimitMb` Aspose จะจัดสรรตามที่เห็นว่าเหมาะสม ซึ่งอาจใช้ได้บนเซิร์ฟเวอร์ inference เฉพาะกิจ แต่เสี่ยงบนแล็ปท็อปของนักพัฒนา + +## ขั้นตอนที่ 3: โหลดภาพสำหรับ OCR + +การโหลดรูปแบบไฟล์ที่ถูกต้องเป็นส่วนสำคัญต่อไป วิธี `OcrImage.FromFile` จะตรวจจับประเภทภาพโดยอัตโนมัติ แต่คุณควรตรวจสอบว่าไฟล์มีอยู่และเป็นรูปแบบ TIFF ที่รองรับ (เช่น LZW‑compressed หรือ CCITT‑G4) ด้วย + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### การจัดการ TIFF หลายหน้า + +หาก TIFF ของคุณมีหลายหน้า Aspose OCR จะอ่านหน้าแรกเท่านั้นโดยค่าเริ่มต้น เพื่อประมวลผลทุกหน้า คุณสามารถวนลูป `image.Pages` (มีใน SDK เวอร์ชันใหม่) แล้วส่งแต่ละหน้าต่อไปยังเอนจินแยกกัน + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +โค้ดข้างต้นแสดงรูปแบบ **load image for OCR** ที่ทำงานได้ทั้งไฟล์หน้าเดียวและหลายหน้า + +## ขั้นตอนที่ 4: จดจำข้อความจาก TIF (หรือ raster ใด ๆ) + +เมื่อภาพอยู่ในหน่วยความจำแล้ว เราขอให้ Aspose ทำเวทมนตร์ของมัน วิธี `Recognize` จะคืนค่า `OcrResult` ที่มีข้อความธรรมดา คะแนนความมั่นใจ และแม้แต่ข้อมูล bounding‑box หากคุณต้องการ + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### ทำไมวิธีนี้จึงทำงานได้ดีกับ TIF + +- **การบีบอัดแบบไม่สูญเสีย:** TIFF มักเก็บข้อมูลพิกเซลดิบ ทำให้เอนจิน OCR ได้ความละเอียดสูงสุด +- **หลายสีสัน:** Aspose สามารถจัดการ TIFF แบบ grayscale, RGB หรือแม้แต่ CMYK ได้โดยไม่ต้องเขียนโค้ดแปลงเพิ่มเติม + +หากต้องการปรับแพ็คเกจภาษา (เช่น ฝรั่งเศสหรือญี่ปุ่น) ให้ตั้งค่า `ocrEngine.Settings.Language = "fr"` ก่อนเรียก `Recognize` + +## ขั้นตอนที่ 5: แสดงข้อความที่จดจำได้ + +สุดท้าย เราแสดงข้อความออกที่คอนโซล ในแอปพลิเคชันจริงคุณอาจบันทึกลงฐานข้อมูล ไฟล์ JSON หรือส่งสตริงนี้ต่อไปยัง pipeline NLP + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +การรันโปรแกรมบนสแกนหน้าพิมพ์ที่ชัดเจน 300 dpi มักให้ผลลัพธ์ประมาณนี้: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +หากภาพเบลอหรือขีดจำกัดหน่วยความจำ GPU ต่ำเกินไป คุณอาจเห็นอักขระผิดรูปหรือผลลัพธ์ที่ถูกตัดสั้น การลด `MemoryLimitMb` ต่ำกว่าขนาดของภาพ (มักประมาณ ~1 GB สำหรับ TIFF 6000×8000 พิกเซล) อาจทำให้เอนจินย้อนกลับไปใช้ CPU โดยอัตโนมัติ + +## ตัวอย่างทำงานเต็ม + +ด้านล่างเป็นโปรแกรมที่สมบูรณ์พร้อมรัน คัดลอกและวางลงในโปรเจค Console App ใหม่ แทนที่ `YOUR_DIRECTORY/large_photo.tif` ด้วยพาธของไฟล์ TIFF ของคุณเอง แล้วกด **F5** + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### รายการตรวจสอบอย่างเร็ว + +- ✅ **Aspose OCR C# example** คอมไพล์โดยไม่มีข้อผิดพลาด. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** ตั้งค่าเป็น 2048 MB. +- ✅ **Image loaded** จากไฟล์ TIF. +- ✅ **Text recognized** และพิมพ์ออก. + +## ข้อผิดพลาดทั่วไป & วิธีหลีกเลี่ยง + +| อาการ | สาเหตุที่เป็นไปได้ | วิธีแก้ | +|---------|-------------------|----------| +| `System.DllNotFoundException: cudart64_110.dll` | ไม่ได้ติดตั้ง CUDA runtime หรือเวอร์ชันไม่ตรงกัน. | ติดตั้ง CUDA 11.x (หรือ 12.x) ให้ตรงกับไดรเวอร์ของคุณ. | +| OCR returns empty string | ภาพมืดเกินไปหรือ DPI < 150. | ทำการพรี‑โปรเซสด้วย `image.AdjustContrast()` หรือปรับขนาดเป็น 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` ต่ำเกินไปสำหรับภาพ. | เพิ่มขีดจำกัดหรือแบ่งภาพเป็นส่วนย่อยโดยใช้ `image.Crop`. | +| `Unsupported image format` error | TIFF ใช้การบีบอัดแปลกใหม่ (เช่น JPEG‑2000). | แปลง TIFF เป็นรูปแบบที่รองรับด้วย ImageMagick ก่อนทำ OCR. | + +## ขยายการสาธิต + +เมื่อคุณมี **aspose ocr c# example** ที่มั่นคงแล้ว คุณอาจต้องการสำรวจ: + +- **การประมวลผลเป็นชุด:** วนลูปโฟลเดอร์ของ TIFs แล้วบันทึกผลลัพธ์แต่ละไฟล์เป็นไฟล์ `.txt` +- **แพ็คเกจภาษา:** `ocrEngine.Settings.Language = "es"` สำหรับภาษาสเปน หรือโหลดพจนานุกรมแบบกำหนดเอง +- **กล่องขอบเขต:** ใช้ `ocrResult.Regions` เพื่อรับพิกัดของแต่ละคำ—สะดวกสำหรับเครื่องมือการลบข้อมูล +- **CPU fallback:** ห่อบล็อก GPU ด้วย try/catch; หากล้มเหลว ให้ตั้งค่า `ocrEngine.Settings.Gpu.Enable = false` แล้วลองใหม่ + +These extensions keep the core pattern intact while adding value for specific use‑ + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบอื่นในโปรเจคของคุณ + +- [สกัดข้อความจากภาพโดยใช้ Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [สกัดข้อความจากภาพ – การปรับประสิทธิภาพ OCR ด้วย Aspose.OCR สำหรับ .NET](/ocr/english/net/ocr-optimization/) +- [สกัดข้อความจากภาพ C# พร้อมการเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/skew-angle-calculation/_index.md b/ocr/thai/net/skew-angle-calculation/_index.md index 2ebf1b3f5..2dc5370b2 100644 --- a/ocr/thai/net/skew-angle-calculation/_index.md +++ b/ocr/thai/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ url: /th/net/skew-angle-calculation/ ปลดปล่อยพลังของ Aspose.OCR สำหรับ .NET ซึ่งเป็นโซลูชันที่แข็งแกร่งสำหรับการจดจำรูปภาพ เรียนรู้วิธีการคำนวณมุมเอียงได้อย่างง่ายดาย ### [คำนวณมุมเอียงจาก URI ในการรับรู้ภาพ OCR](./calculate-skew-angle-from-uri/) สำรวจ Aspose.OCR สำหรับ .NET เพื่อคำนวณมุมเอียงในการจดจำรูปภาพ OCR ได้อย่างง่ายดาย ปรับปรุงโครงการของคุณด้วยความแม่นยำและมีประสิทธิภาพ +### [บทแนะนำเอกสารที่หมุน OCR – การแก้ไขมุมเอียงและการหมุนอัตโนมัติใน C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +เรียนรู้วิธีจัดการเอกสารที่หมุนใน OCR ด้วยการแก้ไขมุมเอียงและการหมุนอัตโนมัติใน C# ด้วย Aspose.OCR {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/thai/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..8d931ad1a --- /dev/null +++ b/ocr/thai/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,270 @@ +--- +category: general +date: 2026-06-03 +description: บทเรียน OCR สำหรับเอกสารที่หมุน ซึ่งแสดงวิธีแก้ไขการเอียงอัตโนมัติและตรวจจับการหมุนโดยใช้ + Aspose OCR ใน C# เรียนรู้แบบขั้นตอนต่อขั้นตอนพร้อมโค้ดเต็ม +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: th +og_description: บทแนะนำการใช้ OCR กับเอกสารที่หมุนสอนวิธีแก้ไขการเอียงอัตโนมัติและตรวจจับการหมุนโดยใช้ + Aspose OCR ใน C# ปฏิบัติตามคู่มือฉบับเต็ม +og_title: บทเรียน OCR เอกสารที่หมุน – แก้ไขการเอียงอัตโนมัติและการหมุนใน C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: บทเรียน OCR เอกสารที่หมุน – แก้ไขการเอียงและการหมุนอัตโนมัติใน C# +url: /th/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# คู่มือ OCR เอกสารหมุน – คู่มือเต็มสำหรับนักพัฒนา C# + +เคยเจอ **ocr rotated document tutorial** บ้างไหมเมื่อแบบฟอร์มสแกนมามุมเอียงหรือหมุน sideways? คุณไม่ได้เป็นคนเดียว ภาพที่เอียงเหล่านั้นอาจทำให้การสกัดข้อความไม่สะอาด แต่ข่าวดีคือ Aspose OCR สามารถจัดเรียงให้ตรงได้โดยอัตโนมัติ + +ในคู่มือขั้นตอนนี้ เราจะสร้าง `OcrEngine` เปิดใช้งาน **automatic skew correction** และ **auto detect rotation** รันเอนจินกับภาพที่หมุน และพิมพ์ข้อความที่สะอาด สุดท้ายคุณจะรู้ว่าทำไมแต่ละการตั้งค่าถึงสำคัญ วิธีปรับให้เหมาะกับกรณีขอบ และจะมีโปรแกรม C# พร้อมรัน + +## สิ่งที่คุณจะได้เรียนรู้ + +* วิธีติดตั้งและอ้างอิง **Aspose OCR** ในโครงการ .NET +* ทำไมการเปิดใช้งาน `AutoCorrectSkew` และ `AutoDetectRotation` ถึงเป็นกุญแจสำคัญของ **ocr rotated document tutorial** ที่เชื่อถือได้ +* วิธีโหลดภาพใดก็ได้ (JPG, PNG, TIFF) แล้วให้เอนจินทำงานหนัก +* เคล็ดลับการจัดการ PDF หลายหน้า, การสแกนความละเอียดต่ำ, และแพ็คเกจภาษาแบบกำหนดเอง + +> **Prerequisites:** Visual Studio 2022 (หรือ IDE C# ใดก็ได้), .NET 6+ runtime, และใบอนุญาต Aspose OCR ที่ถูกต้อง (หรือทดลองใช้ฟรี) ไม่จำเป็นต้องมีประสบการณ์ OCR มาก่อน + +--- + +## ขั้นตอนที่ 1 – ติดตั้ง Aspose OCR และตั้งค่าโครงการ + +เริ่มต้นก่อนอื่น ให้ดึงแพคเกจ NuGet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** หากคุณใช้ไลเซนส์ทดลอง ให้วางไฟล์ `Aspose.OCR.lic` ไว้ในโฟลเดอร์เดียวกับไฟล์ executable ของคุณ หรือทำการลงทะเบียนแบบโปรแกรมโดยใช้ `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +สร้างแอปคอนโซลใหม่: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +ตอนนี้คุณมีพื้นฐานที่สะอาดสำหรับ **ocr rotated document tutorial** ของเรา + +## ขั้นตอนที่ 2 – เริ่มต้น OCR Engine + +เอนจินเป็นหัวใจของกระบวนการ คิดว่ามันเป็นมีดสวิสอเนกประสงค์สำหรับการสกัดข้อความ; คุณเพียงแค่บอกให้มันเปิดฟีเจอร์ที่ต้องการ + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**ทำไมต้องตั้งค่าเหล่านี้?** +* `AutoCorrectSkew` วิเคราะห์เส้นฐานของอักขระและหมุนภาพให้พอเหมาะเพื่อทำให้บรรทัดเป็นแนวนอน +* `AutoDetectRotation` ตรวจสอบการวางแนวโดยรวม (0°, 90°, 180°, 270°) และพลิกหน้าหากกลับหัว หากไม่ได้เปิดใช้ เอนจินจะอ่านเป็น “pɹᴉʍ” แทน “word” + +## ขั้นตอนที่ 3 – โหลดภาพที่ต้องการประมวลผล + +Aspose OCR ทำงานกับรูปแบบแรสเตอร์ทั่วไปทั้งหมด แทนที่พาธตัวอย่างด้วยตำแหน่งจริงของแบบฟอร์มที่หมุนของคุณ + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** หากคุณได้รับไฟล์ TIFF หลายหน้า ให้ใช้ `OcrImage.FromMultiPageTiff(filePath)` และวนลูปผ่าน `image.Pages`. + +## ขั้นตอนที่ 4 – รันการจดจำ + +ตอนนี้เอนจินทำเวทมนต์ มันจะแรกจัดเรียงภาพให้ตรง (ขอบคุณฟลักก์การแก้เอียง/การหมุน) แล้วดึงอักขระออกมา + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +หากคุณต้องการสนับสนุนภาษานอกเหนือจากภาษาอังกฤษ ให้ตั้งค่าก่อนเรียก `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## ขั้นตอนที่ 5 – แสดงผลข้อความที่จดจำได้ + +สุดท้ายให้ดัมพ์ข้อความที่สะอาดไปที่คอนโซล—หรือส่งต่อไปยังไฟล์, ฐานข้อมูล, หรืออะไรก็ตามที่เข้ากับ workflow ของคุณ + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Expected output** (assuming the sample image contains “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +สังเกตว่าข้อความปรากฏอย่างถูกต้องแม้ภาพต้นฉบับจะหมุน 90° และมีการเอียงเล็กน้อย + +--- + +## การจัดการกับปัญหาทั่วไป + +| ปัญหา | สาเหตุ | วิธีแก้ | +|------|----------------|-----| +| **ผลลัพธ์เป็นค่าว่าง** | การปิดการแก้ไขการเอียงหรือภาพมืดเกินไป | เปิด `AutoCorrectSkew` (เปิดอยู่แล้ว) และเพิ่มความคอนทราสต์ของภาพโดยใช้ `image.AdjustContrast(1.2)`. | +| **อักขระเสีย** | ตั้งค่าภาษาไม่ถูกต้อง | ตั้งค่า `ocrEngine.Settings.Language` ให้ตรงกับภาษาของเอกสาร. | +| **ความล่าช้าประสิทธิภาพกับ PDF ขนาดใหญ่** | เอนจินประมวลผลแต่ละหน้าแบบต่อเนื่อง | ใช้ `Parallel.ForEach` กับ `image.Pages` เพื่อใช้ประโยชน์จาก CPU หลายคอร์. | +| **ข้อยกเว้นไลเซนส์** | ทดลองหมดอายุ | ซื้อไลเซนส์ถาวรหรืออยู่ในขอบเขตการทดลอง (5 หน้าต่อการรัน). | + +## เคล็ดลับมืออาชีพสำหรับ OCR Rotated Document Tutorial ที่แข็งแรง + +* **การประมวลผลเป็นชุด:** ห่อกระบวนการทั้งหมดในเมธอดที่รับพาธโฟลเดอร์, วนลูปทุกภาพ, และเขียนผลลัพธ์แต่ละไฟล์เป็น `.txt`. +* **การเตรียมล่วงหน้า:** บางครั้งสแกนที่มีเสียงรบกวนจะได้ประโยชน์จาก `image.Denoise()` ก่อนการจดจำ. +* **การประมวลผลหลัง:** ใช้ regular expressions เพื่อล้างข้อผิดพลาด OCR ที่พบบ่อย เช่น แทนที่ “0” ด้วย “O” เฉพาะเมื่ออยู่ระหว่างตัวอักษร. +* **การบันทึก:** Aspose OCR มี `ocrEngine.Logger` – เชื่อมต่อกับ logger ไฟล์เพื่อบันทึกคำเตือนเกี่ยวกับคะแนนความเชื่อมั่นต่ำ. + +## โค้ดสมบูรณ์พร้อมรัน + +บันทึกโค้ดต่อไปนี้เป็น `Program.cs` ภายในโปรเจกต์คอนโซลของคุณ มันรวมทุกขั้นตอน, คอมเมนต์, และตัวช่วยเล็ก ๆ สำหรับการประมวลผลเป็นชุด + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +รันมัน: + +```bash +dotnet run +``` + +คุณควรเห็นข้อความที่ทำความสะอาดแล้วพิมพ์ออกที่คอนโซล แสดงให้เห็นว่า **ocr rotated document tutorial** ของเราทำงานจากต้นจนจบ + +--- + +## สรุป + +ตอนนี้คุณมี **ocr rotated document tutorial** ที่สมบูรณ์ซึ่งอัตโนมัติแก้ไขการเอียง, ตรวจจับการหมุน, และสกัดข้อความที่สะอาดโดยใช้ Aspose OCR ใน C#. สิ่งสำคัญคือ? การเปิดใช้งาน `AutoCorrectSkew` **และ** `AutoDetectRotation` ทำให้การสแกนที่เอียงอย่างมากกลายเป็นผลลัพธ์ที่อ่านได้อย่างสมบูรณ์ด้วยเพียงไม่กี่บรรทัดของโค้ด + +จากนี้คุณสามารถขยายเป็นงานแบบ batch, ผสานรวมแพ็คเกจภาษา, หรือส่งผลลัพธ์ไปยัง pipeline การวิเคราะห์ต่อไปได้ อยากสำรวจ **automatic skew correction** เพิ่มเติม? ดู API การเตรียมภาพของ Aspose, หรือทดลองปรับค่า threshold สำหรับสแกนที่มีเสียงรบกวน + +มีคำถามเกี่ยวกับการจัดการ PDF, TIFF หลายหน้า, หรือการผสานกับ Azure Functions? แสดงความคิดเห็นได้เลย, ขอให้สนุกกับการเขียนโค้ด! + +## สิ่งที่คุณควรเรียนต่อ + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดซึ่งต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานครบถ้วนพร้อมคำอธิบายขั้นตอนเพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการนำไปใช้แบบต่าง ๆ ในโครงการของคุณ + +- [โหมดเอกสาร OCR – โหมดตรวจจับพื้นที่ใน OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [สกัดข้อความจากภาพ C# ด้วยการเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – การจดจำอักขระด้วยแสง (Optical Character Recognition)](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/thai/net/text-recognition/_index.md index 7001ea592..7ba43ebbb 100644 --- a/ocr/thai/net/text-recognition/_index.md +++ b/ocr/thai/net/text-recognition/_index.md @@ -53,11 +53,22 @@ url: /th/net/text-recognition/ ปรับปรุงแอปพลิเคชัน .NET ของคุณด้วย Aspose.OCR เพื่อการจดจำข้อความรูปภาพที่มีประสิทธิภาพ สำรวจโหมดตรวจจับพื้นที่ OCR เพื่อผลลัพธ์ที่แม่นยำ ### [รับรู้ PDF ในการรับรู้ภาพ OCR](./recognize-pdf/) ปลดล็อกศักยภาพของ OCR ใน .NET ด้วย Aspose.OCR แยกข้อความจาก PDF ได้อย่างง่ายดาย ดาวน์โหลดทันทีเพื่อประสบการณ์การบูรณาการที่ราบรื่น +### [ทำ OCR บน PDF ด้วย Aspose.OCR – คู่มือ C# ฉบับสมบูรณ์](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +เรียนรู้วิธีทำ OCR บนไฟล์ PDF ด้วย Aspose.OCR ด้วยคำแนะนำขั้นตอนเต็มสำหรับ C# ### [จดจำตารางในการจดจำรูปภาพ OCR](./recognize-table/) ปลดล็อกศักยภาพของ Aspose.OCR สำหรับ .NET ด้วยคำแนะนำที่ครอบคลุมเกี่ยวกับการจดจำตารางในการจดจำรูปภาพ OCR +### [ทำ OCR บนรูปภาพด้วย Aspose OCR – คู่มือภาษา Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +เรียนรู้วิธีทำ OCR บนรูปภาพด้วย Aspose OCR สำหรับภาษา Hindi ด้วยคำแนะนำทีละขั้นตอน +### [วิธีใช้ Aspose: แปลงรูปภาพเป็น HTML ด้วย OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +เรียนรู้วิธีแปลงรูปภาพเป็น HTML ด้วย OCR โดยใช้ Aspose อย่างละเอียดเพื่อเพิ่มความสามารถในการแสดงผลบนเว็บ +### [ทำ OCR บนรูปภาพและตรวจจับคำที่สะกดผิดใน C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +เรียนรู้วิธีทำ OCR บนรูปภาพและตรวจจับคำที่สะกดผิดด้วย C# โดยใช้ Aspose.OCR +### [OCR คำบรรยายวิดีโอใน C# – คู่มือฉบับสมบูรณ์](./video-subtitle-ocr-in-c-complete-guide/) +เรียนรู้วิธีทำ OCR คำบรรยายวิดีโอด้วย C# อย่างละเอียด พร้อมขั้นตอนครบถ้วนเพื่อแปลงคำบรรยายเป็นข้อความ + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/thai/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..f5699b709 --- /dev/null +++ b/ocr/thai/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,275 @@ +--- +category: general +date: 2026-06-03 +description: วิธีใช้ Aspose เพื่อแปลงภาพเป็น HTML และดึงข้อความจากภาพใน C#. เรียนรู้การสร้าง + HTML จากภาพและทำ OCR ภาพเป็น HTML อย่างรวดเร็ว. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: th +og_description: วิธีใช้ Aspose เพื่อแปลงภาพเป็น HTML ดึงข้อความจากภาพ และสร้าง HTML + จากภาพด้วย OCR ใน C# ตามคู่มือฉบับเต็มนี้. +og_title: 'วิธีใช้ Aspose: แปลงภาพเป็น HTML ด้วย OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'วิธีใช้ Aspose: แปลงภาพเป็น HTML ด้วย OCR' +url: /th/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีใช้ Aspose: แปลงรูปภาพเป็น HTML ด้วย OCR + +เคยสงสัย **วิธีใช้ Aspose** เพื่อแปลงรูปสแกนให้เป็น HTML ที่เรียบร้อยหรือไม่? บางทีคุณอาจมีหน้าหนังสือพิมพ์ ใบเสร็จ หรือบันทึกมือและต้องการให้ข้อความและการจัดวางคงไว้สำหรับการเผยแพร่บนเว็บ ข่าวดีคือคุณไม่จำเป็นต้องเขียนพาร์เซอร์เองหรือสู้กับการประมวลผลภาพระดับต่ำ—Aspose.OCR จะทำงานหนักให้คุณ + +ในบทเรียนนี้เราจะเดินผ่าน **ตัวอย่างที่สมบูรณ์และสามารถรันได้** ที่แสดงให้คุณเห็นวิธี **แปลงรูปภาพเป็น HTML**, **ดึงข้อความจากรูปภาพ**, และ **สร้าง HTML จากรูปภาพ** ด้วยไลบรารี Aspose OCR ใน C#. เมื่อจบคุณจะมีแอปคอนโซลขนาดเล็กที่สร้างไฟล์ HTML ที่คงการจัดวางของหน้าเดิมไว้ครบถ้วน พร้อมนำไปใช้ในเว็บไซต์ใดก็ได้ + +## ข้อกำหนดเบื้องต้น + +- **.NET 6.0 SDK** หรือรุ่นใหม่กว่า (โค้ดทำงานได้กับ .NET Core และ .NET Framework ทั้งหมด) +- **Visual Studio 2022** (หรือโปรแกรมแก้ไขใดก็ได้ที่คุณชอบ) +- **Aspose.OCR for .NET** – ติดตั้งผ่าน NuGet: `dotnet add package Aspose.OCR`. +- ไฟล์รูปภาพ (JPEG/PNG) ที่คุณต้องการแปลง เช่น `magazine_page.jpg`. + +ไม่ต้องมีไฟล์กำหนดค่าเพิ่มเติม; ไลบรารีมาพร้อมทุกอย่างที่จำเป็นสำหรับ OCR และการสร้างเลย์เอาต์ HTML + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และเพิ่ม Aspose.OCR + +แรกเริ่มสร้างโปรเจกต์คอนโซลใหม่และดึงแพคเกจ Aspose OCR เข้ามา + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** หากคุณใช้ Visual Studio เพียงคลิกขวาที่โปรเจกต์ → *Manage NuGet Packages* → ค้นหา **Aspose.OCR** แล้วติดตั้ง ขั้นตอนนี้ทำให้คุณสามารถ **ocr image to html** ได้โดยไม่มีการอ้างอิงที่ขาดหาย + +## ขั้นตอนที่ 2: เริ่มต้น OCR Engine + +หัวใจของกระบวนการคือคลาส `OcrEngine` คิดว่าเป็นสมองที่อ่านรูปภาพและตัดสินใจว่าจะส่งออกผลลัพธ์อย่างไร + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +ที่นี่เราสร้างอินสแตนซ์ของ `OcrEngine` คุณไม่จำเป็นต้องส่งข้อมูลรับรองใด ๆ สำหรับเวอร์ชันฟรี; ไลบรารีจะใช้โมเดลการจดจำที่ฝังมาในตัว + +## ขั้นตอนที่ 3: โหลดรูปภาพต้นฉบับ + +ต่อไปให้ชี้เอ็นจิ้นไปยังไฟล์ที่ต้องการประมวลผล Aspose มีเมธอด `OcrImage.FromFile` ที่สะดวกซึ่งรองรับรูปแบบภาพส่วนใหญ่ + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +แทนที่ `YOUR_DIRECTORY` ด้วยพาธแบบเต็มหรือแบบสัมพันธ์ที่ไฟล์รูปภาพของคุณอยู่ หากรูปภาพอยู่ในโฟลเดอร์เดียวกับไฟล์ executable คุณสามารถใช้ `"magazine_page.jpg"` ได้เลย + +## ขั้นตอนที่ 4: จดจำและขอ HTML พร้อมเลย์เอาต์ + +นี่คือหัวใจของบทเรียน โดยการส่ง `OutputFormat.HtmlWithLayout` เราบอก Aspose ให้ **สร้าง HTML จากรูปภาพ** พร้อมคงตำแหน่งเดิมของบล็อกข้อความ, รูปภาพ, และตาราง + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +คุณสมบัติ `recognitionResult.Text` ตอนนี้มีเอกสาร HTML เต็มรูปแบบ หากคุณต้องการเพียงข้อความธรรมดาเท่านั้น คุณสามารถใช้ `OutputFormat.Text` ได้ แต่เรามุ่งเน้นที่ **convert image to html** พร้อมความแม่นยำของเลย์เอาต์ + +## ขั้นตอนที่ 5: บันทึกไฟล์ HTML + +สุดท้ายให้เขียนสตริง HTML ลงดิสก์ จะได้ไฟล์พร้อมใช้ที่คุณสามารถเปิดในเบราว์เซอร์ใดก็ได้ + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +เมื่อรันโปรแกรมจะสร้าง `magazine.html` เปิดไฟล์นี้แล้วคุณจะเห็นข้อความของหน้าต้นฉบับจัดวางตรงตามที่ปรากฏในรูปภาพต้นฉบับ—เหมาะสำหรับการเก็บถาวรหรือการเผยแพร่บนเว็บ + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรม **ครบถ้วนพร้อมคัดลอกและวาง** ไม่ได้ละส่วนใดส่วนหนึ่ง คุณจึงสามารถคอมไพล์และรันได้ทันทีหลังตั้งค่าพาธให้ถูกต้อง + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +เมื่อคุณเปิด `magazine.html` ในเบราว์เซอร์ คุณควรเห็นสิ่งที่คล้ายกับนี้ (ย่อเพื่ออธิบาย): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +แอตทริบิวต์ `style` ที่แน่นอนอาจแตกต่างตามรูปภาพต้นฉบับ แต่โครงสร้างรับประกันว่า **ดึงข้อความจากรูปภาพ** และ **สร้าง html จากรูปภาพ** จะเกิดขึ้นในขั้นตอนเดียวอย่างต่อเนื่อง + +## คำถามทั่วไป & กรณีขอบ + +### ถ้ารูปภาพมีความละเอียดต่ำ? + +Aspose.OCR ทำงานได้ดีที่สุดกับภาพที่มีความละเอียดอย่างน้อย **300 DPI** หากไฟล์ของคุณเบลอ ลองทำการพรีโพรเซสด้วยไลบรารีปรับปรุงภาพ (เช่น ImageSharp) ก่อนส่งให้ OCR คุณภาพต่ำอาจส่งผลต่อความแม่นยำของ **ดึงข้อความจากรูปภาพ** และความแม่นยำของเลย์เอาต์ HTML ที่สร้าง + +### ฉันสามารถควบคุมภาษาของ OCR ได้หรือไม่? + +ได้. ตั้งค่าคุณสมบัติ `Language` ของ `OcrEngine` ก่อนเรียก `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +วิธีนี้ช่วยปรับปรุงการจดจำเมื่อทำงานกับอักขระที่ไม่ใช่ภาษาอังกฤษ + +### จะรับข้อความธรรมดาแทน HTML ได้อย่างไร? + +หากคุณต้องการสตริงดิบเพียงอย่างเดียว ให้แทนที่ `OutputFormat.HtmlWithLayout` ด้วย `OutputFormat.Text` คุณสมบัติ `recognitionResult.Text` จะมีแต่ตัวอักษรที่ดึงออกมาเท่านั้น + +### มีวิธีฝังรูปภาพลงใน HTML ที่สร้างหรือไม่? + +Aspose.OCR สามารถฝังรูปภาพต้นฉบับเป็น data URI แบบ base‑64 เมื่อใช้ `OutputFormat.HtmlWithLayoutAndImages` วิธีนี้สะดวกเมื่อคุณต้องการไฟล์ HTML เดียวโดยไม่มีทรัพยากรภายนอก + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### จะจัดการกับชุดข้อมูลขนาดใหญ่ได้อย่างไร? + +สำหรับการประมวลผลเป็นชุด ให้ห่อโค้ดในลูป `foreach` ที่วนผ่านรายการพาธไฟล์ การใช้อินสแตนซ์ `OcrEngine` เดียวกันหลายครั้งจะลดภาระและเร่งความเร็วของขั้นตอน **convert image to html** + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## เคล็ดลับสำหรับโค้ดพร้อมใช้งานใน Production + +- **Dispose resources**: ทั้ง `OcrEngine` และ `OcrImage` implements `IDisposable`. ใช้ `using` เพื่อปลดปล่อยหน่วยความจำเนทีฟโดยเร็ว +- **Error handling**: ดัก `IOException` สำหรับปัญหาไฟล์และ `OcrException` สำหรับปัญหาการจดจำ +- **Performance**: หากประมวลผลหลายภาพ ให้พิจารณาเปิดใช้งาน **parallelism** (`Parallel.ForEach`) แต่ต้องระวังการใช้ CPU—OCR ใช้ทรัพยากร CPU มาก +- **Logging**: ผสาน logger (เช่น Serilog) เพื่อบันทึกคะแนนความมั่นใจของ OCR (`recognitionResult.Confidence`) สำหรับการตรวจสอบคุณภาพ + +## สรุป + +เราพึ่งอธิบาย **วิธีใช้ Aspose** เพื่อ **แปลงรูปภาพเป็น HTML**, **ดึงข้อความจากรูปภาพ**, และ **สร้าง HTML จากรูปภาพ** ในไม่กี่ขั้นตอนที่ง่าย ตัวอย่างโค้ดเต็มแสดงให้เห็นวิธี **ocr image to html** พร้อมคงเลย์เอาต์ ทำให้เป็นพื้นฐานที่มั่นคงสำหรับโครงการดิจิไทเซชันเอกสารใด ๆ + +จากนี้คุณอาจ: + +- ทดลองใช้ตัวเลือก `OutputFormat` ต่าง ๆ เพื่อให้ตรงกับความต้องการของคุณ +- ผสานผลลัพธ์ HTML กับเฟรมเวิร์ก CSS เพื่อให้รองรับการตอบสนองบนอุปกรณ์ต่าง ๆ +- ส่งข้อความที่ดึงออกไปยังดัชนีการค้นหา หรือไปยัง pipeline machine‑learning + +ลองทำดู ปรับตั้งค่า แล้วคุณจะเห็นว่า Aspose แปลงภาพให้เป็นเนื้อหาเว็บได้อย่างง่ายดาย หากเจออุปสรรคใด ๆ คอมเมนต์ไว้ได้—ขอให้สนุกกับการเขียนโค้ด! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + +## คุณควรเรียนรู้อะไรต่อไป? + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอน‑โดย‑ขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการนำไปใช้แบบต่าง ๆ ในโปรเจกต์ของคุณ + +- [ดึงข้อความจากรูปภาพด้วย C# พร้อมเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [แปลงรูปภาพเป็นข้อความ – ทำ OCR บนรูปจาก URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [จดจำข้อความในรูปด้วย Aspose OCR สำหรับหลายภาษา](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/thai/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..dba81fdac --- /dev/null +++ b/ocr/thai/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-03 +description: ทำการ OCR บนภาพและดึงข้อความจากภาพโดยใช้ Aspose.OCR เรียนรู้วิธีตรวจจับคำที่สะกดผิดและรับคำแนะนำการสะกดในตัวอย่าง + C# เดียว +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: th +og_description: ทำ OCR บนรูปภาพเพื่อดึงข้อความจากรูปภาพ แล้วตรวจหาคำที่สะกดผิดและรับคำแนะนำการสะกดด้วย + Aspose.OCR ใน C# +og_title: ทำ OCR บนภาพและตรวจจับคำที่สะกดผิดใน C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: ทำ OCR บนภาพและตรวจจับคำที่สะกดผิดใน C# +url: /th/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ทำ OCR บนรูปภาพและตรวจหาคำที่สะกดผิดใน C# + +เคยสงสัยไหมว่าจะ **ทำ OCR บนรูปภาพ** อย่างไรโดยไม่ต้องบีบหัว? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะกำลังดิจิไทซ์จดหมายเก่า สแกนใบเสร็จ หรือสร้างเวิร์กโฟลว์เอกสารอัจฉริยะ การสกัดข้อความที่สะอาดจากรูปภาพเป็นอุปสรรคแรก ข่าวดีคือ ด้วย Aspose.OCR คุณสามารถสร้างโซลูชันได้ในไม่กี่นาที และคุณยังสามารถ **ตรวจหาคำที่สะกดผิด** และ **รับข้อเสนอแนะการสะกด** ในการทำงานเดียวกันได้อีกด้วย + +ในบทแนะนำนี้เราจะเดินผ่านแอปคอนโซล C# ที่พร้อม‑รันเต็มรูปแบบซึ่ง **สกัดข้อความจากรูปภาพ**, รันตัวตรวจสอบการสะกดภาษาอังกฤษ, และพิมพ์แต่ละข้อผิดพลาดพร้อมแนวคิดการแก้ไขที่เป็นประโยชน์ เมื่อจบคุณจะรู้ **วิธีสกัดข้อความ**, วิธีเชื่อมต่อกับ API ตรวจสอบการสะกด, และรูปแบบผลลัพธ์คอนโซลที่คาดหวัง + +## สิ่งที่คุณจะสร้าง + +- โหลดบิตแมป (หรือ PNG) ที่มีข้อผิดพลาดการพิมพ์ +- รัน Aspose.OCR เพื่อ **ทำ OCR บนรูปภาพ** และรับข้อมูลสตริงดิบ +- เริ่มต้นตัวตรวจสอบการสะกดภาษาอังกฤษในตัว +- **ตรวจหาคำที่สะกดผิด** และ **รับข้อเสนอแนะการสะกด** สำหรับแต่ละคำ +- พิมพ์รายงานที่เป็นระเบียบลงคอนโซล + +ไม่มีบริการภายนอก ไม่มีการเรียก HTTP ที่ยุ่งยาก—เพียงแพ็กเกจ NuGet เดียวและไม่กี่บรรทัดโค้ด + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 SDK หรือใหม่กว่า (โค้ดนี้ยังทำงานบน .NET Framework 4.7+) +- Visual Studio 2022 (หรือโปรแกรมแก้ไขใด ๆ ที่คุณชอบ) +- แพ็กเกจ NuGet Aspose.OCR for .NET (`Aspose.OCR`) +- ไฟล์รูปภาพ (`letter_with_typos.png`) ที่วางไว้ในตำแหน่งที่คุณสามารถอ้างอิงจากโปรเจกต์ได้ + +หากคุณยังไม่เคยใช้ Aspose มาก่อน ไม่ต้องกังวล—การติดตั้งแพ็กเกจง่ายเหมือนรันคำสั่ง: + +```bash +dotnet add package Aspose.OCR +``` + +ตอนนี้มาดำเนินการลงรายละเอียดการทำงานกัน + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และติดตั้ง Aspose.OCR + +สร้างโปรเจกต์คอนโซลใหม่และดึงไลบรารี OCR เข้ามา: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +หลังจากการกู้คืนเสร็จสิ้น ให้เปิด `Program.cs` เราจะเปลี่ยนเนื้อหาเริ่มต้นเป็นโค้ดตัวอย่างเต็มภายหลัง แต่ก่อนนั้นมาพูดถึงเหตุผลที่แต่ละ namespace มีความสำคัญ + +- `Aspose.OCR` – เอนจิน OCR หลักและการจัดการรูปภาพ +- `Aspose.OCR.SpellCheck` – ยูทิลิตี้ตรวจสอบการสะกดที่มาพร้อมกับไลบรารี +- `System` – คลาสพื้นฐานของ .NET (เช่น `Console`) + +## ขั้นตอนที่ 2: โหลดรูปภาพและทำ OCR บนรูปภาพ + +งานจริงแรกคือการป้อนรูปภาพให้กับเอนจิน OCR Aspose.OCR รองรับหลายรูปแบบ (PNG, JPEG, TIFF) นี่คือส่วนที่ทำงานหนัก: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **ทำไมส่วนนี้สำคัญ:** `OcrImage.FromFile` จัดการรายละเอียดระดับพิกเซลให้คุณ, ส่วน `OcrEngine.Recognize` รันโมเดลประสาทเทียมที่ฝึกแล้วเพื่อแปลง glyph ที่มองเห็นเป็นอักขระ Unicode. คุณสมบัติ `ocrResult.Text` ตอนนี้ถือสตริงดิบ—สิ่งที่คุณต้องการเพื่อ **สกัดข้อความจากรูปภาพ** + +> **เคล็ดลับ:** หากรูปภาพของคุณมีหลายภาษา คุณสามารถตั้งค่า `ocrEngine.Language = OcrLanguage.Multilingual;` ก่อนเรียก `Recognize` + +## ขั้นตอนที่ 3: เริ่มต้นตัวตรวจสอบการสะกดภาษาอังกฤษ + +Aspose.OCR มาพร้อมกับเอนจินตรวจสอบการสะกดในตัวที่เข้าใจภาษาอังกฤษโดยอัตโนมัติ การเริ่มต้นเพียงบรรทัดเดียว: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **ทำไมขั้นตอนนี้สำคัญ:** ผลลัพธ์จาก OCR อาจมีอักขระที่รับรู้ผิด (เช่น “l” กับ “1”) หรือข้อผิดพลาดการพิมพ์จริงจากเอกสารต้นฉบับ ตัวตรวจสอบการสะกดจะสแกนสตริง, ค้นหาโทเคนที่สงสัย, และเสนอทางเลือก + +## ขั้นตอนที่ 4: ตรวจหาคำที่สะกดผิดและรับข้อเสนอแนะการสะกด + +ต่อไปเราจะส่งข้อความ OCR ให้กับตัวตรวจสอบ: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` คือคอลเลกชันที่แต่ละรายการประกอบด้วยคำที่ผิดและอาร์เรย์ของการแก้ไขที่เป็นไปได้ + +## ขั้นตอนที่ 5: แสดงผลลัพธ์ + +สุดท้าย เราจะวนลูปคอลเลกชันและพิมพ์รายงานที่อ่านง่าย: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### ผลลัพธ์คอนโซลที่คาดหวัง + +สมมติว่า `letter_with_typos.png` มีประโยค: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +การรันตัวอย่างจะให้ผลลัพธ์ประมาณนี้: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +สังเกตว่าข้อผิดพลาดแต่ละคำจะจับคู่กับข้อเสนอการแก้ไขหลายรายการ—สิ่งที่คุณต้องการเมื่อสร้าง UI การแก้ไขที่เป็นมิตรกับผู้ใช้ + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นโปรแกรม **พร้อมคัดลอก‑วาง** ทั้งหมด แทนที่ `YOUR_DIRECTORY` ด้วยพาธจริงของไฟล์รูปภาพของคุณ + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **กรณีขอบที่ควรพิจารณา** +> - **รูปภาพว่าง:** หากเอนจิน OCR คืนสตริงว่าง `spellChecker.Check` จะคืนคอลเลกชันว่าง—ไม่มีการขัดข้อง +> - **ข้อความไม่ใช่ภาษาอังกฤษ:** เปลี่ยน `OcrLanguage.English` เป็น `OcrLanguage.French` (หรือภาษาอื่นที่รองรับ) เพื่อ **ตรวจหาคำที่สะกดผิด** ในภาษานั้น ๆ +> - **เอกสารขนาดใหญ่:** สำหรับ PDF หลายหน้า คุณจะต้องวนลูปแต่ละหน้า, ทำ OCR, แล้วรวมผลลัพธ์ก่อนตรวจสอบการสะกด + +## ภาพรวมเชิงภาพ (Alt Text) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*แผนภาพด้านบนแสดงกระบวนการจากต้นจนจบ: รูปภาพ → เอนจิน OCR → ข้อความดิบ → ตัวตรวจสอบการสะกด → ข้อเสนอแนะ* + +## คำถามที่พบบ่อย & เคล็ดลับขั้นสูง + +| Question | Answer | +|----------|--------| +| **Do I need an internet connection?** | No. Aspose.OCR runs entirely locally; perfect for offline or secure environments. | +| **How accurate is the spell‑checker?** | It uses a dictionary of ~150k English words and fuzzy matching, so most common typos are caught. | +| **Can I customize the dictionary?** | Yes. `SpellChecker.AddUserDictionary("custom.txt")` lets you load domain‑specific terms (e.g., product names). | +| **What if the image is skewed?** | The OCR engine auto‑detects orientation, but you can manually call `ocrEngine.ImagePreprocessing.Rotate(angle)` for stubborn cases. | +| **Is there a way to highlight suggestions in UI?** | After you have the `misspellings` collection, you can map each `entry.Word` back to its position in `ocrResult.Text` and underline it in a RichTextBox or web view. | + +## สรุป + +เราได้แสดงให้คุณเห็น **วิธีทำ OCR บนรูปภาพ**, **สกัดข้อความจากรูปภาพ**, แล้ว **ตรวจหาคำที่สะกดผิด** พร้อม **รับข้อเสนอแนะการสะกด** ทั้งหมดด้วยแอปคอนโซล C# สั้น ๆ แนวคิดหลักคือให้ Aspose.OCR จัดการการรับรู้ตัวอักษรหนัก ๆ แล้วให้ตัวตรวจสอบการสะกดในตัวทำความสะอาดผลลัพธ์ จากนี้คุณสามารถขยายตัวอย่างเป็นบริการประมวลผลเอกสารเต็มรูปแบบ, ผสานกับ Web API, หรือเชื่อมต่อกับแอปเดสก์ท็อป + +พร้อมก้าวต่อไปหรือยัง? ลองเปลี่ยนภาษาเป็นสเปน, ป้อน PDF หลายหน้า, หรือสร้าง Front‑end WPF เล็ก ๆ ที่ให้ผู้ใช้คลิกคำเพื่อยอมรับข้อเสนอแนะ. บล็อกพื้นฐานพร้อมใช้งานแล้ว—เพียงทดลองต่อไป + +หากคุณเจออุปสรรคหรือมีไอเดียต่อยอด, ฝากคอมเมนต์ด้านล่างได้เลย. Happy coding! + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจวิธีการทำงานทางเลือกในโปรเจกต์ของคุณ + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/thai/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..bd439278c --- /dev/null +++ b/ocr/thai/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,271 @@ +--- +category: general +date: 2026-06-03 +description: ทำการ OCR บนภาพโดยใช้ Aspose OCR ใน C# เรียนรู้วิธีโหลดภาพสำหรับ OCR + และสกัดข้อความภาษาฮินดีจากภาพแบบออฟไลน์ด้วยโค้ดทีละขั้นตอน. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: th +og_description: ทำการ OCR บนภาพด้วย Aspose OCR ใน C# บทเรียนนี้แสดงวิธีโหลดภาพสำหรับ + OCR และดึงข้อความภาษาฮินดีจากภาพแบบออฟไลน์ พร้อมโค้ดที่สามารถรันได้ +og_title: ทำ OCR บนรูปภาพ – คู่มือ Aspose OCR ภาษา Hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: ทำ OCR บนภาพด้วย Aspose OCR – คู่มือภาษาฮินดี +url: /th/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ทำ OCR บนรูปภาพด้วย Aspose OCR – คู่มือภาษา Hindi + +เคยต้อง **perform OCR on image** ไฟล์ภาพแต่ติดขัดกับการดึงอักขระ Hindi ออกมาหรือไม่? คุณไม่ได้เป็นคนเดียว—นักพัฒนาจำนวนมากเจออุปสรรคนี้เมื่อลองอ่านสคริปต์ที่ไม่ใช่ละตินครั้งแรก ข่าวดีคือ Aspose OCR ทำให้กระบวนการนี้ง่ายมาก และคุณสามารถทำได้แบบออฟไลน์ทั้งหมด + +ในคู่มือนี้เราจะ **load image for OCR**, ชี้เครื่องมือไปที่แพ็คเกจภาษาที่ดาวน์โหลดไว้ล่วงหน้า, และสุดท้าย **extract Hindi text image** โดยไม่ต้องเชื่อมต่ออินเทอร์เน็ต เมื่อเสร็จคุณจะได้แอปคอนโซล C# ที่พร้อมรัน อ่านใบเสร็จภาษา Hindi และพิมพ์ข้อความออกที่คอนโซล + +## สิ่งที่คุณต้องมี + +- **.NET 6.0** หรือใหม่กว่า (โค้ดนี้ยังทำงานบน .NET Framework 4.7+ ด้วย) +- **Aspose.OCR for .NET** NuGet package + `dotnet add package Aspose.OCR` +- โฟลเดอร์ที่มี **offline Hindi language resources** (ดาวน์โหลดจากพอร์ทัลของ Aspose) +- ไฟล์รูปภาพที่มีข้อความ Hindi, เช่น `receipt_hindi.png` + +แค่นี้—ไม่มีบริการภายนอก, ไม่มี API key, เพียงโค้ดตรงไปตรงมา + +## Perform OCR on Image – ขั้นตอนการทำงานแบบละเอียด + +ต่อไปนี้เราจะแบ่งกระบวนการออกเป็นเจ็ดขั้นตอน ชัดเจนแต่ละขั้นตอนจะอธิบาย **ทำไม** ถึงสำคัญ ไม่ใช่แค่ **อะไร** ที่ต้องพิมพ์ + +### ขั้นตอนที่ 1: สร้างอินสแตนซ์ของ OCR Engine + +Engine คือหัวใจของ Aspose OCR การสร้างอินสแตนซ์ทำให้คุณเข้าถึงการตั้งค่าต่าง ๆ ที่จะปรับในขั้นต่อไป + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **ทำไม?** +> หากไม่มี `OcrEngine` คุณก็ไม่มีอ็อบเจ็กต์ที่จะเรียก `Recognize` ได้ คิดว่าเป็น “กล้อง” ที่จะสแกนรูปของคุณในภายหลัง + +### ขั้นตอนที่ 2: ชี้ Engine ไปที่ทรัพยากรออฟไลน์ + +Aspose มีแพ็คเกจภาษาให้ดาวน์โหลดเก็บไว้ในเครื่อง การตั้งค่า `ResourcesFolder` บอก Engine ว่าจะหาไฟล์ที่ไหน + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **เคล็ดลับ:** +> ใช้พาธแบบ absolute ระหว่างพัฒนา แล้วเปลี่ยนเป็นพาธแบบ relative หรือใช้การตั้งค่าใน production + +### ขั้นตอนที่ 3: เปิดโหมดออฟไลน์อย่างเข้มงวด + +คุณอาจสงสัย “จำเป็นต้องปิดการค้นหาออนไลน์จริงหรือ?” +หากทำงานอยู่หลังไฟร์วอลล์หรืออยากได้ผลลัพธ์ที่คาดเดาได้ ให้ตั้งค่า `UseOfflineResources` เป็น `true` + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> ปล่อยให้ค่านี้เป็น `false` จะทำให้ Engine ดาวน์โหลดข้อมูลเพิ่มเติม ซึ่งเพิ่มความหน่วงและอาจละเมิดนโยบายความปลอดภัย + +### ขั้นตอนที่ 4: เลือก Hindi เป็นภาษาการจดจำ + +ที่นี่เราจะ **extract Hindi text image** โดยบอก Engine ให้คาดหวังภาษา Hindi ซึ่งช่วยเพิ่มความแม่นยำอย่างมาก + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **ทำไมจึงช่วย:** +> OCR Engine ใช้โมเดลอักขระเฉพาะภาษา การล็อกเป็น Hindi จะทำให้ Engine ไม่ต้องเดาในหลายสิบสคริปต์ + +### ขั้นตอนที่ 5: โหลดรูปภาพสำหรับ OCR + +ตอนนี้เราจะ **load image for OCR** จริง ๆ วิธี `OcrImage.FromFile` จะอ่านบิตแมพและแปลงเป็นรูปแบบที่ Engine เข้าใจ + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **ข้อผิดพลาดทั่วไป:** +> การใช้พาธที่มีสแลชหน้า (`/`) บน Windows ทำงานได้, แต่การใช้ `Path.Combine` จะทำให้โค้ดของคุณเป็นแพลตฟอร์ม‑agnostic มากขึ้น + +### ขั้นตอนที่ 6: รันการจดจำ + +เมื่อทุกอย่างพร้อม เราจะ **perform OCR on image** โดยเรียก `Recognize` + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **กำลังเกิดอะไรขึ้น?** +> Engine สแกนแต่ละพิกเซล, แมตช์แพทเทิร์นกับฐานข้อมูล glyph ของ Hindi, แล้วสร้างสตริง Unicode + +### ขั้นตอนที่ 7: แสดงผลข้อความที่จดจำได้ + +อ็อบเจ็กต์ผลลัพธ์มี property `Text` ที่เก็บสตริงที่สกัดออกมา เราแค่เขียนออกไปที่คอนโซล + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **ผลลัพธ์ที่คาดหวัง:** +> หาก `receipt_hindi.png` มีข้อความ “भुगतान सफल”, คอนโซลจะพิมพ์บรรทัดนั้นโดยคงรักษา diacritics ไว้ + +## Load Image for OCR – การเตรียมทรัพยากร + +หากคุณสงสัยว่าจะส่งสตรีมให้ Engine แทนไฟล์ได้หรือไม่ คำตอบคือได้ แทนที่ `OcrImage.FromFile` ด้วย: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **ทำไมต้องใช้สตรีม?** +> สตรีมทำให้คุณจัดการกับภาพที่เก็บในฐานข้อมูล, cloud blobs หรือ embedded resources—เหมาะกับบริการที่ต้องขยายขนาด + +## Extract Hindi Text Image – การจัดการกรณีขอบ + +1. **Missing language pack** – หากไม่พบแพ็ค Hindi, `Recognize` จะโยน exception. ให้ห่อหุ้มการเรียกใน try/catch แล้วบันทึกข้อความที่เป็นมิตร +2. **Low‑resolution images** – ความแม่นยำของ OCR ลดลงเมื่อความละเอียดต่ำกว่า 300 dpi. ควรทำการพรี‑โปรเซสภาพ (resize, sharpen) ก่อนโหลด +3. **Mixed‑language documents** – สามารถเปิดหลายภาษาได้: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +การปรับแต่งเหล่านี้ทำให้ routine **perform OCR on image** ของคุณคงความเสถียรในสภาพ production + +## รันตัวอย่างเต็มรูปแบบ + +บันทึกไฟล์ต่อไปนี้เป็น `Program.cs`, แก้ไขพาธตามที่ต้องการ, แล้วรัน: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +เมื่อคุณสั่ง `dotnet run` ควรเห็นผลลัพธ์ประมาณนี้: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +หากได้สตริงว่าง ตรวจสอบว่า **ResourcesFolder** ชี้ไปยังโฟลเดอร์ที่มี `Hindi.traineddata` และภาพมีความชัดเจนพอ + +## สรุป + +เราได้อธิบายวิธี **perform OCR on image** ด้วย Aspose OCR ตั้งแต่ **load image for OCR** จนถึง **extract Hindi text image** ในสภาพแวดล้อมออฟไลน์ทั้งหมด โค้ดที่ทำงานได้เต็มรูปแบบด้านบนให้พื้นฐานที่มั่นคง, พร้อมเคล็ดลับการใช้สตรีม, การจัดการข้อผิดพลาด, และการสนับสนุนหลายภาษา เพื่อให้คุณปรับใช้ในโปรเจกต์จริงได้ง่าย + +พร้อมก้าวต่อไปหรือยัง? ลองเปลี่ยนภาษาเป็น **OcrLanguage.Tamil** หรือดึงภาพจาก Azure Blob storage. คุณยังสามารถทดลองปรับ `ImagePreprocessing` เพื่อเพิ่มความแม่นยำบนใบเสร็จที่มีเสียงรบกวน + +มีคำถามหรือเจออุปสรรค? แสดงความคิดเห็นได้เลย—ขอให้สนุกกับการเขียนโค้ด! + +![Perform OCR on image example + + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้ แต่ละแหล่งรวมโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยให้คุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณ + +- [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/) +- [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/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/thai/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..82d3abbad --- /dev/null +++ b/ocr/thai/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-06-03 +description: ทำการ OCR บนไฟล์ PDF และแปลง PDF ที่สแกนเป็น PDF ที่สามารถค้นหาได้โดยใช้ + Aspose.OCR เรียนรู้วิธีจดจำข้อความจาก PDF และสร้าง PDF ที่สามารถค้นหาได้ในไม่กี่นาที +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: th +og_description: ทำการ OCR บน PDF และสร้าง PDF ที่สามารถค้นหาได้ทันที บทเรียนนี้แสดงขั้นตอนโดยละเอียดว่าจะแปลงข้อความจาก + PDF ด้วย Aspose.OCR อย่างไร +og_title: ทำ OCR บน PDF – คู่มือ C# ฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: ทำ OCR บน PDF ด้วย Aspose.OCR – คู่มือ C# ฉบับสมบูรณ์ +url: /th/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ทำ OCR บน PDF ด้วย Aspose.OCR – คู่มือ C# ฉบับสมบูรณ์ + +เคยสงสัย **วิธีทำ OCR บน PDF** ไฟล์โดยไม่ต้องต่อสู้กับเครื่องมือบรรทัดคำสั่งหลายสิบตัวหรือไม่? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะกำลังดิจิไทซ์ใบแจ้งหนี้, เก็บถาวรรายงานเก่า, หรือแค่ต้องการเวอร์ชันที่สามารถค้นหาได้ของสัญญาที่สแกนไว้ การเปลี่ยน PDF ที่คงที่ให้เป็นสิ่งที่คุณสามารถค้นหาได้จริงเป็นการเปลี่ยนเกมอย่างมาก + +ในคู่มือนี้เราจะพาคุณผ่าน **วิธีสร้าง PDF ที่ค้นหาได้** จาก PDF ที่สแกน (และแม้แต่ภาพธรรมดา) ด้วย Aspose.OCR สำหรับ .NET. เมื่อเสร็จคุณจะสามารถ **จดจำข้อความจาก PDF** ด้วยเพียงไม่กี่บรรทัดของโค้ด C# และคุณจะเข้าใจเหตุผลของแต่ละขั้นตอนเพื่อให้คุณปรับใช้โซลูชันกับโปรเจกต์ของคุณเองได้ + +> **สรุปสั้น:** กระบวนการทั้งหมดสรุปได้เป็นสามสิ่ง—การเริ่มต้นเครื่องมือ OCR, การป้อนแหล่งข้อมูล (PDF หรือภาพ), และการบันทึกผลลัพธ์ PDF ที่ค้นหาได้ มาเริ่มกันเลย + +--- + +## สิ่งที่คุณต้องมี + +ก่อนที่เราจะเริ่ม, ตรวจสอบให้แน่ใจว่าคุณมี: + +| ข้อกำหนด | เหตุผลที่สำคัญ | +|--------------|----------------| +| **.NET 6.0+** (หรือ .NET Framework 4.6+) | Aspose.OCR รองรับรันไทม์สมัยใหม่; เวอร์ชันเก่าอาจพลาดการอัปเดต API | +| **Aspose.OCR for .NET** NuGet package | ให้คลาส `OcrEngine` และยูทิลิตี้การจัดการ PDF | +| **ใบอนุญาต Aspose ที่ถูกต้อง** (หรือใช้รุ่นประเมินฟรี) | หากไม่มีใบอนุญาตคุณจะเจอขีดจำกัดการประเมิน 30 วันและลายน้ำ | +| **PDF ที่สแกน** (หรือไฟล์ภาพ) ที่คุณต้องการทำให้ค้นหาได้ | นี้คือเอกสารต้นทางสำหรับ OCR | +| **Visual Studio 2022** (หรือเครื่องมือแก้ไข C# ใดก็ได้) | ทำให้การดีบักง่ายขึ้น, แต่ IDE ใดก็ใช้ได้ | + +คุณสามารถติดตั้งไลบรารีด้วยคำสั่ง NuGet ต่อไปนี้: + +```bash +dotnet add package Aspose.OCR +``` + +> **เคล็ดลับมืออาชีพ:** หากคุณทำงานบน pipeline CI, ให้เพิ่มไฟล์ใบอนุญาตไปยัง artefacts ของการสร้างและโหลดมันใน runtime เพื่อหลีกเลี่ยงการกำหนดเส้นทางแบบ hard‑coding + +--- + +## ทำ OCR บน PDF – ตั้งค่า Aspose.OCR + +สิ่งแรกที่เราต้องการคืออินสแตนซ์ `OcrEngine` ใหม่. คิดว่าเป็นสมองที่จะอ่านเอกสารของคุณ + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +ทำไมต้องสร้างอินสแตนซ์ใหม่ทุกครั้ง? เครื่องมือเก็บการตั้งค่า (เช่น การตั้งค่าภาษา) ที่อาจแตกต่างกันตามเอกสาร การสร้างใหม่ในแต่ละครั้งรับประกันว่ามีสภาพเริ่มต้นที่สะอาดและหลีกเลี่ยงการสื่อสารข้ามงาน + +--- + +## วิธีสร้าง PDF ที่ค้นหาได้ – การตั้งค่ารหัสผ่าน (ไม่บังคับ) + +หาก PDF ของคุณถูกป้องกัน, คุณต้องบอกเครื่องมือรหัสผ่านก่อนที่มันจะอ่านหน้าได้: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +การข้ามขั้นตอนนี้ในไฟล์ที่มีการป้องกันจะทำให้เกิด `PdfPasswordException`. ควรห่อไว้ใน try‑catch หากคุณไม่แน่ใจสถานะการป้องกัน + +--- + +## แปลง PDF ที่สแกนเป็น PDF ที่ค้นหาได้ – โหลดแหล่งข้อมูล + +Aspose.OCR ทำงานกับการแอบสแตรก `OcrImage`, ซึ่งสามารถห่อ PDF, TIFF, JPEG ฯลฯ นี่คือวิธีดึง PDF ที่สแกนเข้าสู่หน่วยความจำ: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +เบื้องหลัง, `FromFile` จะวิเคราะห์แต่ละหน้าเป็นภาพแรสเตอร์ที่เครื่องมือ OCR สามารถประมวลผลได้ หากคุณมี PDF หลายหน้า, เครื่องมือจะวนลูปอัตโนมัติผ่านทุกหน้า + +--- + +## จดจำข้อความจาก PDF – ทำ OCR + +ตอนนี้เป็นแกนหลักของบทเรียน: ให้เครื่องมือจดจำข้อความและส่งออก PDF ที่ค้นหาได้ + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` บอกเครื่องมือให้ฝังชั้นข้อความที่มองไม่เห็นเหนือภาพสแกนเดิม PDF ที่ได้จะคงความคมชัดของสแกนไว้ในขณะที่กลายเป็นไฟล์ที่ค้นหาได้เต็มที่—สิ่งที่คุณต้องการสำหรับการตรวจสอบความสอดคล้อง + +--- + +## แปลงภาพเป็น PDF ที่ค้นหาได้ – บันทึกผลลัพธ์ + +สุดท้าย, เขียนข้อมูลไบนารีลงดิสก์: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +คุณสมบัติ `Binary` เก็บไบต์ PDF ดิบ คุณยังสามารถสตรีมโดยตรงไปยังการตอบสนองเว็บได้หากคุณกำลังสร้าง API + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") + +*ข้อความแทนภาพ: แผนภาพแสดงกระบวนการแปลง OCR เพื่อสร้าง PDF ที่ค้นหาได้* + +--- + +## กรณีขอบและเคล็ดลับปฏิบัติ + +### 1. ไฟล์ขนาดใหญ่ & การจัดการหน่วยความจำ +หากคุณประมวลผล PDF ที่ใหญ่กว่า 100 MB, พิจารณาใช้ `OcrEngineSettings.MemoryLimit` เพื่อลิมิตการใช้หน่วยความจำ นอกจากนี้ให้ประมวลผลหน้าเป็นชุดเพื่อหลีกเลี่ยง `OutOfMemoryException` + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. การสนับสนุนภาษา +โดยค่าเริ่มต้น Aspose.OCR จะสมมติเป็นภาษาอังกฤษ เพื่อจดจำภาษาอื่น, ตั้งค่าคุณสมบัติ `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. สถานการณ์หลายเธรด +`OcrEngine` **ไม่** ปลอดภัยต่อเธรด หากต้องการประมวลผลแบบขนาน, สร้างเครื่องมือแยกต่างหากต่อเธรด + +### 4. การดีบักความแม่นยำของ OCR +คุณสามารถดึงข้อความธรรมดาจาก `ocrResult` เพื่อดีบัก: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +หากผลลัพธ์ดูเป็นอักขระผสม, ทดลองปรับ `PreprocessSettings` (เช่น deskew, despeckle) เพื่อปรับคุณภาพ + +### 5. ปัญหาเรื่องใบอนุญาต +เมื่อคุณรันเวอร์ชันประเมิน, Aspose จะเพิ่มลายน้ำลงใน PDF ผลลัพธ์ ลงทะเบียนใบอนุญาตของคุณตั้งแต่ต้นในแอปพลิเคชัน: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ – ตั้งแต่ต้นจนจบ + +ด้านล่างเป็นโปรแกรมที่พร้อมรันครบถ้วนซึ่งรวมเคล็ดลับทั้งหมดข้างต้น คุณสามารถคัดลอกและวางลงในโปรเจกต์คอนโซลใหม่ได้เลย + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง:** หลังจากรัน, คุณจะเห็นบรรทัดคอนโซลยืนยันตำแหน่งไฟล์ เปิด `output.pdf` ในโปรแกรมดู PDF ใดก็ได้; พยายามพิมพ์คำที่คุณรู้ว่ามีในสแกนต้นฉบับ หากข้อความถูกไฮไลต์, คุณได้ **ทำ OCR บน PDF** สำเร็จและสร้างเอกสารที่ค้นหาได้แล้ว + +--- + +## คำถามที่พบบ่อย + +**Q: ฉันสามารถใช้วิธีนี้แปลงภาพเดียว (PNG/JPEG) เป็น PDF ที่ค้นหาได้หรือไม่?** +A: แน่นอน. แทนที่ `OcrImage.FromFile("input.pdf")` ด้วยเส้นทางไปยังไฟล์ภาพของคุณ เครื่องมือจะเรสเตอร์ไอเมจและฝังชั้น OCR เหมือนเดิม + +**Q: ถ้า PDF ของฉันมีทั้งหน้าที่สแกนและข้อความดั้งเดิมจะเป็นอย่างไร?** +A: เครื่องมือจะวางข้อความ OCR บนเนื้อหาที่มีอยู่แล้ว, ดังนั้นข้อความดั้งเดิมจะยังเลือกได้ในขณะที่หน้าที่สแกนจะกลายเป็นที่ค้นหาได้ + +**Q: OCR มีความแม่นยำแค่ไหน?** +A: ความแม่นยำขึ้นอยู่กับคุณภาพของแหล่งข้อมูล การสแกนที่สะอาดและความละเอียดสูง (>300 dpi) ให้ความแม่นยำ >95 % สำหรับเอกสารที่มีสัญญาณรบกวน, เปิดใช้งาน `PreprocessSettings` (deskew, despeckle) ก่อนเรียก `Recognize` + +--- + +## ขั้นตอนต่อไป – ขยายชุดเครื่องมือ OCR ของคุณ + +ตอนนี้คุณสามารถ **จดจำข้อความจาก PDF** และ **แปลง PDF ที่สแกนเป็น PDF ที่ค้นหาได้**, พิจารณาหัวข้อต่อไปนี้: + +- **การประมวลผลแบบแบตช์**: วนลูปผ่านโฟลเดอร์ของ PDF และสร้างเวอร์ชันที่ค้นหาได้โดยอัตโนมัติ +- **การสกัดข้อความ**: ใช้ `ocrResult.Text` เพื่อป้อนดัชนีการค้นหา (เช่น Elasticsearch) +- **แพ็คภาษาแบบกำหนดเอง**: ดาวน์โหลดข้อมูลภาษาที่เพิ่มจาก Aspose เพื่อสนับสนุนสคริปต์เอเชีย +- **การปฏิบัติตาม PDF/A**: ผสาน Aspose.PDF กับผลลัพธ์ OCR เพื่อสร้าง PDF ที่พร้อมเก็บถาวร + +แต่ละหัวข้อนี้ต่อยอดจากขั้นตอนหลักที่เราได้ครอบคลุมไว้, ทำให้คุณพร้อมขยายโซลูชันของคุณต่อไป + +--- + +## สรุป + +เราได้แสดงให้คุณ **วิธีทำ OCR บน PDF** ด้วย Aspose.OCR, แปลง PDF ที่สแกนให้เป็น PDF ที่ค้นหาได้เต็มรูปแบบ, และแม้กระทั่งอธิบายการแปลงภาพธรรมดาเป็น PDF ที่ค้นหาได้. โค้ด + +## คุณควรเรียนรู้อะไรต่อไป? + +บทแนะนำต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แต่ละแหล่งข้อมูลมีตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายขั้นตอนเพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานแบบอื่นในโปรเจกต์ของคุณเอง. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/thai/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..1e015168a --- /dev/null +++ b/ocr/thai/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: บทเรียน OCR คำบรรยายวิดีโอที่แสดงวิธีการดึงเฟรมจากวิดีโอและอ่านข้อความจากไฟล์วิดีโอเช่น + MP4 ด้วย Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: th +og_description: เรียนรู้การทำ OCR คำบรรยายวิดีโอด้วย Aspose.OCR ดึงเฟรมจากวิดีโอ อ่านข้อความจากวิดีโอ + และดึงข้อความจากไฟล์ MP4 ภายในไม่กี่นาที. +og_title: OCR คำบรรยายวิดีโอใน C# – คู่มือแบบทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: การทำ OCR คำบรรยายวิดีโอใน C# – คู่มือฉบับสมบูรณ์ +url: /th/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR คำบรรยายวิดีโอใน C# – คู่มือฉบับสมบูรณ์ + +เคยต้องการ **video subtitle ocr** แต่ไม่แน่ใจว่าจะเริ่มต้นอย่างไรหรือไม่? คุณไม่ได้อยู่คนเดียว ไม่ว่าคุณจะกำลังแปลงบันทึกการบรรยายเป็นดิจิทัล, ดึงคำบรรยายจากวิดีโอการฝึกอบรม, หรือแค่สนใจการอ่านข้อความจากวิดีโอ, บทเรียนนี้จะแสดงให้คุณเห็นขั้นตอนการทำด้วย C# และ Aspose.OCR อย่างชัดเจน + +ในไม่กี่นาทีต่อไปเราจะดึงเฟรมจากวิดีโอ, รัน OCR บนเฟรมนั้น, และสุดท้ายแสดงข้อความคำบรรยายเฟรมต่อเฟรม. เมื่อจบคุณจะสามารถ **read text from video** ไฟล์—including MP4—โดยไม่ต้องค้นหาเครื่องมือของบุคคลที่สาม. + +## สิ่งที่คุณจะสร้าง + +เราจะสร้างแอปคอนโซลเล็ก ๆ ที่: + +1. ถอดรหัส MP4 (หรือฟอร์แมตที่รองรับอื่น) เป็นเฟรม `Bitmap` แยกแต่ละอัน. +2. จำกัดพื้นที่ OCR ไว้ที่แถบคำบรรยายเพื่อไม่ให้เอนจินเสียสมาธิจากภาพทั้งหมด. +3. ประมวลผลแต่ละเฟรมด้วย `VideoOcrProcessor` ของ Aspose. +4. พิมพ์ข้อความคำบรรยายที่ได้รับการจดจำลงคอนโซล. + +ไม่มีส่วนเกิน, เพียงตัวอย่างทำงานจากต้นจนจบที่คุณสามารถนำไปใช้ในโปรเจกต์จริงได้. + +## ข้อกำหนดเบื้องต้น + +- **.NET 6.0** หรือใหม่กว่า (โค้ดนี้ยังทำงานบน .NET Framework 4.7+). +- **Aspose.OCR for .NET** – ติดตั้งผ่าน NuGet: `Install-Package Aspose.OCR`. +- ไฟล์วิดีโอ (MP4 ทำงานได้ดี). +- วิธีถอดรหัสเฟรมวิดีโอ – ตัวอย่างใช้เมธอด placeholder, แต่คุณสามารถต่อเข้ากับ FFmpeg, OpenCV, หรือไลบรารีใดก็ได้ที่คืนค่าเป็นอ็อบเจกต์ `Bitmap`. + +> Pro tip: หากคุณใช้ Windows, แพ็กเกจ `System.Drawing.Common` ทำงานได้ดีสำหรับ `Bitmap`. บน Linux/macOS คุณจะต้องติดตั้ง dependency `libgdiplus` ที่เป็น native. + +## ขั้นตอนที่ 1 – ดึงเฟรมจากวิดีโอ + +อุปสรรคแรกคือการแปลงภาพเคลื่อนไหวให้เป็นภาพนิ่ง. เมธอด `GetVideoFrames` ด้านล่างถูกเว้นไว้ให้คุณเติมด้วยตัวถอดรหัสที่ชื่นชอบ. ตัวอย่างสเก็ตช์สั้น ๆ ด้วย FFmpeg‑Core (เพื่อแสดงโครงสร้างข้อมูล): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **ทำไมเรื่องนี้ถึงสำคัญ:** การดึงเฟรมทำให้ OCR engine มีภาพคงที่ทำงานด้วย, ซึ่งช่วยเพิ่มความแม่นยำอย่างมากเมื่อเทียบกับการพยายามอ่านโดยตรงจากสตรีมวิดีโอ. + +## ขั้นตอนที่ 2 – ตั้งค่า VideoOcrProcessor + +เมื่อเรามีลำดับของอ็อบเจกต์ `Bitmap` แล้ว เราสามารถส่งให้ Aspose.OCR ได้. `VideoOcrProcessor` ให้เรากำหนด **Region of Interest (ROI)** – เหมาะสำหรับคำบรรยายที่มักอยู่ด้านบนหรือด้านล่างของเฟรม. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **ทำไมต้องจำกัด ROI?** การละเลยส่วนที่เหลือของภาพช่วยลดสัญญาณรบกวน, ลดเวลาประมวลผล, และหลีกเลี่ยงผลบวกเท็จจากกราฟิกพื้นหลัง. + +## ขั้นตอนที่ 3 – รัน OCR บนลำดับเฟรม + +เมื่อโปรเซสเซอร์พร้อม, การป้อนเฟรมทำได้ด้วยบรรทัดเดียว. เมธอด `Process` จะคืนค่า enumerable ของอ็อบเจกต์ `OcrResult`, แต่ละอันมีข้อความที่จดจำได้สำหรับเฟรมนั้น. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **เกิดอะไรขึ้นเบื้องหลัง?** Aspose.OCR จะทำการ normalize แต่ละ bitmap, รัน recognizer ที่ใช้ neural‑network, แล้วทำ post‑process ผลลัพธ์เพื่อปรับปรุงเครื่องหมายวรรคตอนและการแบ่งบรรทัด. + +## ขั้นตอนที่ 4 – แสดงข้อความที่สกัดออกมา + +สุดท้าย เราจะวนลูปผลลัพธ์และพิมพ์แต่ละบรรทัดคำบรรยาย. คุณอาจบันทึกเป็นไฟล์ SRT, ฐานข้อมูล, หรือส่งต่อให้บริการแปลภาษาได้เช่นกัน. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### ตัวอย่างทำงานเต็มรูปแบบ + +นำทุกส่วนมารวมกันจะได้โปรแกรมคอนโซลที่ทำงานได้อย่างอิสระ: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**ผลลัพธ์ที่คาดหวัง (ตัวอย่าง)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +หาก OCR มีปัญหากับเฟรมใดเฟรมหนึ่ง คุณจะเห็นสตริงว่าง – นั่นเป็นสัญญาณให้คุณปรับ ROI หรือเพิ่มอัตราการดึงเฟรม. + +## ปัญหาที่พบบ่อย & วิธีแก้ + +| ปัญหา | ทำไมจึงเกิด | วิธีแก้ | +|-------|-------------|--------| +| **อักขระแปลก** | เฟรมความละเอียดต่ำหรือบีบอัดหนัก | ดึงเฟรมที่บิตเรตสูงขึ้น, หรือ upscale bitmap ก่อน OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **ไม่มีข้อความคืนค่า** | ROI ไม่ครอบแถบคำบรรยายจริง | ตรวจสอบพิกัดสี่เหลี่ยม (ใช้เครื่องมือ screenshot วัด). | +| **คอขวดประสิทธิภาพ** | ประมวลผลทุกเฟรมที่ 30 fps มากเกินไป | ลดอัตราเป็น 1‑2 fps สำหรับส่วนใหญ่ของสตรีมคำบรรยาย; ยังคงจับการเปลี่ยนแปลงคำบรรยายได้. | +| **ไม่พบ FFmpeg** | `ffmpeg.exe` ไม่อยู่ใน `PATH` | ระบุพาธเต็มใน `ProcessStartInfo.FileName` หรือทำการติดตั้ง FFmpeg อย่างทั่วโลก. | + +## การขยายโซลูชัน + +- **ส่งออกเป็น SRT** – รวม timestamps กับข้อความ OCR แล้วเขียนไฟล์ SubRip. +- **รองรับหลายภาษา** – ตั้งค่า `ocrProcessor.Language = OcrLanguage.Spanish` (หรือภาษาอื่นที่รองรับ). +- **ประมวลผลแบบเรียลไทม์** – ส่งเฟรมโดยตรงจากสตรีมสดแทนการอ่านจากดิสก์. + +ทั้งหมดนี้ยังคงอิงกับแนวคิดหลักของ **extract frames from video**, **read text from video**, และ **extract text from mp4**. + +## สรุป + +เราได้เดินผ่านเวิร์กโฟลว์ **video subtitle ocr** อย่างครบถ้วนใน C#. ด้วยการดึงเฟรมจากวิดีโอ, โฟกัส OCR ไปที่แถบคำบรรยาย, และวนลูปผลลัพธ์, คุณสามารถ **read text from video** ไฟล์เช่น MP4 ได้อย่างเชื่อถือได้. โค้ดพร้อมคัดลอก‑วาง, และการออกแบบแบบโมดูลาร์ทำให้คุณเปลี่ยนตัวถอดรหัสเฟรมตามที่ต้องการได้ง่าย. + +ขั้นตอนต่อไป? ลองส่งออกผลลัพธ์เป็นไฟล์ SRT, ทดลองขนาด ROI ต่าง ๆ, หรือส่งคำบรรยายไปยัง API แปลภาษาเพื่อสร้างคำบรรยายหลายภาษา. ความเป็นไปได้ไม่มีที่สิ้นสุดเมื่อคุณครอบคลุมพื้นฐานการสกัดข้อความจากวิดีโอแล้ว. + +ขอให้สนุกกับการเขียนโค้ด, และขอให้คำบรรยายของคุณชัดเจนเสมอ! + +## สิ่งที่คุณควรเรียนต่อไป + +บทเรียนต่อไปนี้ครอบคลุมหัวข้อที่เกี่ยวข้องอย่างใกล้ชิดและต่อยอดจากเทคนิคที่แสดงในคู่มือนี้. แต่ละแหล่งรวมตัวอย่างโค้ดทำงานเต็มรูปแบบพร้อมคำอธิบายทีละขั้นตอน เพื่อช่วยคุณเชี่ยวชาญฟีเจอร์ API เพิ่มเติมและสำรวจแนวทางการทำงานอื่น ๆ ในโปรเจกต์ของคุณเอง. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/ocr-configuration/_index.md b/ocr/turkish/net/ocr-configuration/_index.md index 876063bfd..0116f938f 100644 --- a/ocr/turkish/net/ocr-configuration/_index.md +++ b/ocr/turkish/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Aspose.OCR ile .NET’te OCR görüntü tanıma gücünü keşfedin. Görüntül Aspose.OCR for .NET ile güçlü OCR yeteneklerini açığa çıkarın. Görüntülerden sorunsuz bir şekilde metin çıkarın. ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) Aspose.OCR for .NET’in potansiyelini ortaya çıkarın. Listelerle OCR görüntü tanımını zahmetsizce gerçekleştirin. Uygulamalarınızda üretkenliği ve veri çıkarımını artırın. +### [C#'ta Aspose OCR Sürümünü Alın – Tam Kılavuz](./get-aspose-ocr-version-in-c-complete-guide/) +Aspose OCR kütüphanesinin sürüm bilgisini C# kodu ile nasıl alacağınızı adım adım gösterir. ### Yaygın Kullanım Senaryoları - **Taralı faturalardan metin çıkarma** ile otomatik muhasebe. @@ -100,4 +102,4 @@ C: Evet, `OcrResult` nesnesi programatik olarak inceleyebileceğiniz güven değ {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/turkish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..3d16c1fbf --- /dev/null +++ b/ocr/turkish/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-06-03 +description: Basit bir kod parçacığıyla C#'ta Aspose OCR sürümünü alın. OcrEngine + GetVersion kullanarak Aspose OCR kütüphanesi sürümünü nasıl alacağınızı öğrenin. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: tr +og_description: Aspose OCR sürümünü C#'ta hızlıca alın. Bu öğreticide, OcrEngine GetVersion + kullanarak Aspose OCR kütüphanesi sürümünü nasıl alacağınız tam olarak gösterilmektedir. +og_title: C#'ta Aspose OCR Sürümünü Alın – Tam Kılavuz +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: C#'ta Aspose OCR Sürümünü Edinin – Tam Rehber +url: /tr/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR Sürümünü C#'ta Alın – Tam Kılavuz + +Hiç .NET projeniz içinde **Aspose OCR sürümünü** nasıl alacağınızı merak ettiniz mi? Belki bir uyumsuzluğu gideriyorsunuzdur ya da üretimde çalışan kütüphanenin tam sürümünü kaydetmek istiyorsunuzdur. Nedeni ne olursa olsun, doğru yere geldiniz. + +Bu öğreticide, `OcrEngine.GetVersion()` metodunu çağıran ve sonucu ekrana yazdıran küçük, bağımsız bir C# programı üzerinden ilerleyeceğiz. Sonunda sadece *sürümü nasıl alacağınızı* değil, aynı zamanda **Aspose OCR kütüphanesini** yükseltirken sürüm kontrolünün neden baş ağrılarından sizi kurtarabileceğini de öğreneceksiniz. + +## Öğrenecekleriniz + +- Bir C# projesine Aspose.OCR NuGet paketini ekleyin +- `OcrEngine.GetVersion()` metodunu ( **ocrengine getversion** giriş noktası) kullanın +- Olası istisnaları yakalayın ve çıktıyı doğrulayın +- Kesiti gerçek dünya senaryoları için, örneğin günlük kaydı veya koşullu özellik geçişleri gibi, genişletin + +OCR konusunda önceden deneyim gerekmez—sadece temel C# ve Visual Studio (veya favori IDE’niz) bilgisi yeterlidir. Hadi başlayalım. + +--- + +## 1. Adım: Projeyi Kurun ve Aspose OCR Kütüphanesini Çekin + +Herhangi bir OCR‑ile‑ilgili API’yi çağırmadan önce, projenizde **Aspose OCR kütüphanesinin** referans olarak ekli olması gerekir. + +1. Visual Studio’da bir terminal ya da Package Manager Console açın. +2. Aşağıdaki komutu çalıştırarak en son kararlı sürümü yükleyin: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro ipucu:** .NET Core yerine .NET Framework hedefliyorsanız, NuGet Package Manager UI’yı kullanın ve çalışma zamanınıza uygun sürümü seçin. Paket, daha sonra kullanacağımız `OcrEngine` sınıfını içerir. + +### Neden Önemli + +Paketi kurduğunuzda, diskteki derleme (assembly) sürümü, çalışma zamanında kütüphanenin bildirdiği sürümden farklı olabilir. Sürümü kod aracılığıyla sorgulamak, CLR’nin yüklediği tam derlemeyi okuduğunuzdan emin olmanızı sağlar; bu, hata ayıklama ve uyumluluk denetimleri için kritik öneme sahiptir. + +--- + +## 2. Adım: **Aspose OCR Sürümünü** Almak İçin Minimum Kodu Yazın + +Yeni bir konsol uygulaması oluşturun (`dotnet new console -n OcrVersionDemo`) ve varsayılan `Program.cs` dosyasını aşağıdaki kodla değiştirin: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Her bölümün açıklaması** + +- `using Aspose.OCR;` OCR ad alanını kapsam içine alır, böylece `OcrEngine`’i çağırabiliriz. +- `OcrEngine.GetVersion()` **ocrengine getversion** adlı statik metottur ve `"24.5.7"` gibi bir dize döndürür. +- Çağrıyı bir `try/catch` bloğuna sarmak, çalışma zamanı sürprizlerinden korunmanızı sağlar—örneğin yerel ikili dosyalar hedef makinede bulunmayabilir. +- `$"Aspose OCR version: {version}"` biçimindeki interpolasyonlu dize, net ve insan‑okunur bir satır yazdırır. + +### Beklenen çıktı + +Proje klasöründe `dotnet run` komutunu çalıştırdığınızda aşağıdakine benzer bir şey görmelisiniz: + +``` +Aspose OCR version: 24.5.7 +``` + +Kütüphane yüklenemezse, hata dalı kısa bir mesaj verir ve sorunu hızlıca tespit etmenize yardımcı olur. + +--- + +## 3. Adım: Sürümün NuGet Paketiyle Eşleştiğini Doğrulayın + +Yüklediğiniz NuGet sürümünün çalışma zamanında kullanılan sürüm olduğunu varsaymak kolaydır, ancak ortam tuhaflıkları devreye girebilir. Çift kontrol için: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Bu ek kodu çalıştırdığınızda aşağıdakine benzer bir çıktı alırsınız: + +``` +Assembly file version: 24.5.7.0 +``` + +İki değer farklıysa, Global Assembly Cache (GAC) ya da önceki bir derleme klasöründen eski bir DLL yüklüyor olabilirsiniz. Bu durumda çözümünüzü temizleyin (`dotnet clean`) ve yeniden derleyin. + +--- + +## 4. Adım: Sürüm Kontrolünü Üretim Günlüğüne Entegre Edin + +Çoğu gerçek dünya uygulaması sadece konsola yazdırmaz; bir günlük dosyasına ya da telemetri sistemine yazar. İşte `Microsoft.Extensions.Logging` kullanarak hızlı bir örnek: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Artık sürüm, yapılandırılmış günlüklerinizde `{Version}` alanı üzerinden kolayca filtrelenebilir. Bu desen, her bir mikro‑servisin potansiyel olarak farklı bir OCR DLL’si çektiği senaryolarda özellikle kullanışlıdır. + +--- + +## Yaygın Sorular & Kenar Durumları + +### `GetVersion()` boş bir dize döndürürse ne olur? + +Bu genellikle bozuk bir kurulum ya da eksik bir yerel bağımlılık işaretidir. NuGet paketini yeniden yükleyin ve `Aspose.OCR.Native.dll` (veya ilgili platform‑spesifik ikili) çalıştırılabilir dosyanızın yanına yerleştirildiğinden emin olun. + +### Metod .NET Core 2.0’da çalışır mı? + +Evet, **Aspose OCR** .NET Standard 2.0 ve üzerini destekler; bu standardı uygulayan herhangi bir .NET Core sürümü `OcrEngine.GetVersion()`’ı çağırabilir. Self‑contained bir uygulama yayınlıyorsanız, doğru çalışma zamanı tanımlayıcılarını (`win-x64`, `linux-x64` vb.) referans gösterdiğinizden emin olun. + +### Lisans dosyası olmadan sürümü alabilir miyim? + +Kesinlikle. `GetVersion()` **lisans** gerektirmez; sadece kütüphane derleme numarasını raporlar. Ancak geçerli bir lisans olmadan OCR çalıştırmaya çalışırsanız çalışma zamanı istisnası alırsınız. Bu yüzden snippet’imizdeki `try/catch` bloğu, sürüm kontrolünü OCR yürütme akışından izole eder ve değerli bir koruma sağlar. + +--- + +## Tam Çalışan Örnek (Kopyala‑Yapıştır Hazır) + +Aşağıda, yeni bir konsol projesine bırakabileceğiniz tüm program yer alıyor. İsteğe bağlı günlük bloğu da dahil, hem konsol çıktısını hem de yapılandırılmış günlükleri aynı anda görebileceksiniz. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +`dotnet run` ile çalıştırın; sürümü onaylayan iki satır ve `LogLevel.Debug` etkinleştirildiğinde bir debug satırı göreceksiniz. + +--- + +## Sonuç + +C# ortamında **Aspose OCR sürümünü** almanız için gereken her şeyi kapsadık—**Aspose OCR kütüphanesini** kurmaktan, **ocrengine getversion** metodunu çağırmaya, hataları yönetmeye ve sonucu üretim‑düzeyinde günlüklemeye kadar. Bu bilgiyle artık uygulamanızın kullandığı tam OCR derlemesini güvenilir şekilde doğrulayabilir, sürüm‑kaynaklı hatalardan kaçınabilir ve uyumluluk gereksinimlerini zahmetsizce karşılayabilirsiniz. + +Sonraki adım? Bu sürüm kontrolünü gerçek bir OCR çağrısıyla (`OcrEngine` → `RecognizeImage`) birleştirip hem sürümü hem de tanıma sonucunu günlüğe kaydedin. Ayrıca **retrieve aspose version** desenini diğer Aspose ürünleri (PDF, Slides, Cells) için de keşfederek bütün suite’inizin senkronize kalmasını sağlayabilirsiniz. + +Keyifli kodlamalar, OCR boru hatlarınız keskin kalsın! + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanarak yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini ustalaşmanız ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmeniz için adım‑adım açıklamalı tam çalışan kod örnekleri içerir. + +- [Aspose.OCR for .NET ile OCR Sonuçlarını Nasıl Alırsınız](/ocr/english/net/text-recognition/get-recognition-result/) +- [Aspose.OCR Kullanarak Dil Seçimiyle C#’ta Görüntü Metni Çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR for .NET’te Liste Kullanarak Toplu OCR Görüntü İşleme](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/turkish/net/ocr-optimization/_index.md index 12ce2f053..d4933b786 100644 --- a/ocr/turkish/net/ocr-optimization/_index.md +++ b/ocr/turkish/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Aspose.OCR for .NET’ü keşfedin. Ön işleme filtreleriyle OCR doğruluğunu Aspose.OCR for .NET ile OCR doğruluğunu artırın. Yazım hatalarını düzeltin, sözlükleri özelleştirin ve hatasız metin tanımayı zahmetsizce sağlayın. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) Aspose.OCR for .NET’ün potansiyelini ortaya çıkarın. Bu kapsamlı adım adım rehberle çok sayfalı OCR sonuçlarını belgeler olarak zahmetsizce kaydedin. +### [Aspose OCR C# Örneği – GPU'yu Etkinleştir, Bellek Sınırını Ayarla ve TIF Görüntülerini İşle](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Aspose.OCR for .NET ile GPU'yu etkinleştirin, bellek sınırı ayarlayın ve TIF görüntülerini işleyin. ## Sıkça Sorulan Sorular diff --git a/ocr/turkish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/turkish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..7ace1097e --- /dev/null +++ b/ocr/turkish/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,287 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR C# örneği, GPU bellek sınırını nasıl ayarlayacağınızı, OCR + için görüntüyü nasıl yükleyeceğinizi ve TIF dosyalarından metni tam kod ve ipuçlarıyla + tanıma işlemini gösterir. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: tr +og_description: 'Tam bir Aspose OCR C# örneğini öğrenin: GPU''yu etkinleştirin, GPU + bellek sınırını ayarlayın, OCR için bir görüntü yükleyin ve TIF dosyalarından metni + tanıyın. Tam kod dahil.' +og_title: Aspose OCR C# Örneği – GPU Hızlandırma, Bellek Sınırı ve TIF İşleme +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Aspose OCR C# Örneği – GPU'yu Etkinleştir, Bellek Sınırını Ayarla ve TIF Görüntülerini + İşle +url: /tr/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR C# Örneği – GPU'yu Etkinleştir, Bellek Sınırını Ayarla ve TIF Görüntüleri İşle + +Büyük TIFF taramalarıyla çalışırken **Aspose OCR C# example** kodundan en yüksek performansı nasıl alabileceğinizi hiç merak ettiniz mi? Tek başınıza değilsiniz. Gerçek dünyadaki birçok projede—örneğin arşivleri dijitalleştirmek ya da yüksek çözünürlüklü fişlerden veri çıkarmak—darboğaz OCR algoritması değil, donanım kullanımındadır. + +Şöyle bir şey var: Aspose OCR GPU hızlandırmasını destekliyor, ancak ona ne kadar bellek kullanabileceğini söylemeniz, doğru görüntü tipini yüklemeniz ve sonunda .tif dosyasından tanınan metni almanız gerekiyor. Bu öğretici, SDK'yı kurmaktan GPU ayarlarını ince ayarlamaya kadar her adımı size gösteriyor, böylece GPU'nuzun RAM'ini boşaltmadan OCR'ı ışık hızında çalıştırabilirsiniz. + +Ayrıca birkaç “ya böyle olursa” senaryosu da ekleyeceğiz—örneğin çok sayfalı TIFF'leri işlemek ya da bir GPU bulunmadığında CPU'ya geri dönmek—böylece tek seferlik bir kod parçacığı değil, sağlam bir çözüm elde edersiniz. + +## Gerekenler + +İlerlemeye başlamadan önce makinenizde aşağıdakilerin olduğundan emin olun: + +| Önkoşul | Neden Önemli | +|--------------|----------------| +| **.NET 6 SDK** (veya daha yeni) | Aspose OCR, .NET Standard 2.0+ hedefler; bu yüzden herhangi bir yeni .NET sürümü çalışır. | +| **Aspose.OCR NuGet paketi** (`Install-Package Aspose.OCR`) | `OcrEngine`, `GpuSettings` vb. sağlayan çekirdek kütüphane. | +| **CUDA 11+** (NVIDIA) **veya ROCm 5+** (AMD) | GPU hızlandırması için gerekli; SDK çalışma zamanında uyumlu bir sürücü kontrol eder. | +| En az **2 GB VRAM** sahip **GPU** (biz 2048 MB olarak sınırlayacağız) | Yeterli bellek olmazsa motor sessizce CPU'ya geçebilir. | +| İşlemek istediğiniz **yüksek çözünürlüklü TIFF** görüntüsü | Aspose OCR neredeyse her raster formatını okuyabilir, ancak TIF taramalar için yaygındır. | +| Visual Studio 2022 (veya tercih ettiğiniz başka bir editör) | C# projesini derlemek ve hata ayıklamak için. | + +Bu öğelerden biri eksik olursa kod hâlâ derlenir, ancak aradığınız performans artışını göremezsiniz. + +## Adım 1: Aspose OCR C# Örneği Motorunu Oluşturun + +Her **Aspose OCR C# example**'ın ilk işi OCR motorunu örneklemektir. `OcrEngine`i bir film yönetmeni gibi düşünün—görüntü yüklemeden metin çıkarımına kadar her şeyi koordine eder. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Pro ipucu:** Birden çok görüntüyü ardışık işlemek istiyorsanız tek bir `OcrEngine` nesnesini canlı tutun. Her görüntü için yeniden oluşturmak, OCR süresini aşan bir ek yük getirir. + +## Adım 2: GPU Bellek Sınırını Ayarlayın (ve Hızlandırmayı Etkinleştirin) + +Şimdi çoğu kişinin takıldığı kısma geliyoruz: **GPU bellek sınırını ayarlama**. Varsayılan olarak Aspose OCR, mümkün olduğunca fazla VRAM kullanmaya çalışır; bu da paylaşımlı bir iş istasyonunda diğer uygulamaları aç bırakabilir. `GpuSettings` nesnesi, tahsisatı sınırlamanıza izin verir. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Neden bellek sınırı belirlemelisiniz? + +- **Kararlılık:** Devasa görüntüler işlenirken bellek dışı hataları önler. +- **Birlikte Çalışabilirlik:** Diğer GPU‑ağır uygulamaların (ör. TensorFlow modelleri) yan yana çalışmasına olanak tanır. +- **Tahmin Edilebilirlik:** GPU takas yapmayacağı için performans testleri tekrarlanabilir olur. + +`MemoryLimitMb`'yi atlamanız durumunda Aspose, gerektiğini düşündüğü kadar bellek ayırır; bu, özel bir çıkarım sunucusunda sorun olmayabilir ama bir geliştirici dizüstü bilgisayarında riskli olabilir. + +## Adım 3: OCR İçin Görüntüyü Yükleyin + +Doğru dosya formatını yüklemek bir sonraki kritik adımdır. `OcrImage.FromFile` yöntemi görüntü tipini otomatik algılar, ancak dosyanın var olduğunu ve desteklenen bir TIFF varyantı (ör. LZW‑sıkıştırmalı veya CCITT‑G4) olduğunu yine de kontrol etmelisiniz. + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Çok sayfalı TIFF'leri işleme + +TIFF'inizde birden fazla sayfa varsa, Aspose OCR varsayılan olarak sadece ilkini okur. Tüm sayfaları işlemek için `image.Pages` (yeni SDK sürümlerinde mevcut) üzerinden döngü kurabilir ve her sayfayı motorun içine ayrı ayrı besleyebilirsiniz. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Yukarıdaki kod parçacığı, tek‑sayfalı ve çok‑sayfalı dosyalar için çalışan **OCR için görüntü yükleme** desenini gösterir. + +## Adım 4: TIF'ten (veya herhangi bir raster) Metin Tanıyın + +Görüntü bellekte yerini aldığında, Aspose'a sihrini yapmasını söyleriz. `Recognize` yöntemi, düz metin, güven puanları ve gerekirse sınırlayıcı kutu bilgilerini içeren bir `OcrResult` döndürür. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Neden TIF ile iyi çalışır? + +- **Kayıpsız sıkıştırma:** TIFF genellikle ham piksel verisini saklar; bu da OCR motoruna en yüksek doğruluğu verir. +- **Çoklu renk uzayları:** Aspose, ek dönüşüm kodu yazmadan gri ton, RGB veya hatta CMYK TIFF'leri işleyebilir. + +Dil paketlerini (ör. Fransızca veya Japonca) ayarlamanız gerekiyorsa, `ocrEngine.Settings.Language = "fr"` satırını `Recognize` çağrısından önce ekleyin. + +## Adım 5: Tanınan Metni Görüntüleyin + +Son olarak metni konsola yazdırıyoruz. Gerçek bir uygulamada bunu bir veritabanına, JSON dosyasına yazabilir ya da bir sonraki NLP boru hattına aktarabilirsiniz. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Beklenen çıktı + +300 dpi çözünürlüğünde, net bir basılı sayfanın taramasıyla programı çalıştırdığınızda tipik olarak aşağıdakine benzer bir sonuç alırsınız: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Görüntü bulanıksa ya da GPU bellek sınırı çok düşükse, bozuk karakterler ya da kesik bir sonuç görebilirsiniz. `MemoryLimitMb`'yi görüntünün ayak izinin (genellikle 6000×8000 piksel bir TIFF için ~1 GB) altına düşürmek, motorun otomatik olarak CPU'ya geçmesine neden olur. + +## Tam Çalışan Örnek + +Aşağıda, kopyalayıp yeni bir Console App projesine yapıştırabileceğiniz, çalıştırmaya hazır tam program yer alıyor. `YOUR_DIRECTORY/large_photo.tif` kısmını kendi TIFF dosyanızın yolu ile değiştirin ve **F5** tuşuna basın. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Hızlı kontrol listesi + +- ✅ **Aspose OCR C# example** hatasız derlendi. +- ✅ **GPU etkin** (`Enable = true`). +- ✅ **GPU bellek sınırı** 2048 MB olarak ayarlandı. +- ✅ **Görüntü** bir TIF dosyasından yüklendi. +- ✅ **Metin tanındı** ve ekrana basıldı. + +## Yaygın Tuzaklar & Kaçınma Yolları + +| Belirti | Muhtemel Neden | Çözüm | +|---------|----------------|-------| +| `System.DllNotFoundException: cudart64_110.dll` | CUDA çalışma zamanı yüklü değil ya da sürüm uyumsuzluğu. | Sürücünüzle eşleşen CUDA 11.x (veya 12.x) kurun. | +| OCR boş string döndürüyor | Görüntü çok karanlık ya da DPI < 150. | `image.AdjustContrast()` ile ön‑işlem yapın veya 300 dpi'ye yeniden örnekleyin. | +| GPU'da bellek dışı çökme | `MemoryLimitMb` görüntü için çok düşük. | Sınırı yükseltin ya da `image.Crop` ile görüntüyü parçalara bölün. | +| `Unsupported image format` hatası | TIFF egzotik bir sıkıştırma (ör. JPEG‑2000) kullanıyor. | OCR'dan önce ImageMagick ile TIFF'i desteklenen bir formata dönüştürün. | + +## Demoyu Genişletmek + +Şimdi sağlam bir **aspose ocr c# example**'a sahip olduğunuza göre aşağıdakileri keşfedebilirsiniz: + +- **Toplu işleme:** Bir klasördeki TIF'ler üzerinde döngü kurun, her sonucu bir `.txt` dosyasına yazın. +- **Dil paketleri:** `ocrEngine.Settings.Language = "es"` ile İspanyolca, ya da özel sözlükler yükleyin. +- **Sınırlayıcı kutular:** `ocrResult.Regions` ile her kelimenin koordinatlarını alın—kırpma araçları için kullanışlı. +- **CPU geri dönüşü:** GPU bloğunu try/catch içinde tutun; hata durumunda `ocrEngine.Settings.Gpu.Enable = false` yapıp yeniden deneyin. + +Bu uzantılar, temel deseni bozmadan belirli senaryolar için değer katar. + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve ilgili konuları derinlemesine ele alan tam çalışan kod örnekleri içerir. Her kaynak, ek API özelliklerini ustalaşmanız ve projelerinizde alternatif uygulama yaklaşımları keşfetmeniz için adım‑adım açıklamalar sunar. + +- [Aspose.OCR .NET ile Görüntüden Metin Çıkarma](/ocr/english/net/image-and-drawing-recognition/) +- [Aspose.OCR .NET için OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) +- [Aspose.OCR ile Dil Seçimi Kullanarak C#'ta Görüntü Metni Çıkarma](/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/net/skew-angle-calculation/_index.md b/ocr/turkish/net/skew-angle-calculation/_index.md index e8878e248..f8036c9a8 100644 --- a/ocr/turkish/net/skew-angle-calculation/_index.md +++ b/ocr/turkish/net/skew-angle-calculation/_index.md @@ -40,9 +40,11 @@ C# uygulamalarınızda doğru metin tanıma için güçlü bir OCR çözümü ol Görüntü tanıma için güçlü bir çözüm olan Aspose.OCR for .NET'in gücünü açığa çıkarın. Eğim açılarını zahmetsizce nasıl hesaplayacağınızı öğrenin. ### [OCR Görüntü Tanıma'da URI'den Eğim Açısını Hesaplama](./calculate-skew-angle-from-uri/) OCR görüntü tanımada eğim açılarını zahmetsizce hesaplamak için Aspose.OCR for .NET'i keşfedin. Projelerinizi hassasiyet ve verimlilikle geliştirin. +### [OCR Döndürülmüş Belge Öğreticisi – C#'ta Otomatik Eğim ve Döndürme Düzeltmesi](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +C# ile döndürülmüş belgelerde otomatik eğim ve döndürme düzeltmesi yaparak OCR doğruluğunu artırın. {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/turkish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..7ee119da9 --- /dev/null +++ b/ocr/turkish/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-06-03 +description: Aspose OCR kullanarak C#’ta eğimi otomatik düzeltmeyi ve döndürmeyi algılamayı + gösteren döndürülmüş belge OCR öğreticisi. Tam kod ile adım adım öğrenin. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: tr +og_description: OCR döndürülmüş belge öğreticisi, Aspose OCR'i C# içinde kullanarak + kaymayı otomatik olarak düzeltmeyi ve dönüşü tespit etmeyi öğretir. Tam kılavuzu + izleyin. +og_title: OCR Döndürülmüş Belge Öğreticisi – C#'ta Otomatik Eğrilik ve Döndürme Düzeltmesi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: OCR Döndürülmüş Belge Öğreticisi – C#'ta Otomatik Eğrilik ve Döndürme Düzeltmesi +url: /tr/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Döndürülmüş Belge Öğreticisi – C# Geliştiricileri için Tam Kılavuz + +Ever stumbled upon an **ocr rotated document tutorial** when a scanned form came in sideways or slanted? You’re not alone. Those wonky images can ruin a clean text extraction, but the good news is that Aspose OCR can straighten things out for you automatically. + +Bu adım‑adım rehberde bir `OcrEngine` oluşturacağız, **automatic skew correction** ve **auto detect rotation** özelliklerini açacağız, motoru döndürülmüş bir görüntüde çalıştıracağız ve temiz metni yazdıracağız. Sonunda her ayarın neden önemli olduğunu, kenar durumları için nasıl ayarlayacağınızı tam olarak öğrenecek ve çalıştırmaya hazır bir C# programına sahip olacaksınız. + +## Öğrenecekleriniz + +* .NET projesinde **Aspose OCR**'yi nasıl kurup referans göstereceğinizi öğrenin. +* `AutoCorrectSkew` ve `AutoDetectRotation`'ı etkinleştirmenin güvenilir bir **ocr rotated document tutorial** için anahtar olduğunu öğrenin. +* Herhangi bir görüntüyü (JPG, PNG, TIFF) nasıl yükleyeceğinizi ve motorun işi halletmesine izin vereceğinizi öğrenin. +* Çok sayfalı PDF'ler, düşük çözünürlüklü taramalar ve özel dil paketleriyle başa çıkma ipuçları. + +> **Önkoşullar:** Visual Studio 2022 (veya herhangi bir C# IDE), .NET 6+ çalışma zamanı ve geçerli bir Aspose OCR lisansı (veya ücretsiz deneme). Önceden OCR deneyimi gerekmez. + +--- + +## Adım 1 – Aspose OCR'yi Kurun ve Projeyi Ayarlayın + +İlk olarak, NuGet paketini alın: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro ipucu:** Deneme lisansı kullanıyorsanız, `Aspose.OCR.lic` dosyasını çalıştırılabilir dosyanızla aynı klasöre koyun veya programatik olarak `License license = new License(); license.SetLicense("Aspose.OCR.lic");` ile kaydedin. + +Create a new console app: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Şimdi **ocr rotated document tutorial** için temiz bir başlangıç noktanız var. + +## Adım 2 – OCR Motorunu Başlatın + +Motor, sürecin kalbidir. Metin çıkarımı için çok amaçlı bir İsviçre çakısı gibi düşünün; sadece hangi özellikleri etkinleştireceğini ona söylemeniz yeterli. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Bu ayarlar neden?** +* `AutoCorrectSkew` karakterlerin temel çizgisini analiz eder ve satırları yatay hâle getirecek kadar görüntüyü döndürür. +* `AutoDetectRotation` genel yönelimi (0°, 90°, 180°, 270°) inceler ve sayfa ters ise çevirir. Bunlar olmadan motor “pɹᴉʍ” yerine “word” okur. + +## Adım 3 – İşlemek İstediğiniz Görüntüyü Yükleyin + +Aspose OCR, yaygın raster formatlarının tümüyle çalışır. Yer tutucu yolu, döndürülmüş formunuzun gerçek konumuyla değiştirin. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Kenar durumu:** Çok sayfalı bir TIFF alırsanız, `OcrImage.FromMultiPageTiff(filePath)` kullanın ve `image.Pages` üzerinden döngü yapın. + +## Adım 4 – Tanıma İşlemini Çalıştırın + +Şimdi motor sihri yapar. Önce görüntüyü (eğim/döndürme bayraklarımız sayesinde) düzleştirir ve ardından karakterleri çıkarır. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +İngilizce dışındaki dil desteğine ihtiyacınız varsa, `Recognize` çağırmadan önce ayarlayın: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Adım 5 – Tanınan Metni Çıktılayın + +Son olarak, temiz metni konsola dökün—veya bir dosyaya, veritabanına, iş akışınıza uyan bir yere yönlendirin. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Beklenen çıktı** (örnek görüntünün “Invoice #1234” içerdiğini varsayarsak): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Kaynak görüntü 90° döndürülmüş ve hafif eğilmiş olsa bile metnin doğru göründüğüne dikkat edin. + +## Yaygın Sorunlarla Baş Etme + +| Sorun | Neden Oluşur | Çözüm | +|------|----------------|-----| +| **Boş çıktı** | Eğim düzeltmesi devre dışı bırakılmış veya görüntü çok karanlık. | `AutoCorrectSkew`'i etkinleştirin (zaten açık) ve `image.AdjustContrast(1.2)` ile görüntü kontrastını artırın. | +| **Bozuk karakterler** | Yanlış dil ayarı. | `ocrEngine.Settings.Language`'i belge diline uygun şekilde ayarlayın. | +| **Büyük PDF'lerde performans gecikmesi** | Motor her sayfayı sıralı olarak işler. | Çok çekirdekli CPU'ları kullanmak için `image.Pages` üzerinde `Parallel.ForEach` kullanın. | +| **Lisans istisnası** | Deneme süresi doldu. | Kalıcı bir lisans edinin veya deneme sınırları içinde kalın (her çalıştırmada 5 sayfa). | + +## Sağlam Bir OCR Döndürülmüş Belge Öğreticisi İçin Pro İpuçları + +* **Batch processing:** Tüm akışı bir klasör yolu kabul eden, her görüntüyü döngüye alan ve her sonucu bir `.txt` dosyasına yazan bir yöntem içinde paketleyin. +* **Pre‑processing:** Bazen gürültülü bir tarama, tanımadan önce `image.Denoise()` ile fayda sağlar. +* **Post‑processing:** Yaygın OCR hatalarını temizlemek için düzenli ifadeler kullanın, örneğin “0” karakterini yalnızca harflerle çevriliyse “O” ile değiştirin. +* **Logging:** Aspose OCR, `ocrEngine.Logger` sağlar – düşük güven puanlarıyla ilgili uyarıları yakalamak için bir dosya günlüğüne bağlayın. + +## Tam, Çalıştırmaya Hazır Kod + +Aşağıdakileri konsol projenizin içinde `Program.cs` olarak kaydedin. Tüm adımları, yorumları ve toplu işleme için küçük bir yardımcı işlevi içerir. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Run it: + +```bash +dotnet run +``` + +Konsola temizlenmiş metnin yazdırıldığını görmelisiniz; bu da **ocr rotated document tutorial**'ımızın uçtan uca çalıştığını kanıtlar. + +## Sonuç + +Artık Aspose OCR kullanarak C# içinde eğimi otomatik olarak düzelten, döndürmeyi algılayan ve temiz metin çıkaran eksiksiz bir **ocr rotated document tutorial**'a sahipsiniz. Temel çıkarım? `AutoCorrectSkew` **ve** `AutoDetectRotation`'ı etkinleştirmek, umutsuzca eğilmiş bir taramayı sadece birkaç kod satırıyla tamamen okunabilir bir çıktıya dönüştürür. + +Buradan itibaren toplu işler ekleyebilir, dil paketlerini entegre edebilir veya sonuçları sonraki analiz hatlarına aktarabilirsiniz. **automatic skew correction**'ı daha fazla keşfetmek ister misiniz? Aspose'un görüntü ön işleme API'sine göz atın veya gürültülü taramalar için özel eşiklerle deney yapın. + +PDF'lerle, çok sayfalı TIFF'lerle başa çıkma veya Azure Functions ile entegrasyon hakkında sorularınız mı var? Yorum bırakın, iyi kodlamalar! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan yakın konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım‑adım açıklamalar içerir. + +- [ocr document mode – Detect Areas Mode in OCR Image Recognition](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR Tutorial – Optical Character Recognition](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/turkish/net/text-recognition/_index.md index 5ddf0e83d..797f8fb3c 100644 --- a/ocr/turkish/net/text-recognition/_index.md +++ b/ocr/turkish/net/text-recognition/_index.md @@ -53,11 +53,21 @@ Aspose.OCR for .NET'in gücünü açığa çıkarın. OCR sonuçlarını JSON fo Etkili görüntü metni tanıma için .NET uygulamalarınızı Aspose.OCR ile geliştirin. Kesin sonuçlar için OCR Tespit Alanları Modunu keşfedin. ### [OCR Görüntü Tanıma'da PDF'yi tanıma](./recognize-pdf/) Aspose.OCR ile .NET'te OCR'nin potansiyelini ortaya çıkarın. PDF'lerden metni zahmetsizce çıkarın. Sorunsuz bir entegrasyon deneyimi için hemen indirin. +### [Aspose.OCR ile PDF'de OCR Yapma – Tam C# Kılavuzu](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Aspose.OCR kullanarak PDF dosyalarından metin çıkarmayı adım adım öğrenin ve C# ile tam entegrasyonu keşfedin. ### [OCR Görüntü Tanıma'da Tabloyu Tanıma](./recognize-table/) OCR görüntü tanımada tabloları tanımaya ilişkin kapsamlı kılavuzumuzla Aspose.OCR for .NET'in potansiyelini ortaya çıkarın. +### [Aspose OCR ile Görüntüde OCR Yapma – Hint Kılavuzu](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Aspose OCR kullanarak Hint dilinde görüntüden metin çıkarma adımlarını öğrenin. +### [Aspose Kullanımı: OCR ile Görüntüyü HTML'ye Dönüştürme](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Aspose.OCR kullanarak bir görüntüyü HTML formatına dönüştürmeyi adım adım öğrenin. +### [C# ile Görüntüde OCR Yapma ve Yanlış Yazılmış Kelimeleri Algılama](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +### [C# ile Video Altyazı OCR – Tam Kılavuz](./video-subtitle-ocr-in-c-complete-guide/) +C# kullanarak video dosyalarındaki altyazıları OCR ile tanıyın ve metin olarak çıkarın. Adım adım tam rehber. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/turkish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..317313c5c --- /dev/null +++ b/ocr/turkish/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Aspose kullanarak resmi HTML'ye dönüştürme ve C#'ta resimden metin çıkarma. + Resimden HTML oluşturmayı ve OCR ile resmi hızlıca HTML'ye dönüştürmeyi öğrenin. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: tr +og_description: Aspose kullanarak resmi HTML'ye dönüştürme, resimden metin çıkarma + ve OCR ile C#'ta resimden HTML oluşturma. Bu kapsamlı rehberi izleyin. +og_title: 'Aspose Nasıl Kullanılır: Görüntüyü OCR ile HTML''ye Dönüştürme' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Aspose Nasıl Kullanılır: Görüntüyü OCR ile HTML''ye Dönüştürme' +url: /tr/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose Nasıl Kullanılır: Görüntüyü OCR ile HTML'ye Dönüştürme + +Hiç **Aspose nasıl kullanılır** sorusunu aklınıza getirip taranmış bir resmi düzenli HTML'e dönüştürmeyi düşündünüz mü? Belki bir dergi sayfası, bir fiş ya da el yazısı bir notunuz var ve metni ve düzeni web yayıncılığı için korumanız gerekiyor. İyi haber şu ki, özel bir ayrıştırıcı yazmanıza ya da düşük‑seviye görüntü işleme ile uğraşmanıza gerek yok—Aspose.OCR bu işi sizin yerinize yapıyor. + +Bu öğreticide, **tam, çalıştırılabilir bir örnek** üzerinden **görüntüyü HTML'ye dönüştürme**, **görüntüden metin çıkarma** ve **görüntüden HTML üretme** işlemlerini Aspose OCR kütüphanesini C# ile nasıl kullanacağınızı adım adım göstereceğiz. Sonunda, orijinal sayfa düzeni korunmuş bir HTML dosyası üreten küçük bir konsol uygulamanız olacak ve bu dosyayı istediğiniz web sitesine kolayca ekleyebileceksiniz. + +## Önkoşullar + +İşe başlamadan önce makinenizde aşağıdakilerin yüklü olduğundan emin olun: + +- **.NET 6.0 SDK** veya daha yeni bir sürüm (kod .NET Core ve .NET Framework ile aynı şekilde çalışır). +- **Visual Studio 2022** (ya da tercih ettiğiniz başka bir editör). +- **Aspose.OCR for .NET** – NuGet üzerinden kurun: `dotnet add package Aspose.OCR`. +- Dönüştürmek istediğiniz bir görüntü dosyası (JPEG/PNG), örnek: `magazine_page.jpg`. + +Ek bir yapılandırma dosyasına ihtiyaç yok; kütüphane OCR ve HTML düzen üretimi için gereken her şeyi içinde barındırıyor. + +## Adım 1: Projeyi Oluşturun ve Aspose.OCR'ı Ekleyin + +İlk olarak yeni bir konsol projesi oluşturun ve Aspose OCR paketini ekleyin. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro ipucu:** Visual Studio kullanıyorsanız, proje üzerine sağ‑tıklayın → *Manage NuGet Packages* → **Aspose.OCR** aratın ve kurun. Bu adım, **ocr image to html** işlemini eksik referans olmadan yapmanızı sağlar. + +## Adım 2: OCR Motorunu Başlatın + +İşlemin çekirdeği `OcrEngine` sınıfıdır. Bunu, resmi okuyup sonucu nasıl çıktıya dönüştüreceğini belirleyen beyin olarak düşünebilirsiniz. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Burada `OcrEngine` örneğini oluşturuyoruz. Ücretsiz sürüm için herhangi bir kimlik bilgisi girmenize gerek yok; kütüphane yerleşik tanıma modellerini kullanacaktır. + +## Adım 3: Kaynak Görüntüyü Yükleyin + +Sonra motoru işlemek istediğiniz dosyaya yönlendirin. Aspose, çoğu görüntü formatını destekleyen kullanışlı bir `OcrImage.FromFile` metoduna sahiptir. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +`YOUR_DIRECTORY` kısmını, görüntünüzün bulunduğu mutlak ya da göreli yol ile değiştirin. Görüntü çalıştırılabilir dosyanın aynı klasöründeyse sadece `"magazine_page.jpg"` kullanabilirsiniz. + +## Adım 4: Tanıma Yapın ve Düzenli HTML İsteyin + +Bu, öğreticinin kalbidir. `OutputFormat.HtmlWithLayout` değerini göndererek Aspose'a **görüntüden HTML üret** komutunu veriyoruz; böylece metin blokları, görseller ve tabloların orijinal konumları korunur. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +`recognitionResult.Text` özelliği artık tam bir HTML belgesi içeriyor. Sadece düz metin isteseydiniz `OutputFormat.Text` kullanabilirdiniz, ancak burada **convert image to html** işlemini düzen sadakatiyle yapıyoruz. + +## Adım 5: HTML Dosyasını Kaydedin + +Son olarak, HTML dizesini diske yazın. Böylece istediğiniz tarayıcıda açabileceğiniz hazır bir dosyanız olur. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Programı çalıştırdığınızda `magazine.html` oluşturulacak. Açtığınızda, orijinal sayfanın metni tam olarak kaynak görüntüdeki gibi konumlanmış olarak görünecek—arşivleme ya da web yayıncılığı için mükemmel. + +## Tam Çalışan Örnek + +Aşağıda **tam, kopyala‑yapıştır‑hazır** program yer alıyor. Hiçbir parça atlanmadı, bu yüzden doğru yolları ayarladıktan hemen sonra derleyip çalıştırabilirsiniz. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Beklenen Çıktı + +`magazine.html` dosyasını bir tarayıcıda açtığınızda aşağıdaki gibi (örnek amaçlı sadeleştirilmiş) bir görünüm elde etmelisiniz: + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Tam `style` nitelikleri orijinal görüntüye bağlı olarak değişecektir, ancak yapı **extract text from image** ve **generate html from image** işlemlerinin tek bir sorunsuz adımda gerçekleştiğini garanti eder. + +## Sık Sorulan Sorular & Kenar Durumlar + +### Görüntü düşük çözünürlükte ise ne olur? + +Aspose.OCR, en az **300 DPI** olan görüntülerde en iyi performansı gösterir. Dosyanız bulanıksa, OCR motoruna göndermeden önce bir görüntü iyileştirme kütüphanesi (ör. ImageSharp) ile ön işleme yapmayı deneyin. Düşük kalite, **extract text from image** doğruluğunu ve oluşturulan HTML düzeninin sadakatini etkileyebilir. + +### OCR dilini kontrol edebilir miyim? + +Evet. `OcrEngine` üzerinde `Recognize` çağrısından önce `Language` özelliğini ayarlayın: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Bu, İngilizce dışındaki karakterlerle çalışırken tanıma kalitesini artırır. + +### HTML yerine sadece düz metin almak istiyorum, nasıl yaparım? + +Sadece ham dizeye ihtiyacınız varsa `OutputFormat.HtmlWithLayout` yerine `OutputFormat.Text` kullanın. Aynı `recognitionResult.Text` özelliği o zaman sadece çıkarılan karakterleri içerir. + +### Oluşturulan HTML'e görselleri gömmek mümkün mü? + +Aspose.OCR, `OutputFormat.HtmlWithLayoutAndImages` kullanıldığında orijinal görüntüyü base‑64 veri URI'si olarak gömebilir. Bu, dış varlıklar olmadan tek bir HTML dosyası istediğinizde çok kullanışlıdır. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Büyük toplu işler nasıl yönetilir? + +Toplu işleme için mantığı bir dosya yolu listesi üzerinde `foreach` döngüsüyle sarın. Aynı `OcrEngine` örneğini yeniden kullanmak, yükü azaltır ve **convert image to html** hattını hızlandırır. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Üretim‑Hazır Kod İçin İpuçları + +- **Kaynakları serbest bırakın**: Hem `OcrEngine` hem de `OcrImage` `IDisposable` uygular. `using` ifadeleriyle sarmalayarak yerel belleği zamanında temizleyin. +- **Hata yönetimi**: Dosya ile ilgili sorunlar için `IOException`, tanıma problemleri için `OcrException` yakalayın. +- **Performans**: Çok sayıda görüntü işliyorsanız **paralellik** (`Parallel.ForEach`) etkinleştirmeyi düşünün ancak CPU kullanımına dikkat edin—OCR işlemci‑ağırdır. +- **Günlükleme**: OCR güven skorlarını (`recognitionResult.Confidence`) kalite izleme için yakalamak üzere bir logger (ör. Serilog) entegre edin. + +## Sonuç + +Aspose kullanarak **görüntüyü HTML'ye dönüştürme**, **görüntüden metin çıkarma** ve **görüntüden HTML üretme** işlemlerini birkaç basit adımda nasıl yapacağınızı gördük. Tam kod örneği, **ocr image to html** yaparken düzeni korumanızı sağlayarak belge‑dijitalleştirme projeleriniz için sağlam bir temel sunar. + +Bundan sonra şunları deneyebilirsiniz: + +- İhtiyacınıza uygun farklı `OutputFormat` seçeneklerini keşfedin. +- HTML çıktısını bir CSS framework'ü ile birleştirerek duyarlı tasarımlar oluşturun. +- Çıkarılan metni bir arama indeksine ya da makine öğrenmesi hattına besleyin. + +Deneyin, ayarları ince ayarlayın ve Aspose'un resimleri web‑hazır içeriğe nasıl zahmetsizce dönüştürdüğünü görün. Sorun yaşarsanız yorum bırakın—iyi kodlamalar! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + + +## Sonraki Öğrenmeniz Gerekenler + + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayalı olarak yakın ilişkili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olacak tam çalışan kod örnekleri ve adım adım açıklamalar içerir. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/turkish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..b6107c2a0 --- /dev/null +++ b/ocr/turkish/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,241 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR kullanarak görüntüde OCR gerçekleştirip metni çıkarın. Tek + bir C# demosunda yanlış yazılmış kelimeleri nasıl tespit edeceğinizi ve yazım önerilerini + nasıl alacağınızı öğrenin. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: tr +og_description: Görüntüdeki metni çıkarmak için OCR yapın, ardından hatalı yazılmış + kelimeleri tespit edin ve Aspose.OCR ile C#’ta yazım önerileri alın. +og_title: Resimde OCR Yap ve C#'ta Yazım Hatalı Kelimeleri Tespit Et +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Görüntüde OCR Yap ve C#'ta Yanlış Yazılmış Kelimeleri Tespit Et +url: /tr/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntü Üzerinde OCR Yapma ve C#'ta Yazım Hatalı Kelimeleri Tespit Etme + +Saçınızı yolmak zorunda kalmadan **perform OCR on image** dosyalarının nasıl yapılacağını hiç merak ettiniz mi? Tek başınıza değilsiniz. İster eski mektupları dijitalleştiriyor olun, faturaları tarıyor olun ya da akıllı bir belge iş akışı oluşturuyor olun, resimlerden temiz metin çıkarmak ilk engeldir. İyi haber? Aspose.OCR ile dakikalar içinde bir çözüm oluşturabilirsiniz ve ek olarak aynı çalıştırmada **detect misspelled words** ve **get spelling suggestions** da yapabilirsiniz. + +Bu öğreticide, **extracts text from image** yapan, bir İngilizce yazım denetleyicisi çalıştıran ve her hatayı kullanışlı düzeltme önerileriyle yazdıran tam, çalıştırmaya hazır bir C# konsol uygulamasını adım adım inceleyeceğiz. Sonuna geldiğinizde **how to extract text**'i tam olarak bilecek, spell‑check API'sini nasıl bağlayacağınızı ve beklenen konsol çıktısının nasıl göründüğünü öğreneceksiniz. + +## Oluşturacağınız Şey + +- Tipografik hatalar içeren bir bitmap (veya PNG) yükleyin. +- Aspose.OCR'yi **perform OCR on image** yapmak ve ham dize verisi elde etmek için çalıştırın. +- Yerleşik İngilizce yazım denetleyiciyi başlatın. +- **Detect misspelled words** ve her biri için **get spelling suggestions** alın. +- Konsola düzenli bir rapor yazdırın. + +Harici hizmetler yok, uğraştırıcı HTTP çağrıları yok—sadece tek bir NuGet paketi ve birkaç satır kod. + +## Önkoşullar + +- .NET 6.0 SDK veya daha yenisi (kod .NET Framework 4.7+ üzerinde de çalışır). +- Visual Studio 2022 (veya istediğiniz herhangi bir editör). +- .NET için Aspose.OCR NuGet paketi (`Aspose.OCR`). +- Projeden referans alabileceğiniz bir yerde bulunan bir görüntü dosyası (`letter_with_typos.png`). + +Aspose'u daha önce hiç kullanmadıysanız endişelenmeyin—paketi kurmak şu komutu çalıştırmak kadar kolay: + +```bash +dotnet add package Aspose.OCR +``` + +Şimdi uygulamaya dalalım. + +## Adım 1: Projeyi Kurun ve Aspose.OCR'yi Yükleyin + +Yeni bir konsol projesi oluşturun ve OCR kütüphanesini ekleyin: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Geri yükleme tamamlandıktan sonra `Program.cs` dosyasını açın. Varsayılan içeriği daha sonra tam demo kodu ile değiştireceğiz, ama önce her bir ad alanının neden önemli olduğundan bahsedelim. + +- `Aspose.OCR` – Çekirdek OCR motoru ve görüntü işleme. +- `Aspose.OCR.SpellCheck` – Kütüphane ile gelen yazım denetleme yardımcı programları. +- `System` – Standart .NET temel sınıfları (ör. `Console`). + +## Adım 2: Görüntüyü Yükleyin ve Görüntü Üzerinde OCR Yapın + +İlk gerçek iş, görüntüyü OCR motoruna beslemektir. Aspose.OCR birçok formatı (PNG, JPEG, TIFF) okur. İşte işi yapan kod parçacığı: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Neden önemli:** `OcrImage.FromFile` piksel‑seviyesindeki detayları soyutlar, `OcrEngine.Recognize` ise görsel glifleri Unicode karakterlerine çeviren eğitilmiş sinir modelini çalıştırır. `ocrResult.Text` özelliği artık ham dizeyi tutar—tam da **extract text from image**'e ihtiyacınız olan şey. +> **Pro ipucu:** Görüntünüz birden fazla dil içeriyorsa, `Recognize`'ı çağırmadan önce `ocrEngine.Language = OcrLanguage.Multilingual;` ayarlayabilirsiniz. + +## Adım 3: İngilizce Yazım Denetleyiciyi Başlatın + +Aspose.OCR, kutudan çıkar çıkmaz İngilizceyi anlayan yerleşik bir yazım denetleme motoru ile birlikte gelir. Onu başlatmak tek satırdır: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Bu adımın önemi:** OCR çıktısı hatalı tanınmış karakterler (ör. “l” vs “1”) veya kaynak belgeden gelen gerçek yazım hataları içerebilir. Yazım denetleyici dizeyi tarar, şüpheli tokenları bulur ve alternatifler önerir. + +## Adım 4: Yazım Hatalı Kelimeleri Tespit Edin ve Yazım Önerileri Alın + +Şimdi OCR metnini denetleyiciye besliyoruz: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings`, her bir girişin hatalı kelimeyi ve olası düzeltmelerin bir dizisini içerdiği bir koleksiyondur. + +## Adım 5: Sonuçları Çıktılayın + +Son olarak, koleksiyon üzerinde döngü kurup insan tarafından okunabilir bir rapor yazdırıyoruz: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Beklenen Konsol Çıktısı + +`letter_with_typos.png` dosyasının şu cümleyi içerdiğini varsayalım: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Demo çalıştırıldığında aşağıdakine benzer bir çıktı üretir: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Her bir yazım hatasının bir dizi makul düzeltme ile eşleştiğine dikkat edin—kullanıcı dostu bir düzeltme arayüzü oluştururken tam da ihtiyacınız olan şey. + +## Tam Çalışan Örnek + +Aşağıda **tam, kopyala‑yapıştır‑hazır** program bulunmaktadır. `YOUR_DIRECTORY` ifadesini görüntü dosyanızın gerçek yolu ile değiştirin. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Dikkate Alınması Gereken Kenar Durumları** +> - **Boş Görüntü:** OCR motoru boş bir dize döndürürse, `spellChecker.Check` sadece boş bir koleksiyon döndürür—çökme olmaz. +> - **İngilizce Olmayan Metin:** `OcrLanguage.English` yerine `OcrLanguage.French` (veya desteklenen herhangi bir dil) kullanarak **detect misspelled words**'i diğer yerel ayarlarda yapabilirsiniz. +> - **Büyük Belgeler:** Çok sayfalı PDF'lerde, her sayfada OCR çalıştırıp sonuçları birleştirerek yazım denetlemesinden önce toplarsınız. + +## Görsel Genel Bakış (Resim Alt Metni) + +![Görüntü üzerinde OCR yapma, görüntüden metin çıkarma ve ardından yazım hatalı kelimeleri yazım önerileriyle tespit etme akışını gösteren diyagram](perform-ocr-on-image-flow.png) + +*Yukarıdaki diyagram uçtan uca akışı gösterir: görüntü → OCR motoru → ham metin → yazım denetleyici → öneriler.* + +## Sık Sorulan Sorular & Pro İpuçları + +| Question | Answer | +|----------|--------| +| **İnternet bağlantısına ihtiyacım var mı?** | Hayır. Aspose.OCR tamamen yerel olarak çalışır; çevrim dışı veya güvenli ortamlar için mükemmeldir. | +| **Yazım denetleyici ne kadar doğru?** | Yaklaşık 150k İngilizce kelime içeren bir sözlük ve bulanık eşleşme kullanır, bu yüzden çoğu yaygın yazım hatası yakalanır. | +| **Sözlüğü özelleştirebilir miyim?** | Evet. `SpellChecker.AddUserDictionary("custom.txt")` domain‑spesifik terimleri (ör. ürün adları) yüklemenizi sağlar. | +| **Görüntü eğik olursa ne olur?** | OCR motoru yönelimi otomatik algılar, ancak inatçı durumlar için `ocrEngine.ImagePreprocessing.Rotate(angle)` metodunu manuel olarak çağırabilirsiniz. | +| **Önerileri UI'da vurgulamanın bir yolu var mı?** | `misspellings` koleksiyonuna sahip olduktan sonra, her bir `entry.Word`'i `ocrResult.Text` içindeki konumuna eşleyebilir ve RichTextBox ya da web görünümünde altını çizebilirsiniz. | + +## Sonuç + +Sizlere **how to perform OCR on image**, **extract text from image** ve ardından **detect misspelled words** yaparken **getting spelling suggestions** almayı gösterdik—hepsi kısa bir C# konsol uygulamasıyla. Temel fikir basit: karakter tanıma işini Aspose.OCR'ye bırakın, ardından yerleşik yazım denetleyicisi çıktıyı temizlesin. Buradan demo'yu tam bir belge işleme servisine genişletebilir, bir web API ile entegre edebilir veya bir masaüstü editörüne bağlayabilirsiniz. + +Bir sonraki adıma hazır mısınız? Dili İspanyolcaya değiştirin, çok sayfalı bir PDF besleyin veya kullanıcıların bir kelimeye tıklayarak öneriyi kabul etmesini sağlayan küçük bir WPF ön yüzü oluşturun. Yapı taşları zaten yerinde—denemeye devam edin. + +Herhangi bir sorunla karşılaşırsanız veya genişletme fikirleriniz varsa, aşağıya bir yorum bırakın. Kodlamanın tadını çıkarın! + +## Sonra Ne Öğrenmelisiniz? + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Aspose.OCR kullanarak dil seçimiyle Görüntü Metni Çıkarma C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose.OCR .NET ile Görüntüden Metin Çıkarma](/ocr/english/net/image-and-drawing-recognition/) +- [Görüntüden Metin Çıkarma – Aspose.OCR for .NET ile OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/turkish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..a1f52bf9f --- /dev/null +++ b/ocr/turkish/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,272 @@ +--- +category: general +date: 2026-06-03 +description: C#'da Aspose OCR kullanarak görüntüde OCR gerçekleştirin. OCR için görüntüyü + nasıl yükleyeceğinizi ve çevrim dışı olarak adım adım kodla Hintçe metin içeren + görüntüyü nasıl çıkaracağınızı öğrenin. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: tr +og_description: C#'ta Aspose OCR ile görüntüde OCR gerçekleştirin. Bu öğreticide, + OCR için görüntünün nasıl yükleneceği ve çevrim dışı olarak Hintçe metin içeren + görüntünün nasıl çıkarılacağı, çalıştırılabilir kodla birlikte gösterilmektedir. +og_title: Görüntüde OCR Yap – Aspose OCR Hint Kılavuzu +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Aspose OCR ile Görüntüde OCR Yapma – Hint Rehberi +url: /tr/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose OCR ile Görüntü Üzerinde OCR Yapma – Hintçe Kılavuz + +Görüntü dosyalarında **görüntü üzerinde OCR gerçekleştirme** ihtiyacı hiç duydunuz mu, ancak Hintçe karakterleri çıkarmakta takıldınız mı? Yalnız değilsiniz—birçok geliştirici, Latin dışı betikleri okumaya ilk kez çalıştıklarında bu engelle karşılaşıyor. İyi haber şu ki, Aspose OCR bunu oldukça sorunsuz hâle getiriyor ve tamamen çevrim dışı olarak da yapabilirsiniz. + +Bu kılavuzda **OCR için görüntü yükle**, motoru çevrim dışı dil paketlerinize yönlendirecek ve sonunda **Hintçe metin görüntüsü** verisini internete dokunmadan çıkaracağız. Sonunda, bir Hintçe makbuzu okuyup metni konsola yazdıran, çalıştırmaya hazır bir C# konsol uygulamanız olacak. + +## Gereksinimler + +- **.NET 6.0** veya üzeri (kod ayrıca .NET Framework 4.7+ üzerinde de çalışır) +- **Aspose.OCR for .NET** NuGet paketi + `dotnet add package Aspose.OCR` +- **çevrim dışı Hintçe dil kaynaklarını** içeren bir klasör (Aspose portalından indirin) +- Hintçe metin içeren bir görüntü dosyası, örn. `receipt_hindi.png` + +Hepsi bu—harici hizmetler yok, API anahtarları yok, sadece doğrudan kod. + +## Görüntü Üzerinde OCR – Adım Adım Uygulama + +Aşağıda süreci yedi net adıma bölüyoruz. Her adım **neden** önemli olduğunu, sadece **ne** yazmanız gerektiğini açıklıyor. + +### Adım 1: OCR Motoru Örneğini Oluşturun + +Motor, Aspose OCR'un kalbidir. Örneğini oluşturmak, daha sonra ayarlayacağınız tüm ayarlara erişim sağlar. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Neden?** +> Bir `OcrEngine` olmadan `Recognize` çağıracak nesneniz yoktur. Bunu, daha sonra resminizi tarayacak “kamera” olarak düşünün. + +### Adım 2: Motoru Çevrim Dışı Kaynaklara Yönlendirin + +Aspose, yerel olarak depolayabileceğiniz dil paketleri sunar. `ResourcesFolder` ayarı, motorun nerelere bakacağını belirtir. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **İpucu:** +> Geliştirme sırasında mutlak bir yol kullanın, ardından üretim için göreli bir yol veya yapılandırma ayarına geçin. + +### Adım 3: Çevrim Dışı Modu Zorla + +Şöyle düşünebilirsiniz: “Gerçekten çevrimiçi aramayı devre dışı bırakmam gerekiyor mu?” +Bir güvenlik duvarının arkasında çalışıyorsanız ya da belirli sonuçlar istiyorsanız, `UseOfflineResources` değerini `true` olarak ayarlayın. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Profesyonel ipucu:** +> Bu bayrağı `false` bırakmak, motorun ek veri indirmesine neden olabilir; bu da gecikme ekler ve güvenlik politikalarını ihlal edebilir. + +### Adım 4: Tanıma Dili Olarak Hintçe'yi Seçin + +Burada motoru hangi dili bekleyeceğini belirterek **Hintçe metin görüntüsü çıkar**ıyoruz. Bu, doğruluğu büyük ölçüde artırır. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Neden yardımcı olur:** +> OCR motorları dil‑spesifik karakter modelleri kullanır. Hintçe'ye kilitleyerek, motorun onlarca betik arasında tahmin yapmasını önlersiniz. + +### Adım 5: OCR için Görüntüyü Yükle + +Şimdi gerçekten **OCR için görüntüyü yükle**. `OcrImage.FromFile` yöntemi bitmap'i motorun anlayacağı bir formata okur. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Yaygın tuzak:** +> Windows'ta ileri eğik çizgiyle bir yol vermek çalışır, ancak `Path.Combine` kullanmak kodunuzu platform bağımsız hâle getirir. + +### Adım 6: Tanıma İşlemini Çalıştır + +Her şey ayarlandığında, sonunda `Recognize` çağırarak **görüntü üzerinde OCR gerçekleştir**. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Ne oluyor?** +> Motor her pikseli tarar, desenleri Hintçe glif veri tabanıyla eşleştirir ve bir Unicode karakter dizisi oluşturur. + +### Adım 7: Tanınan Metni Çıktıla + +Sonuç nesnesi, çıkarılan dizeyi tutan bir `Text` özelliği içerir. Biz sadece bunu konsola yazarız. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Beklenen çıktı:** +> `receipt_hindi.png` “भुगतान सफल” içeriyorsa, konsol tam olarak bu satırı, diakritik işaretleri koruyarak yazdırır. + +## OCR için Görüntü Yükleme – Kaynağı Hazırlama + +Motoru bir dosya yerine akış (stream) ile besleyip besleyemeyeceğinizi merak ediyorsanız, cevap evet. `OcrImage.FromFile` ifadesini şu şekilde değiştirin: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Neden akış kullanmalı?** +> Akışlar, veritabanlarında, bulut blob'larında veya gömülü kaynaklarda depolanan görüntülerle çalışmanıza olanak tanır—ölçeklenebilir hizmetler için mükemmeldir. + +## Hintçe Metin Görüntüsü Çıkarma – Kenar Durumlarını Ele Alma + +1. **Dil paketinin eksik olması** – Hintçe paketi bulunamazsa, `Recognize` bir istisna fırlatır. Çağrıyı try/catch içinde sarın ve dostça bir mesaj kaydedin. +2. **Düşük çözünürlüklü görüntüler** – OCR doğruluğu 300 dpi'nin altına düştüğünde azalır. Görüntüyü yüklemeden önce ön‑işlem yapın (yeniden boyutlandırma, keskinleştirme). +3. **Karışık dil belgeleri** – Birden fazla dili etkinleştirebilirsiniz: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Bu ayarlamalar, **görüntü üzerinde OCR gerçekleştir** rutininizin üretimde sağlam kalmasını sağlar. + +## Tam Örneği Çalıştırma + +`Program.cs` olarak aşağıdaki dosyayı kaydedin, yer tutucu yolları değiştirin ve çalıştırın: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +`dotnet run` komutunu çalıştırdığınızda, aşağıdakine benzer bir şey görmelisiniz: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Eğer boş bir dize alırsanız, **ResourcesFolder**'ın `Hindi.traineddata` içeren klasöre işaret ettiğini ve görüntünün yeterince net olduğunu iki kez kontrol edin. + +## Sonuç + +Aspose OCR ile **görüntü dosyalarında OCR gerçekleştir** nasıl yapılacağını adım adım inceledik; **OCR için görüntü yükle** den **Hintçe metin görüntüsü çıkar** a kadar tamamen çevrim dışı bir senaryoda her şeyi kapsadık. Yukarıdaki tam, çalıştırılabilir kod size sağlam bir temel sağlar ve akışlar, hata yönetimi ve çok‑dilli destek üzerine ipuçları, çözümü gerçek dünya projelerine uyarlamanıza yardımcı olacaktır. + +Bir sonraki adıma hazır mısınız? Dili **OcrLanguage.Tamil** olarak değiştirmeyi ya da Azure Blob depolamadan görüntü beslemeyi deneyin. Ayrıca gürültülü makbuzlarda doğruluğu artırmak için `ImagePreprocessing` ayarlarıyla da deneyler yapabilirsiniz. + +Sorularınız mı var ya da bir sorunla mı karşılaştınız? Yorum bırakın—iyi kodlamalar! + +![Görüntü üzerinde OCR örneği + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan yakından ilgili konuları kapsar. Her kaynak, ek API özelliklerini öğrenmenize ve kendi projelerinizde alternatif uygulama yaklaşımlarını keşfetmenize yardımcı olmak için adım adım açıklamalar içeren tam çalışan kod örnekleri sunar. + +- [Aspose.OCR 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 için metin görüntüsü tanıma](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Görüntüden Metin Çıkarma – .NET için Aspose.OCR ile OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/turkish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..c000f70fc --- /dev/null +++ b/ocr/turkish/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR kullanarak PDF üzerinde OCR gerçekleştirin ve taranmış PDF'yi + aranabilir PDF'ye dönüştürün. PDF'den metin tanımayı ve dakikalar içinde aranabilir + PDF'ler oluşturmayı öğrenin. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: tr +og_description: PDF üzerinde OCR gerçekleştir ve anında aranabilir bir PDF oluştur. + Bu eğitim, Aspose.OCR kullanarak PDF'den metin tanımanın adım adım nasıl yapılacağını + gösterir. +og_title: PDF'de OCR Yapın – Tam C# Rehberi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Aspose.OCR ile PDF'de OCR Yapın – Tam C# Rehberi +url: /tr/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Aspose.OCR ile PDF Üzerinde OCR Yapma – Tam C# Kılavuzu + +Hiç **PDF üzerinde OCR nasıl yapılır** diye merak ettiniz mi, komut satırı araçlarıyla uğraşmadan? Yalnız değilsiniz. İster faturaları dijitalleştiriyor, eski raporları arşivliyor, ister taranmış bir sözleşmenin aranabilir bir versiyonuna ihtiyacınız olsun, sabit bir PDF'i gerçekten arayabileceğiniz bir şeye dönüştürmek oyunu değiştiriyor. + +Bu kılavuzda, Aspose.OCR for .NET kullanarak taranmış PDF'lerden (ve hatta düz görüntülerden) **aranabilir PDF** dosyaları oluşturmayı adım adım göstereceğiz. Sonunda, birkaç satır C# kodu ile **PDF'den metin tanıma** yapabilecek ve her adımın nedenini anlayarak çözümü kendi projelerinize uyarlayabileceksiniz. + +> **Hızlı özet:** Tüm süreç üç adıma indirgenir—OCR motorunu başlatmak, kaynağı (PDF veya görüntü) beslemek ve aranabilir PDF çıktısını kaydetmek. Hadi başlayalım. + +--- + +## Gereksinimler + +Başlamadan önce şunların olduğundan emin olun: + +| Gereklilik | Neden Önemli | +|------------|--------------| +| **.NET 6.0+** (veya .NET Framework 4.6+) | Aspose.OCR modern çalışma zamanlarını hedefler; eski sürümler API güncellemelerini kaçırabilir. | +| **Aspose.OCR for .NET** NuGet paketi | `OcrEngine` sınıfını ve PDF işleme yardımcılarını sağlar. | +| **Geçerli bir Aspose lisansı** (veya ücretsiz deneme) | Lisans olmadan 30‑günlük deneme sınırı ve filigranlarla karşılaşırsınız. | +| **Aranabilir hâle getirmek istediğiniz taranmış PDF** (veya bir görüntü dosyası) | OCR için kaynak belge budur. | +| **Visual Studio 2022** (veya herhangi bir C# editörü) | Hata ayıklamayı kolaylaştırır, ancak herhangi bir IDE de çalışır. | + +Kütüphaneyi aşağıdaki NuGet komutuyla kurabilirsiniz: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro ipucu:** CI pipeline'ında çalışıyorsanız, lisans dosyasını derleme artefaktlerine ekleyin ve çalışma zamanında yükleyin; böylece yolları sabit kodlamaktan kaçınmış olursunuz. + +--- + +## PDF Üzerinde OCR Yapma – Aspose.OCR'ı Kurma + +İlk olarak yeni bir `OcrEngine` örneğine ihtiyacımız var. Bunu, belgenizi okuyacak beyin olarak düşünün. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Neden her seferinde yeni bir örnek? Motor, belge bazında değişebilen (dil ayarları gibi) yapılandırmaları tutar. Her çalıştırmada yeni bir örnek oluşturmak temiz bir başlangıç sağlar ve işler arasında karışıklığı önler. + +--- + +## Aranabilir PDF Oluşturma – Şifreleme Ayarları (İsteğe Bağlı) + +PDF'niz korumalıysa, motorun sayfaları okuyabilmesi için şifreyi belirtmeniz gerekir: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Korunan bir dosyada bu adımı atlamak `PdfPasswordException` hatasına yol açar. Koruma durumundan emin değilseniz her zaman try‑catch bloğu içinde yakalayın. + +--- + +## Taranmış PDF'yi Aranabilir PDF'ye Dönüştürme – Kaynağı Yükleme + +Aspose.OCR, PDF, TIFF, JPEG vb. dosyaları saran `OcrImage` soyutlamasını kullanır. İşte taranmış bir PDF'yi belleğe almanın yolu: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Arka planda, `FromFile` her sayfayı OCR motorunun işleyebileceği raster görüntülere dönüştürür. Çok sayfalı bir PDF'niz varsa, motor otomatik olarak tüm sayfalar üzerinde döner. + +--- + +## PDF'den Metin Tanıma – OCR'i Çalıştırma + +Şimdi öğreticinin özü: motoru metni tanıması ve aranabilir bir PDF üretmesi için yönlendirin. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` motorun, orijinal taranmış görüntülerin üzerine görünmez bir metin katmanı eklemesini söyler. Ortaya çıkan PDF, taramanın görsel bütünlüğünü korurken tamamen aranabilir hâle gelir—uygulama denetimlerinde tam ihtiyacınız olan şey. + +--- + +## Görüntüyü Aranabilir PDF'ye Dönüştürme – Sonucu Kaydetme + +Son olarak ikili veriyi diske yazın: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +`Binary` özelliği ham PDF baytlarını tutar. Bir API geliştiriyorsanız, bunları doğrudan bir web yanıtına da akıtabilirsiniz. + +--- + +![Diagram showing the OCR conversion flow to create searchable PDF](https://example.com/ocr-flow.png "Perform OCR on PDF flow diagram") +*Görsel alt metni: PDF üzerinde OCR akış diyagramı, taranmış bir PDF'nin aranabilir PDF'ye nasıl dönüştüğünü gösterir.* + +--- + +## Kenar Durumları ve Pratik İpuçları + +### 1. Büyük Dosyalar ve Bellek Yönetimi +100 MB'den büyük PDF'ler işliyorsanız, `OcrEngineSettings.MemoryLimit` ile bellek kullanımını sınırlamayı düşünün. Ayrıca `OutOfMemoryException` almamak için sayfaları partiler halinde işleyin. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Dil Desteği +Varsayılan olarak Aspose.OCR İngilizce kabul eder. Başka dilleri tanımak için `Language` özelliğini ayarlayın: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Çoklu İş Parçacıklı Senaryolar +`OcrEngine` **thread‑safe** değildir. Paralel işleme ihtiyacınız varsa, her iş parçacığı için ayrı bir motor oluşturun. + +### 4. OCR Doğruluğunu Hata Ayıklama +Hata ayıklama amacıyla `ocrResult`'tan düz metni çıkarabilirsiniz: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Çıktı bozuk görünüyorsa, kaliteyi artırmak için `PreprocessSettings` (ör. deskew, despeckle) ile deney yapın. + +### 5. Lisans Tuşları +Değerlendirme sürümünü çalıştırdığınızda Aspose çıktıya bir filigran ekler. Lisansı uygulamanın başında kaydedin: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Tam Çalışan Örnek – Baştan Sona + +Aşağıda, yukarıdaki tüm ipuçlarını içeren, çalıştırılmaya hazır tam program yer alıyor. Yeni bir console projesine kopyalayıp yapıştırabilirsiniz. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Beklenen çıktı:** Çalıştırdıktan sonra, dosya konumunu belirten bir konsol satırı göreceksiniz. `output.pdf` dosyasını herhangi bir PDF görüntüleyicide açın; orijinal taramada bulunan bir kelimeyi yazmayı deneyin. Metin vurgulanıyorsa, **PDF üzerinde OCR yaptınız** ve aranabilir bir belge oluşturdunuz demektir. + +--- + +## Sıkça Sorulan Sorular + +**S: Tek bir görüntüyü (PNG/JPEG) aranabilir PDF'ye dönüştürebilir miyim?** +C: Kesinlikle. `OcrImage.FromFile("input.pdf")` ifadesini görüntü dosyanızın yolu ile değiştirin. Motor aynı şekilde görüntüyü rasterleştirir ve OCR katmanını ekler. + +**S: PDF'im hem taranmış sayfalar hem de yerel metin içeriyorsa ne olur?** +C: Motor, mevcut içeriğin üzerine OCR metnini bindirir; yerel metin seçilebilir kalırken taranmış sayfalar aranabilir hâle gelir. + +**S: OCR ne kadar doğru?** +C: Doğruluk kaynak kalitesine bağlıdır. Temiz, yüksek çözünürlüklü taramalar (>300 dpi) %95'in üzerinde doğruluk sağlar. Gürültülü belgeler için `PreprocessSettings` (deskew, despeckle) etkinleştirerek kaliteyi artırın. + +--- + +## Sonraki Adımlar – OCR Araç Setinizi Genişletme + +Artık **PDF'den metin tanıma** ve **taranmış PDF'yi aranabilir PDF'ye dönüştürme** konularını başardığınıza göre, aşağıdaki konulara göz atabilirsiniz: + +- **Toplu işleme**: Bir klasördeki PDF'leri döngüyle işleyip otomatik olarak aranabilir sürümler oluşturun. +- **Metin çıkarma**: `ocrResult.Text`'i bir arama indeksi (ör. Elasticsearch) için kullanın. +- **Özel dil paketleri**: Aspose'tan ek dil verileri indirerek Asya scriptlerini destekleyin. +- **PDF/A uyumluluğu**: OCR çıktısını Aspose.PDF ile birleştirerek arşiv‑hazır PDF'ler üretin. + +Bu konular, temel adımlara dayanır; böylece çözümünüzü rahatça genişletebilirsiniz. + +--- + +## Özet + +Aspose.OCR kullanarak **PDF üzerinde OCR yapma**, taranmış PDF'leri tam anlamıyla aranabilir PDF'lere dönüştürme ve hatta düz görüntüleri aynı şekilde işleme konularını gösterdik. Kod + +## Bir Sonraki Öğrenmeniz Gerekenler + + +Aşağıdaki öğreticiler, bu kılavuzda gösterilen tekniklere dayanan ve ilgili konuları derinlemesine ele alan örnekler sunar. Her kaynak, adım adım açıklamalar ve tam çalışan kod örnekleri içerir; böylece API özelliklerini daha iyi kavrayabilir ve projelerinizde alternatif yaklaşımları keşfedebilirsiniz. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/turkish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9c925ca0d --- /dev/null +++ b/ocr/turkish/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,279 @@ +--- +category: general +date: 2026-06-03 +description: Aspose.OCR kullanarak MP4 gibi video dosyalarından kareler çıkarma ve + metin okuma işlemini gösteren video altyazı OCR öğreticisi. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: tr +og_description: Aspose.OCR ile video altyazı OCR'ını öğrenin. Videodan kareler çıkarın, + videodan metin okuyun ve birkaç dakika içinde MP4'ten metin çıkarın. +og_title: C# ile Video Altyazı OCR – Adım Adım Rehber +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: C#'ta Video Altyazı OCR – Tam Kılavuz +url: /tr/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# ile Video Altyazı OCR – Tam Kılavuz + +Hiç **video subtitle ocr**'a ihtiyaç duydunuz mu ama nereden başlayacağınızı bilemediniz mi? Yalnız değilsiniz. İster ders kayıtlarını dijitalleştiriyor, ister eğitim videolarından altyazı çekiyor, ister sadece videodan metin okumaya meraklı olun, bu öğretici size C# ve Aspose.OCR ile tam olarak nasıl yapılacağını gösteriyor. + +Önümüzdeki birkaç dakikada videodan kareler çıkaracağız, bu karelerde OCR çalıştıracağız ve sonunda altyazı metnini kare‑kare görüntüleyeceğiz. Sonunda **videodan metin okuma** yeteneğine sahip olacaksınız—MP4 dahil—ve üçüncü‑taraf araçlar aramak zorunda kalmayacaksınız. + +## Ne Oluşturacaksınız + +Küçük bir konsol uygulaması yapacağız ve bu uygulama: + +1. Bir MP4'ü (veya desteklenen herhangi bir formatı) tek tek `Bitmap` karelerine çözecek. +2. OCR bölgesini altyazı bandına sınırlayacak, böylece motor bütün resimle meşgul olmayacak. +3. Her kareyi Aspose'un `VideoOcrProcessor`'ı ile işleyecek. +4. Tanınan altyazı metnini konsola yazdıracak. + +Süsleme yok, sadece gerçek bir projeye ekleyebileceğiniz uçtan uca çalışan bir örnek. + +## Önkoşullar + +- **.NET 6.0** veya üzeri (kod .NET Framework 4.7+ üzerinde de çalışır). +- **Aspose.OCR for .NET** – NuGet üzerinden kurun: `Install-Package Aspose.OCR`. +- Bir video dosyası (MP4 harika çalışır). +- Video karelerini çözmek için bir yol – demo bir yer tutucu yöntem kullanıyor, ama `Bitmap` nesneleri döndüren herhangi bir kütüphane (FFmpeg, OpenCV vb.) ile değiştirebilirsiniz. + +> Pro ipucu: Windows'ta `System.Drawing.Common` paketi `Bitmap` için sorunsuz çalışır. Linux/macOS'ta ise yerel `libgdiplus` bağımlılığına ihtiyacınız olacak. + +## Adım 1 – Videodan Kareleri Çıkarma + +İlk engel, hareketli bir resmi sabit görüntülere dönüştürmek. Aşağıdaki `GetVideoFrames` yöntemi kasıtlı olarak boş bırakıldı; favori çözücünüzle değiştirin. İşte verinin şeklini göstermek için FFmpeg‑Core kullanan hızlı bir taslak: + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Neden önemli:** Kareleri çıkarmak OCR motoruna statik bir görüntü verir, bu da doğrudan video akışından okumaya göre doğruluğu büyük ölçüde artırır. + +## Adım 2 – VideoOcrProcessor'ı Ayarlama + +Artık bir `Bitmap` dizimiz olduğuna göre, bunları Aspose.OCR'a verebiliriz. `VideoOcrProcessor`, **İlgi Bölgesi (ROI)** tanımlamamıza izin verir – genellikle çerçevenin üst ya da alt kısmında bulunan altyazılar için mükemmeldir. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **ROI'yi sınırlamanın nedeni:** Resmin geri kalanını görmezden gelerek gürültüyü azaltır, işleme süresini kısaltır ve arka plan grafiklerinden kaynaklanan yanlış pozitifleri önler. + +## Adım 3 – Kare Dizisi Üzerinde OCR Çalıştırma + +İşlemci hazır olduğunda, kareleri beslemek tek satır kodla yapılır. `Process` metodu, her kareye karşılık gelen tanınan metni içeren `OcrResult` nesnelerinin bir enumerable'ını döndürür. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Arka planda neler oluyor?** Aspose.OCR, her bitmap'i normalleştirir, sinir‑ağ‑tabanlı bir tanıyıcı çalıştırır ve ardından noktalama ve satır sonlarını iyileştirmek için çıktıyı post‑process eder. + +## Adım 4 – Çıkarılan Metni Görüntüleme + +Son olarak sonuçlar üzerinde döngü kurup her altyazı satırını yazdırıyoruz. Ayrıca bunları bir SRT dosyasına, veritabanına kaydedebilir ya da bir çeviri servisine gönderebilirsiniz. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Tam Çalışan Örnek + +Her şeyi bir araya getirdiğimizde bağımsız bir konsol programı elde ederiz: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Beklenen çıktı (örnek)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Eğer OCR belirli bir karede zorlanırsa boş bir string göreceksiniz – bu, ROI'yi ayarlamanız ya da kare çıkarma oranını artırmanız gerektiğine işaret eder. + +## Yaygın Tuzaklar ve Çözümleri + +| Sorun | Neden Oluşur | Çözüm | +|-------|--------------|------| +| **Bozuk karakterler** | Düşük çözünürlüklü kareler veya yüksek sıkıştırma | Kareleri daha yüksek bitrate ile çıkarın, ya da OCR'dan önce bitmap'i upscale edin (`Bitmap.Clone(new Size(...), ...)`). | +| **Metin dönmüyor** | ROI aslında altyazı bandını kapsamıyor | Dikdörtgen koordinatlarını doğrulayın (ekran görüntüsü aracıyla ölçüm yapın). | +| **Performans darboğazı** | 30 fps'de her kareyi işlemek gereksiz | Çoğu altyazı akışı için 1‑2 fps'e down‑sample edin; yine de her altyazı değişimini yakalayabilirsiniz. | +| **FFmpeg bulunamadı** | `ffmpeg.exe` `PATH` içinde yok | `ProcessStartInfo.FileName` içinde tam yolu belirtin ya da FFmpeg'i global olarak kurun. | + +## Çözümü Genişletmek + +- **SRT'ye Dışa Aktarma** – zaman damgalarını OCR metniyle birleştirip SubRip dosyası yazın. +- **Çok‑dilli destek** – `ocrProcessor.Language = OcrLanguage.Spanish` (veya desteklenen başka bir dil) ayarlayın. +- **Gerçek‑zaman işleme** – diskten okumak yerine canlı akıştan kareleri doğrudan boru hattına yönlendirin. + +Tüm bu varyasyonlar hâlâ **videodan kare çıkarma**, **videodan metin okuma** ve **mp4'ten metin çıkarma** temel fikirleri etrafında döner. + +## Sonuç + +C# içinde tam bir **video subtitle ocr** iş akışını adım adım inceledik. Videodan kare çıkararak, OCR'ı altyazı bandına odaklayarak ve sonuçları yineleyerek MP4 gibi video dosyalarından güvenilir bir şekilde **metin okuyabilirsiniz**. Kod kopyala‑yapıştır için hazır ve modüler tasarımı sayesinde istediğiniz herhangi bir kare çözücüyü takas edebilirsiniz. + +Sonraki adımlar? Sonuçları bir SRT dosyasına dışa aktarın, farklı ROI boyutlarıyla deney yapın ya da altyazıları çok‑dilli altyazılar için bir çeviri API'sine besleyin. Temel metin çıkarma becerilerini kavradıktan sonra sınır yok. + +İyi kodlamalar, altyazılarınız her zaman kristal netliğinde olsun! + +## Sonraki Öğrenmeniz Gerekenler + +Aşağıdaki öğreticiler, bu rehberde gösterilen tekniklere dayanan ve yakından ilgili konuları kapsar. Her kaynak, adım adım açıklamalarla tam çalışan kod örnekleri içerir ve API özelliklerini daha iyi kavramanızı ve projelerinizde alternatif uygulama yaklaşımları keşfetmenizi sağlar. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/ocr-configuration/_index.md b/ocr/vietnamese/net/ocr-configuration/_index.md index b9a6ce6fa..761544d66 100644 --- a/ocr/vietnamese/net/ocr-configuration/_index.md +++ b/ocr/vietnamese/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Mở khóa sức mạnh của nhận dạng hình ảnh OCR trong .NET với Asp Mở khóa các khả năng OCR mạnh mẽ với Aspose.OCR cho .NET. Trích xuất văn bản từ hình ảnh một cách liền mạch. ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) Mở khóa tiềm năng của Aspose.OCR cho .NET. Thực hiện nhận dạng hình ảnh OCR với danh sách một cách dễ dàng. Tăng năng suất và việc trích xuất dữ liệu trong các ứng dụng của bạn. +### [Lấy phiên bản Aspose OCR trong C# – Hướng dẫn đầy đủ](./get-aspose-ocr-version-in-c-complete-guide/) +Hướng dẫn chi tiết cách lấy phiên bản hiện tại của Aspose.OCR trong dự án C#. ### Các trường hợp sử dụng phổ biến - **Extract text images** từ hóa đơn đã quét để tự động kế toán. @@ -102,4 +104,4 @@ A: Có, đối tượng `OcrResult` cung cấp các giá trị confidence mà b {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md b/ocr/vietnamese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md new file mode 100644 index 000000000..06499dcdc --- /dev/null +++ b/ocr/vietnamese/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-06-03 +description: Lấy phiên bản Aspose OCR trong C# bằng một đoạn mã đơn giản. Tìm hiểu + cách truy xuất phiên bản thư viện Aspose OCR bằng OcrEngine GetVersion. +draft: false +keywords: +- get aspose ocr version +- aspose ocr library +- ocrengine getversion +- c# ocr example +- retrieve aspose version +language: vi +og_description: Lấy nhanh phiên bản Aspose OCR trong C#. Hướng dẫn này chỉ ra cách + chính xác để truy xuất phiên bản thư viện Aspose OCR bằng OcrEngine GetVersion. +og_title: Tải Phiên bản Aspose OCR cho C# – Hướng dẫn đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + headline: Get Aspose OCR Version in C# – Complete Guide + type: TechArticle +- description: Get Aspose OCR version in C# with a simple snippet. Learn how to retrieve + the Aspose OCR library version using OcrEngine GetVersion. + name: Get Aspose OCR Version in C# – Complete Guide + steps: + - name: Why this matters + text: When you install the package, the assembly version on disk may differ from + the version reported by the library at runtime. Querying the version via code + ensures you’re reading the exact build that the CLR loaded, which is crucial + for debugging and for compliance audits. + - name: Expected output + text: 'When you run `dotnet run` inside the project folder, you should see something + similar to:' + - name: What if `GetVersion()` returns an empty string? + text: That usually signals a corrupted installation or a missing native dependency. + Re‑install the NuGet package and verify that the `Aspose.OCR.Native.dll` (or + the appropriate platform‑specific binary) sits alongside your executable. + - name: Does the method work on .NET Core 2.0? + text: Yes, **Aspose OCR** supports .NET Standard 2.0 and higher, so any .NET Core + version that implements that standard can call `OcrEngine.GetVersion()`. Just + make sure you reference the correct runtime identifiers (`win-x64`, `linux-x64`, + etc.) if you’re publishing a self‑contained app. + - name: Can I retrieve the version without a license file? + text: Absolutely. `GetVersion()` does **not** require a license; it simply reports + the library build number. However, if you attempt to perform OCR without a valid + license, you’ll get a runtime exception. That’s why the `try/catch` in our snippet + is valuable—it isolates the version check from the OCR exec + type: HowTo +tags: +- Aspose +- OCR +- C# +- .NET +title: Lấy phiên bản Aspose OCR trong C# – Hướng dẫn toàn diện +url: /vi/net/ocr-configuration/get-aspose-ocr-version-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Lấy Phiên Bản Aspose OCR trong C# – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi **cách lấy phiên bản Aspose OCR** từ dự án .NET của mình chưa? Có thể bạn đang gặp vấn đề không khớp phiên bản, hoặc chỉ muốn ghi lại bản dựng thư viện đang chạy trong môi trường production. Dù lý do gì, bạn đã đến đúng nơi. + +Trong tutorial này, chúng ta sẽ đi qua một chương trình C# nhỏ gọn, tự chứa, gọi `OcrEngine.GetVersion()` và in kết quả ra. Khi kết thúc, bạn sẽ biết không chỉ *cách* lấy phiên bản, mà còn *tại sao* việc kiểm tra phiên bản có thể giúp bạn tránh những rắc rối khi nâng cấp **thư viện Aspose OCR**. + +## Những Điều Bạn Sẽ Học + +- Thêm gói NuGet Aspose.OCR vào dự án C# +- Sử dụng phương thức `OcrEngine.GetVersion()` (điểm vào **ocrengine getversion**) +- Xử lý các ngoại lệ có thể xảy ra và xác minh đầu ra +- Mở rộng đoạn mã cho các kịch bản thực tế như ghi log hoặc bật/tắt tính năng có điều kiện + +Không yêu cầu kinh nghiệm trước về OCR—chỉ cần nắm cơ bản C# và Visual Studio (hoặc IDE yêu thích). Bắt đầu thôi. + +--- + +## Bước 1: Thiết Lập Dự Án và Kéo Thư Viện Aspose OCR Vào + +Trước khi bạn có thể gọi bất kỳ API nào liên quan tới OCR, cần phải tham chiếu **thư viện Aspose OCR** trong dự án. + +1. Mở terminal hoặc Package Manager Console trong Visual Studio. +2. Chạy lệnh sau để cài đặt phiên bản ổn định mới nhất: + +```bash +dotnet add package Aspose.OCR +``` + +> **Mẹo:** Nếu bạn đang nhắm tới .NET Framework thay vì .NET Core, hãy dùng NuGet Package Manager UI và chọn phiên bản phù hợp với runtime của bạn. Gói này bao gồm lớp `OcrEngine` mà chúng ta sẽ dùng sau. + +### Tại sao lại quan trọng + +Khi bạn cài đặt gói, phiên bản assembly trên đĩa có thể khác với phiên bản mà thư viện báo cáo tại thời gian chạy. Truy vấn phiên bản bằng code đảm bảo bạn đọc đúng bản dựng mà CLR đã tải, điều này rất quan trọng cho việc gỡ lỗi và kiểm tra tuân thủ. + +--- + +## Bước 2: Viết Mã Tối Thiểu Để **Lấy Phiên Bản Aspose OCR** + +Tạo một ứng dụng console mới (`dotnet new console -n OcrVersionDemo`) và thay thế `Program.cs` mặc định bằng đoạn sau: + +```csharp +using System; +using Aspose.OCR; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + try + { + // Step 2a: Retrieve the Aspose OCR library version. + // This is the core of the get aspose ocr version operation. + string version = OcrEngine.GetVersion(); // e.g., "24.5.7" + + // Step 2b: Display the version information to the console. + Console.WriteLine($"Aspose OCR version: {version}"); + } + catch (Exception ex) + { + // If something goes wrong (missing DLL, license issue, etc.) + Console.Error.WriteLine($"Failed to get Aspose OCR version: {ex.Message}"); + } + } + } +} +``` + +**Giải thích từng phần** + +- `using Aspose.OCR;` đưa namespace OCR vào phạm vi, cho phép gọi `OcrEngine`. +- `OcrEngine.GetVersion()` là phương thức tĩnh **ocrengine getversion** trả về một chuỗi như `"24.5.7"`. +- Đặt lời gọi trong khối `try/catch` bảo vệ bạn khỏi những bất ngờ thời gian chạy—có thể các binary gốc không được tìm thấy trên máy mục tiêu. +- Chuỗi nội suy `$"Aspose OCR version: {version}"` in ra một dòng rõ ràng, dễ đọc. + +### Kết quả mong đợi + +Khi bạn chạy `dotnet run` trong thư mục dự án, sẽ thấy thứ gì đó tương tự: + +``` +Aspose OCR version: 24.5.7 +``` + +Nếu thư viện không tải được, nhánh lỗi sẽ in ra một thông báo ngắn gọn, giúp bạn nhanh chóng xác định vấn đề. + +--- + +## Bước 3: Xác Minh Phiên Bản Trùng Khớp Với Gói NuGet Của Bạn + +Rất dễ để cho rằng phiên bản NuGet bạn cài đặt là phiên bản đang được dùng tại thời gian chạy, nhưng môi trường có thể gây ra ngoại lệ. Để kiểm tra lại: + +```csharp +// After retrieving the version, compare it to the package metadata. +var assembly = typeof(OcrEngine).Assembly; +var fileVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location).FileVersion; + +Console.WriteLine($"Assembly file version: {fileVersion}"); +``` + +Chạy đoạn mã phụ này sẽ in ra một giá trị như: + +``` +Assembly file version: 24.5.7.0 +``` + +Nếu hai giá trị khác nhau, có thể bạn đang tải một DLL cũ từ Global Assembly Cache (GAC) hoặc từ thư mục build trước. Trong trường hợp đó, hãy làm sạch solution (`dotnet clean`) và biên dịch lại. + +--- + +## Bước 4: Đưa Kiểm Tra Phiên Bản Vào Log Production + +Hầu hết các ứng dụng thực tế không chỉ in ra console; chúng ghi vào file log hoặc hệ thống telemetry. Dưới đây là một ví dụ nhanh dùng `Microsoft.Extensions.Logging`: + +```csharp +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +// Set up a minimal logger. +var serviceProvider = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + +var logger = serviceProvider.GetService>(); + +try +{ + string version = OcrEngine.GetVersion(); + logger.LogInformation("Aspose OCR version: {Version}", version); +} +catch (Exception ex) +{ + logger.LogError(ex, "Unable to retrieve Aspose OCR version"); +} +``` + +Bây giờ phiên bản sẽ xuất hiện trong log có cấu trúc, dễ dàng lọc theo `{Version}` sau này. Mô hình này đặc biệt hữu ích khi bạn có nhiều micro‑service mỗi service có thể kéo một DLL OCR khác nhau. + +--- + +## Các Câu Hỏi Thường Gặp & Trường Hợp Cạnh + +### Nếu `GetVersion()` trả về chuỗi rỗng thì sao? + +Điều này thường báo hiệu việc cài đặt bị hỏng hoặc thiếu dependency gốc. Hãy cài lại gói NuGet và chắc chắn rằng `Aspose.OCR.Native.dll` (hoặc binary nền tảng tương ứng) nằm cạnh file thực thi của bạn. + +### Phương thức có hoạt động trên .NET Core 2.0 không? + +Có, **Aspose OCR** hỗ trợ .NET Standard 2.0 trở lên, vì vậy bất kỳ phiên bản .NET Core nào thực thi chuẩn này đều có thể gọi `OcrEngine.GetVersion()`. Chỉ cần chắc chắn bạn tham chiếu đúng runtime identifiers (`win-x64`, `linux-x64`, …) nếu xuất bản dưới dạng self‑contained app. + +### Có thể lấy phiên bản mà không có file license không? + +Chắc chắn. `GetVersion()` **không** yêu cầu license; nó chỉ báo cáo số build của thư viện. Tuy nhiên, nếu bạn cố thực hiện OCR mà không có license hợp lệ, sẽ gặp ngoại lệ thời gian chạy. Đó là lý do tại sao `try/catch` trong đoạn mã của chúng ta có giá trị—nó tách việc kiểm tra phiên bản ra khỏi luồng thực thi OCR. + +--- + +## Ví Dụ Hoàn Chỉnh (Sẵn Sàng Sao Chép) + +Dưới đây là toàn bộ chương trình, có thể dán ngay vào một dự án console mới. Nó bao gồm khối logging tùy chọn, vì vậy bạn sẽ thấy cả output console và log có cấu trúc hoạt động đồng thời. + +```csharp +using System; +using Aspose.OCR; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.DependencyInjection; + +namespace OcrVersionDemo +{ + class Program + { + static void Main() + { + // Set up a simple console logger. + var services = new ServiceCollection() + .AddLogging(builder => builder.AddConsole()) + .BuildServiceProvider(); + + var logger = services.GetService>(); + + try + { + // Retrieve the Aspose OCR library version. + string version = OcrEngine.GetVersion(); // get aspose ocr version + + // Log and display the version. + logger.LogInformation("Aspose OCR version: {Version}", version); + Console.WriteLine($"Aspose OCR version: {version}"); + + // Extra verification – compare with assembly file version. + var assembly = typeof(OcrEngine).Assembly; + var fileVersion = System.Diagnostics.FileVersionInfo + .GetVersionInfo(assembly.Location).FileVersion; + logger.LogDebug("Assembly file version: {FileVersion}", fileVersion); + Console.WriteLine($"Assembly file version: {fileVersion}"); + } + catch (Exception ex) + { + logger.LogError(ex, "Failed to get Aspose OCR version"); + Console.Error.WriteLine($"Error: {ex.Message}"); + } + } + } +} +``` + +Chạy bằng `dotnet run` và bạn sẽ thấy hai dòng xác nhận phiên bản, cộng thêm một dòng debug nếu bật `LogLevel.Debug`. + +--- + +## Kết Luận + +Chúng ta đã bao quát mọi thứ cần thiết để **lấy phiên bản Aspose OCR** trong môi trường C#—từ việc cài đặt **thư viện Aspose OCR**, gọi phương thức **ocrengine getversion**, xử lý lỗi, đến việc nhúng kết quả vào log cấp production. Với kiến thức này, bạn có thể xác minh một cách đáng tin cậy bản dựng OCR mà ứng dụng đang sử dụng, tránh các lỗi liên quan tới phiên bản và đáp ứng yêu cầu tuân thủ mà không gặp khó khăn. + +Bước tiếp theo? Hãy kết hợp kiểm tra phiên bản này với một lời gọi OCR thực tế (`OcrEngine` → `RecognizeImage`) và ghi log cả phiên bản và kết quả nhận dạng. Bạn cũng có thể khám phá mẫu **retrieve aspose version** cho các sản phẩm Aspose khác (PDF, Slides, Cells) để đồng bộ toàn bộ suite. + +Chúc lập trình vui vẻ, và chúc các pipeline OCR của bạn luôn sắc nét! + +## Bạn Nên Học Gì Tiếp Theo? + + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ cùng giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Batch OCR Images with List in Aspose.OCR for .NET](/ocr/english/net/ocr-configuration/ocr-operation-with-list/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/ocr-optimization/_index.md b/ocr/vietnamese/net/ocr-optimization/_index.md index e65f42655..6e8ca5d36 100644 --- a/ocr/vietnamese/net/ocr-optimization/_index.md +++ b/ocr/vietnamese/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Khám phá Aspose.OCR for .NET. Tăng cường độ chính xác OCR với các Cải thiện độ chính xác OCR với Aspose.OCR for .NET. Sửa lỗi chính tả, tùy chỉnh từ điển và đạt được nhận dạng văn bản không lỗi một cách dễ dàng. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) Mở khóa tiềm năng của Aspose.OCR for .NET. Lưu dễ dàng kết quả OCR đa trang dưới dạng tài liệu với hướng dẫn chi tiết từng bước này. +### [Ví dụ Aspose OCR C# – Bật GPU, Đặt giới hạn bộ nhớ & Xử lý ảnh TIF](./aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/) +Hướng dẫn bật GPU, giới hạn bộ nhớ và xử lý ảnh TIF bằng Aspose OCR trong C# để tăng tốc độ và hiệu suất OCR. ## Câu hỏi thường gặp diff --git a/ocr/vietnamese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md b/ocr/vietnamese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md new file mode 100644 index 000000000..3fcd177c6 --- /dev/null +++ b/ocr/vietnamese/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/_index.md @@ -0,0 +1,284 @@ +--- +category: general +date: 2026-06-03 +description: Ví dụ Aspose OCR C# cho thấy cách đặt giới hạn bộ nhớ GPU, tải hình ảnh + để OCR và nhận dạng văn bản từ các tệp TIF với mã đầy đủ và các mẹo. +draft: false +keywords: +- aspose ocr c# example +- set gpu memory limit +- load image for ocr +- recognize text from tif +- gpu acceleration asp ocr +- high‑resolution OCR c# +- asp ocr cuda setup +language: vi +og_description: 'Tìm hiểu ví dụ đầy đủ Aspose OCR C#: bật GPU, đặt giới hạn bộ nhớ + GPU, tải ảnh để OCR và nhận dạng văn bản từ các tệp TIF. Bao gồm toàn bộ mã nguồn.' +og_title: Ví dụ Aspose OCR C# – Tăng tốc GPU, Giới hạn bộ nhớ & Xử lý TIF +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + headline: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + type: TechArticle +- description: Aspose OCR C# example showing how to set GPU memory limit, load image + for OCR and recognize text from TIF files with full code and tips. + name: Aspose OCR C# Example – Enable GPU, Set Memory Limit & Process TIF Images + steps: + - name: Why set a memory limit? + text: '- **Stability:** Prevents out‑of‑memory crashes when processing gigantic + images. - **Co‑existence:** Allows other GPU‑heavy apps (e.g., TensorFlow models) + to run side‑by‑side. - **Predictability:** Makes performance testing repeatable + because the GPU won’t start swapping.' + - name: Handling multi‑page TIFFs + text: If your TIFF contains several pages, Aspose OCR will only read the first + one by default. To process all pages, you can loop over `image.Pages` (available + in newer SDK versions) and feed each page to the engine separately. + - name: Why this works well with TIF + text: '- **Lossless compression:** TIFF often stores raw pixel data, giving the + OCR engine the highest fidelity. - **Multiple color spaces:** Aspose can handle + grayscale, RGB, or even CMYK TIFFs without extra conversion code.' + - name: Expected output + text: 'Running the program on a clear, 300 dpi scan of a printed page typically + yields something like:' + - name: Quick checklist + text: '- ✅ **Aspose OCR C# example** compiled without errors. - ✅ **GPU enabled** + (`Enable = true`). - ✅ **GPU memory limit** set to 2048 MB. - ✅ **Image loaded** + from a TIF file. - ✅ **Text recognized** and printed.' + type: HowTo +tags: +- Aspose +- OCR +- C# +- GPU +title: Ví dụ Aspose OCR C# – Bật GPU, Đặt giới hạn bộ nhớ & Xử lý ảnh TIF +url: /vi/net/ocr-optimization/aspose-ocr-c-example-enable-gpu-set-memory-limit-process-tif/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ví dụ Aspose OCR C# – Kích hoạt GPU, Đặt giới hạn bộ nhớ & Xử lý ảnh TIF + +Bạn có bao giờ tự hỏi làm thế nào để khai thác tối đa hiệu năng từ mã **Aspose OCR C# example** khi xử lý các bản quét TIFF khổng lồ không? Bạn không phải là người duy nhất. Trong nhiều dự án thực tế—như số hóa tài liệu lưu trữ hoặc trích xuất dữ liệu từ biên lai độ phân giải cao—điểm nghẽn không phải là thuật toán OCR mà là việc sử dụng phần cứng. + +Đây là vấn đề: Aspose OCR hỗ trợ tăng tốc bằng GPU, nhưng bạn phải chỉ định chính xác lượng bộ nhớ nó có thể sử dụng, tải đúng loại ảnh, và cuối cùng lấy văn bản đã nhận dạng từ một tệp .tif. Hướng dẫn này sẽ dẫn bạn qua từng bước, từ cài đặt SDK đến điều chỉnh cài đặt GPU, để bạn có thể chạy OCR với tốc độ cao mà không làm đầy RAM của GPU. + +Chúng tôi cũng sẽ đưa vào một vài kịch bản “nếu như” — như xử lý TIFF đa trang hoặc chuyển sang CPU khi không có GPU — để bạn có được một giải pháp vững chắc, không chỉ là một đoạn mã đơn lẻ. + +## Những gì bạn cần + +Trước khi bắt đầu, hãy chắc chắn rằng máy của bạn có những thứ sau: + +| Prerequisite | Why it matters | +|--------------|----------------| +| **.NET 6 SDK** (or later) | Aspose OCR nhắm tới .NET Standard 2.0+, vì vậy bất kỳ phiên bản .NET mới nào cũng hoạt động. | +| **Aspose.OCR NuGet package** (`Install-Package Aspose.OCR`) | Thư viện cốt lõi cung cấp `OcrEngine`, `GpuSettings`, v.v. | +| **CUDA 11+** (NVIDIA) **or ROCm 5+** (AMD) | Cần thiết cho tăng tốc GPU; SDK sẽ kiểm tra driver tương thích tại thời gian chạy. | +| A **GPU with at least 2 GB VRAM** (we’ll cap it at 2048 MB) | Nếu không đủ bộ nhớ, engine có thể tự động chuyển sang CPU mà không báo lỗi. | +| A **high‑resolution TIFF** image you want to process | Aspose OCR có thể đọc hầu hết các định dạng raster, nhưng TIF thường được dùng cho các bản quét. | +| Visual Studio 2022 (or any editor you like) | Để biên dịch và gỡ lỗi dự án C#. | + +Nếu thiếu bất kỳ mục nào trong số này, mã vẫn sẽ biên dịch, nhưng bạn sẽ không thấy được những cải thiện hiệu năng mà chúng ta mong muốn. + +## Bước 1: Tạo Engine ví dụ Aspose OCR C# + +Điều đầu tiên trong mọi **Aspose OCR C# example** là khởi tạo engine OCR. Hãy nghĩ `OcrEngine` như đạo diễn của một bộ phim — nó điều phối mọi thứ từ việc tải ảnh đến trích xuất văn bản. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Mẹo:** Nếu bạn dự định xử lý nhiều ảnh liên tiếp, hãy giữ một `OcrEngine` duy nhất hoạt động. Tạo lại nó cho mỗi ảnh sẽ tạo thêm overhead có thể làm thời gian OCR trở nên rất lâu. + +## Bước 2: Đặt giới hạn bộ nhớ GPU (và kích hoạt tăng tốc) + +Bây giờ là phần thường làm người dùng bối rối: **đặt giới hạn bộ nhớ GPU**. Mặc định Aspose OCR sẽ cố gắng sử dụng càng nhiều VRAM càng tốt, điều này trên một workstation chia sẻ có thể làm các ứng dụng khác bị thiếu tài nguyên. Đối tượng `GpuSettings` cho phép bạn giới hạn việc cấp phát. + +```csharp + // Step 2: Enable GPU acceleration (requires CUDA 11+ or ROCm 5+) + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, // Turn on the GPU path + DeviceId = 0, // First GPU in the system (change if you have multiple) + MemoryLimitMb = 2048 // Optional cap – 2 GB in this example + }; +``` + +### Tại sao cần đặt giới hạn bộ nhớ? + +- **Stability:** Ngăn ngừa các lỗi hết bộ nhớ khi xử lý ảnh khổng lồ. +- **Co‑existence:** Cho phép các ứng dụng nặng GPU khác (ví dụ, mô hình TensorFlow) chạy đồng thời. +- **Predictability:** Giúp việc kiểm tra hiệu năng có thể lặp lại vì GPU sẽ không bắt đầu swap. + +Nếu bạn bỏ qua `MemoryLimitMb`, Aspose sẽ cấp phát bất kỳ lượng bộ nhớ nào nó cho là cần thiết, điều này có thể ổn trên máy chủ inference chuyên dụng nhưng rủi ro trên laptop của nhà phát triển. + +## Bước 3: Tải ảnh cho OCR + +Tải đúng định dạng tệp là phần quan trọng tiếp theo. Phương thức `OcrImage.FromFile` tự động phát hiện loại ảnh, nhưng bạn vẫn nên kiểm tra xem tệp có tồn tại và đó là biến thể TIFF được hỗ trợ (ví dụ, nén LZW hoặc CCITT‑G4). + +```csharp + // Step 3: Load the high‑resolution image to be processed + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); +``` + +### Xử lý TIFF đa trang + +Nếu TIFF của bạn chứa nhiều trang, Aspose OCR sẽ chỉ đọc trang đầu tiên theo mặc định. Để xử lý tất cả các trang, bạn có thể lặp qua `image.Pages` (có trong các phiên bản SDK mới) và đưa mỗi trang vào engine riêng biệt. + +```csharp + foreach (var page in image.Pages) + { + var result = ocrEngine.Recognize(page); + System.Console.WriteLine($"--- Page {page.Index + 1} ---"); + System.Console.WriteLine(result.Text); + } + return; // Skip the single‑image path below +``` + +Đoạn mã trên minh họa mẫu **load image for OCR** hoạt động cho cả tệp đơn trang và đa trang. + +## Bước 4: Nhận dạng văn bản từ TIF (hoặc bất kỳ raster nào) + +Bây giờ ảnh đã nằm trong bộ nhớ, chúng ta yêu cầu Aspose thực hiện phép màu. Phương thức `Recognize` trả về một `OcrResult` chứa văn bản thuần, điểm tin cậy, và thậm chí thông tin bounding‑box nếu bạn cần. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +### Tại sao điều này hoạt động tốt với TIF + +- **Lossless compression:** TIFF thường lưu trữ dữ liệu pixel thô, cung cấp độ trung thực cao nhất cho engine OCR. +- **Multiple color spaces:** Aspose có thể xử lý TIFF ở chế độ xám, RGB, hoặc thậm chí CMYK mà không cần mã chuyển đổi thêm. + +Nếu bạn cần điều chỉnh gói ngôn ngữ (ví dụ, tiếng Pháp hoặc tiếng Nhật), hãy đặt `ocrEngine.Settings.Language = "fr"` trước khi gọi `Recognize`. + +## Bước 5: Hiển thị văn bản đã nhận dạng + +Cuối cùng, chúng ta xuất văn bản ra console. Trong một ứng dụng thực tế, bạn có thể ghi vào cơ sở dữ liệu, tệp JSON, hoặc đưa chuỗi này vào pipeline NLP tiếp theo. + +```csharp + // Step 5: Display the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Kết quả mong đợi + +Chạy chương trình trên một bản quét rõ ràng, 300 dpi của một trang in thường cho ra kết quả tương tự: + +``` +=== OCR Output === +Lorem ipsum dolor sit amet, consectetur adipiscing elit. +Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +... +``` + +Nếu ảnh mờ hoặc giới hạn bộ nhớ GPU quá thấp, bạn có thể thấy ký tự rối hoặc kết quả bị cắt ngắn. Hạ `MemoryLimitMb` xuống dưới kích thước ảnh (thường ~1 GB cho TIFF 6000×8000 pixel) có thể khiến engine tự động chuyển sang CPU. + +## Ví dụ hoàn chỉnh hoạt động + +Dưới đây là chương trình đầy đủ, sẵn sàng chạy. Sao chép‑dán vào một dự án Console App mới, thay thế `YOUR_DIRECTORY/large_photo.tif` bằng đường dẫn tới tệp TIFF của bạn, và nhấn **F5**. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class GpuDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Enable GPU acceleration and set a memory cap + ocrEngine.Settings.Gpu = new GpuSettings + { + Enable = true, + DeviceId = 0, + MemoryLimitMb = 2048 // 2 GB limit – adjust to your GPU size + }; + + // Step 3: Load the image (ensure the file exists) + var imagePath = "YOUR_DIRECTORY/large_photo.tif"; + + if (!System.IO.File.Exists(imagePath)) + { + System.Console.WriteLine($"Error: File not found -> {imagePath}"); + return; + } + + var image = OcrImage.FromFile(imagePath); + + // Step 4: Perform OCR on the loaded image + var ocrResult = ocrEngine.Recognize(image); + + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Output ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +### Danh sách kiểm tra nhanh + +- ✅ **Aspose OCR C# example** biên dịch không lỗi. +- ✅ **GPU enabled** (`Enable = true`). +- ✅ **GPU memory limit** được đặt thành 2048 MB. +- ✅ **Image loaded** từ tệp TIF. +- ✅ **Text recognized** và được in ra. + +## Những cạm bẫy thường gặp & Cách tránh + +| Symptom | Likely cause | Fix | +|---------|--------------|-----| +| `System.DllNotFoundException: cudart64_110.dll` | Runtime CUDA chưa được cài đặt hoặc phiên bản không khớp. | Cài đặt CUDA 11.x (hoặc 12.x) phù hợp với driver của bạn. | +| OCR returns empty string | Ảnh quá tối hoặc DPI < 150. | Tiền xử lý bằng `image.AdjustContrast()` hoặc thay đổi độ phân giải lại thành 300 dpi. | +| Out‑of‑memory crash on GPU | `MemoryLimitMb` quá thấp so với kích thước ảnh. | Tăng giới hạn hoặc chia ảnh thành các ô bằng `image.Crop`. | +| `Unsupported image format` error | TIFF sử dụng nén đặc biệt (ví dụ, JPEG‑2000). | Chuyển đổi TIFF sang định dạng được hỗ trợ bằng ImageMagick trước khi OCR. | + +## Mở rộng demo + +Bây giờ bạn đã có một **aspose ocr c# example** vững chắc, bạn có thể muốn khám phá: + +- **Batch processing:** Lặp qua một thư mục chứa các tệp TIF, ghi mỗi kết quả vào tệp `.txt`. +- **Language packs:** `ocrEngine.Settings.Language = "es"` cho tiếng Tây Ban Nha, hoặc tải các từ điển tùy chỉnh. +- **Bounding boxes:** Sử dụng `ocrResult.Regions` để lấy tọa độ của mỗi từ — hữu ích cho các công cụ che dấu. +- **CPU fallback:** Bao bọc khối GPU trong try/catch; nếu thất bại, đặt `ocrEngine.Settings.Gpu.Enable = false` và thử lại. + +Những mở rộng này giữ nguyên mẫu cốt lõi trong khi bổ sung giá trị cho các trường hợp sử dụng cụ thể. + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên đều có các ví dụ mã hoàn chỉnh cùng giải thích từng bước để giúp bạn nắm vững các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/net/skew-angle-calculation/_index.md b/ocr/vietnamese/net/skew-angle-calculation/_index.md index cd2f340e5..fdd72f650 100644 --- a/ocr/vietnamese/net/skew-angle-calculation/_index.md +++ b/ocr/vietnamese/net/skew-angle-calculation/_index.md @@ -40,9 +40,12 @@ Khám phá Aspose.OCR cho .NET, một giải pháp OCR mạnh mẽ để nhận Giải phóng sức mạnh của Aspose.OCR cho .NET, một giải pháp mạnh mẽ để nhận dạng hình ảnh. Tìm hiểu cách tính góc nghiêng một cách dễ dàng. ### [Tính toán góc nghiêng từ URI trong nhận dạng hình ảnh OCR](./calculate-skew-angle-from-uri/) Khám phá Aspose.OCR cho .NET để dễ dàng tính toán các góc nghiêng trong nhận dạng hình ảnh OCR. Nâng cao dự án của bạn với độ chính xác và hiệu quả. +### [Hướng dẫn tài liệu OCR đã xoay – Tự động chỉnh góc nghiêng & sửa xoay trong C#](./ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/) +Khám phá cách tự động chỉnh góc nghiêng và sửa xoay tài liệu OCR trong C# bằng Aspose.OCR cho .NET. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md b/ocr/vietnamese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md new file mode 100644 index 000000000..1ecdb825b --- /dev/null +++ b/ocr/vietnamese/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-06-03 +description: Hướng dẫn OCR tài liệu đã xoay, trình bày cách tự động chỉnh sửa độ nghiêng + và phát hiện góc quay bằng Aspose OCR trong C#. Học từng bước với mã nguồn đầy đủ. +draft: false +keywords: +- ocr rotated document tutorial +- Aspose OCR +- automatic skew correction +- auto detect rotation +- C# image processing +language: vi +og_description: Hướng dẫn OCR tài liệu bị xoay dạy bạn cách tự động chỉnh sửa độ lệch + và phát hiện góc quay bằng Aspose OCR trong C#. Hãy theo dõi hướng dẫn đầy đủ. +og_title: Hướng dẫn OCR tài liệu xoay – Tự động chỉnh nghiêng & sửa xoay trong C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: OCR rotated document tutorial that shows how to auto-correct skew and + detect rotation using Aspose OCR in C#. Learn step‑by‑step with full code. + headline: OCR Rotated Document Tutorial – Auto Skew & Rotation Fix in C# + type: TechArticle +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Hướng dẫn OCR tài liệu xoay – Tự động chỉnh nghiêng & sửa xoay trong C# +url: /vi/net/skew-angle-calculation/ocr-rotated-document-tutorial-auto-skew-rotation-fix-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hướng Dẫn Tài Liệu OCR Xoay – Hướng Dẫn Đầy Đủ cho Các Nhà Phát Triển C# + +Bạn đã bao giờ gặp phải một **ocr rotated document tutorial** khi một mẫu quét xuất hiện nghiêng hoặc lệch không? Bạn không phải là người duy nhất. Những hình ảnh lệch lạc đó có thể phá hỏng việc trích xuất văn bản sạch sẽ, nhưng tin tốt là Aspose OCR có thể tự động chỉnh thẳng chúng cho bạn. + +Trong hướng dẫn từng bước này, chúng ta sẽ khởi tạo một `OcrEngine`, bật **automatic skew correction** và **auto detect rotation**, chạy engine trên một hình ảnh đã xoay, và in ra văn bản sạch. Khi kết thúc, bạn sẽ hiểu chính xác tại sao mỗi cài đặt quan trọng, cách điều chỉnh chúng cho các trường hợp đặc biệt, và sẽ có một chương trình C# sẵn sàng chạy. + +## Những Điều Bạn Sẽ Học + +* Cách cài đặt và tham chiếu **Aspose OCR** trong dự án .NET. +* Tại sao việc bật `AutoCorrectSkew` và `AutoDetectRotation` là chìa khóa cho một **ocr rotated document tutorial** đáng tin cậy. +* Cách tải bất kỳ hình ảnh nào (JPG, PNG, TIFF) và để engine thực hiện công việc nặng. +* Mẹo xử lý PDF đa trang, quét độ phân giải thấp, và các gói ngôn ngữ tùy chỉnh. + +> **Prerequisites:** Visual Studio 2022 (hoặc bất kỳ IDE C# nào), môi trường .NET 6+ runtime, và giấy phép Aspose OCR hợp lệ (hoặc bản dùng thử miễn phí). Không yêu cầu kinh nghiệm OCR trước. + +--- + +## Bước 1 – Cài Đặt Aspose OCR và Thiết Lập Dự Án + +First things first. Grab the NuGet package: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Nếu bạn đang sử dụng giấy phép dùng thử, đặt tệp `Aspose.OCR.lic` trong cùng thư mục với tệp thực thi của bạn, hoặc đăng ký nó bằng mã: `License license = new License(); license.SetLicense("Aspose.OCR.lic");`. + +Create a new console app: + +```bash +dotnet new console -n OcrRotatedDemo +cd OcrRotatedDemo +``` + +Bây giờ bạn đã có một môi trường trống sạch cho **ocr rotated document tutorial** của chúng ta. + +## Bước 2 – Khởi Tạo Engine OCR + +The engine là trái tim của quá trình. Hãy nghĩ nó như một con dao đa năng cho việc trích xuất văn bản; bạn chỉ cần cho nó biết những tính năng nào cần bật. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class SkewDemo +{ + static void Main() + { + // Step 2.1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2.2: Enable automatic skew correction + ocrEngine.Settings.AutoCorrectSkew = true; // <-- fixes slanted lines + + // Step 2.3: Enable automatic rotation detection + ocrEngine.Settings.AutoDetectRotation = true; // <-- turns the page upright +``` + +**Tại sao lại dùng những cài đặt này?** +* `AutoCorrectSkew` phân tích đường cơ sở của các ký tự và xoay hình ảnh vừa đủ để các dòng trở nên ngang. +* `AutoDetectRotation` kiểm tra hướng tổng thể (0°, 90°, 180°, 270°) và lật trang nếu nó ngược lên. Nếu không có chúng, engine sẽ đọc “pɹᴉʍ” thay vì “word`. + +## Bước 3 – Tải Hình Ảnh Bạn Muốn Xử Lý + +Aspose OCR hỗ trợ bất kỳ định dạng raster phổ biến nào. Thay thế đường dẫn placeholder bằng vị trí thực tế của mẫu đã xoay của bạn. + +```csharp + // Step 3: Load the image that may be rotated or skewed + var imagePath = @"C:\Scans\rotated_form.jpg"; // adjust as needed + var image = OcrImage.FromFile(imagePath); +``` + +> **Edge case:** Nếu bạn nhận được một tệp TIFF đa trang, hãy sử dụng `OcrImage.FromMultiPageTiff(filePath)` và lặp qua `image.Pages`. + +## Bước 4 – Chạy Nhận Diện + +Bây giờ engine thực hiện phép màu. Nó sẽ đầu tiên chỉnh thẳng hình ảnh (nhờ các cờ skew/rotation) và sau đó trích xuất các ký tự. + +```csharp + // Step 4: Perform OCR recognition on the image + var ocrResult = ocrEngine.Recognize(image); +``` + +Nếu bạn cần hỗ trợ ngôn ngữ ngoài tiếng Anh, hãy đặt nó trước khi gọi `Recognize`: + +```csharp + ocrEngine.Settings.Language = Language.Spanish; // example +``` + +## Bước 5 – Xuất Văn Bản Đã Nhận Diện + +Cuối cùng, ghi văn bản sạch ra console—hoặc chuyển nó tới tệp, cơ sở dữ liệu, bất cứ gì phù hợp với quy trình của bạn. + +```csharp + // Step 5: Output the recognized text + System.Console.WriteLine("=== OCR Result ==="); + System.Console.WriteLine(ocrResult.Text); + } +} +``` + +**Kết quả mong đợi** (giả sử hình mẫu chứa “Invoice #1234”): + +``` +=== OCR Result === +Invoice #1234 +Date: 2026-05-30 +Total: $1,250.00 +``` + +Lưu ý cách văn bản hiển thị đúng mặc dù hình nguồn đã bị xoay 90° và hơi lệch. + +--- + +## Xử Lý Các Rủi Ro Thường Gặp + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|------|----------------|-----| +| **Blank output** | Chỉnh sửa lệch bị tắt hoặc hình ảnh quá tối. | Bật `AutoCorrectSkew` (đã bật) và tăng độ tương phản hình ảnh bằng `image.AdjustContrast(1.2)`. | +| **Garbage characters** | Cài đặt ngôn ngữ sai. | Đặt `ocrEngine.Settings.Language` phù hợp với ngôn ngữ của tài liệu. | +| **Performance lag on large PDFs** | Engine xử lý từng trang một cách tuần tự. | Sử dụng `Parallel.ForEach` trên `image.Pages` để tận dụng CPU đa nhân. | +| **License exception** | Bản dùng thử đã hết hạn. | Mua giấy phép vĩnh viễn hoặc tuân thủ giới hạn dùng thử (5 trang mỗi lần chạy). | + +## Mẹo Chuyên Nghiệp cho Hướng Dẫn OCR Tài Liệu Xoay Ổn Định + +* **Batch processing:** Đóng gói toàn bộ quy trình trong một phương thức nhận đường dẫn thư mục, lặp qua mọi hình ảnh, và ghi mỗi kết quả vào tệp `.txt`. +* **Pre‑processing:** Đôi khi một bản quét nhiễu sẽ được cải thiện bằng `image.Denoise()` trước khi nhận dạng. +* **Post‑processing:** Sử dụng biểu thức chính quy để làm sạch các lỗi OCR thường gặp, ví dụ, thay thế “0” bằng “O” chỉ khi nó được bao quanh bởi các ký tự. +* **Logging:** Aspose OCR cung cấp `ocrEngine.Logger` – kết nối nó với một logger file để ghi lại các cảnh báo về điểm tin cậy thấp. + +## Mã Hoàn Chỉnh, Sẵn Sàng Chạy + +Lưu đoạn sau dưới dạng `Program.cs` trong dự án console của bạn. Nó bao gồm tất cả các bước, chú thích, và một helper nhỏ cho việc xử lý batch. + +```csharp +using System; +using System.IO; +using Aspose.OCR; +using Aspose.OCR.Settings; + +namespace OcrRotatedDemo +{ + class Program + { + static void Main() + { + // OPTIONAL: Register your license here + // var license = new License(); + // license.SetLicense("Aspose.OCR.lic"); + + // Path to a single image – change as needed + string imagePath = @"C:\Scans\rotated_form.jpg"; + + // Run OCR on one file + string result = ProcessImage(imagePath); + Console.WriteLine("=== OCR Result for Single File ==="); + Console.WriteLine(result); + + // OPTIONAL: Process an entire folder + // string folder = @"C:\Scans\Batch"; + // ProcessFolder(folder); + } + + /// + /// Recognizes text from a possibly rotated or skewed image. + /// + static string ProcessImage(string filePath) + { + var engine = new OcrEngine(); + + // Enable automatic corrections – core of our OCR rotated document tutorial + engine.Settings.AutoCorrectSkew = true; + engine.Settings.AutoDetectRotation = true; + + // If you know the language, set it here (default is English) + // engine.Settings.Language = Language.French; + + var image = OcrImage.FromFile(filePath); + var result = engine.Recognize(image); + return result.Text; + } + + /// + /// Processes every image in a folder and writes a .txt per file. + /// + static void ProcessFolder(string folderPath) + { + foreach (var file in Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)) + { + if (!file.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".png", StringComparison.OrdinalIgnoreCase) && + !file.EndsWith(".tif", StringComparison.OrdinalIgnoreCase)) + continue; // skip unsupported files + + string text = ProcessImage(file); + string outPath = Path.ChangeExtension(file, ".txt"); + File.WriteAllText(outPath, text); + Console.WriteLine($"Processed {Path.GetFileName(file)} → {Path.GetFileName(outPath)}"); + } + } + } +} +``` + +Chạy nó: + +```bash +dotnet run +``` + +Bạn sẽ thấy văn bản đã được làm sạch được in ra console, chứng minh rằng **ocr rotated document tutorial** của chúng ta hoạt động từ đầu đến cuối. + +## Kết Luận + +Bây giờ bạn đã có một **ocr rotated document tutorial** hoàn chỉnh, tự động chỉnh sửa lệch, phát hiện xoay, và trích xuất văn bản sạch bằng Aspose OCR trong C#. Điều quan trọng? Bật `AutoCorrectSkew` **và** `AutoDetectRotation` biến một bản quét nghiêng tệ hại thành đầu ra hoàn toàn đọc được chỉ với vài dòng mã. + +Từ đây, bạn có thể mở rộng thành các công việc batch, tích hợp các gói ngôn ngữ, hoặc đưa kết quả vào các pipeline phân tích dữ liệu. Muốn khám phá thêm về **automatic skew correction**? Hãy xem API tiền xử lý ảnh của Aspose, hoặc thử nghiệm các ngưỡng tùy chỉnh cho các bản quét nhiễu. + +Có câu hỏi về xử lý PDF, TIFF đa trang, hoặc tích hợp với Azure Functions? Hãy để lại bình luận, và chúc bạn lập trình vui vẻ! + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên đều có các ví dụ mã hoàn chỉnh kèm giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [chế độ tài liệu OCR – Chế độ Phát hiện Vùng trong Nhận dạng Ảnh OCR](/ocr/english/net/text-recognition/ocr-detect-areas-mode/) +- [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/) +- [Hướng Dẫn Aspose OCR – Nhận dạng ký tự quang học](/ocr/english/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/_index.md b/ocr/vietnamese/net/text-recognition/_index.md index 205befdea..b34572aca 100644 --- a/ocr/vietnamese/net/text-recognition/_index.md +++ b/ocr/vietnamese/net/text-recognition/_index.md @@ -53,11 +53,22 @@ Giải phóng sức mạnh của Aspose.OCR cho .NET. Tìm hiểu cách thu đư Nâng cao các ứng dụng .NET của bạn với Aspose.OCR để nhận dạng văn bản hình ảnh hiệu quả. Khám phá Chế độ khu vực phát hiện OCR để có kết quả chính xác. ### [Nhận dạng PDF trong Nhận dạng hình ảnh OCR](./recognize-pdf/) Khai phá tiềm năng của OCR trong .NET với Aspose.OCR. Trích xuất văn bản từ tệp PDF một cách dễ dàng. Tải xuống ngay để có trải nghiệm tích hợp liền mạch. +### [Thực hiện OCR trên PDF với Aspose.OCR – Hướng dẫn C# đầy đủ](./perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/) +Hướng dẫn chi tiết cách sử dụng Aspose.OCR trong .NET để thực hiện OCR trên tệp PDF bằng C# một cách hiệu quả. ### [Nhận dạng bảng trong nhận dạng hình ảnh OCR](./recognize-table/) Khai phá tiềm năng của Aspose.OCR cho .NET với hướng dẫn toàn diện của chúng tôi về nhận dạng bảng trong nhận dạng hình ảnh OCR. +### [Thực hiện OCR trên hình ảnh với Aspose OCR – Hướng dẫn tiếng Hindi](./perform-ocr-on-image-with-aspose-ocr-hindi-guide/) +Khám phá cách sử dụng Aspose OCR để nhận dạng văn bản trên hình ảnh cho ngôn ngữ Hindi trong hướng dẫn chi tiết này. +### [Thực hiện OCR trên hình ảnh và phát hiện từ sai chính tả trong C#](./perform-ocr-on-image-and-detect-misspelled-words-in-c/) +Hướng dẫn chi tiết cách sử dụng Aspose.OCR trong C# để thực hiện OCR trên hình ảnh và phát hiện các từ sai chính tả. +### [Cách sử dụng Aspose: Chuyển đổi hình ảnh sang HTML với OCR](./how-to-use-aspose-convert-image-to-html-with-ocr/) +Hướng dẫn chi tiết cách chuyển đổi hình ảnh thành HTML bằng Aspose OCR, giúp bạn nhúng nội dung văn bản đã nhận dạng vào trang web. +### [OCR phụ đề video trong C# – Hướng dẫn đầy đủ](./video-subtitle-ocr-in-c-complete-guide/) +Khám phá cách sử dụng Aspose.OCR trong .NET để nhận dạng phụ đề video bằng C# một cách chi tiết và hiệu quả. + {{< /blocks/products/pf/tutorial-page-section >}} {{< /blocks/products/pf/main-container >}} {{< /blocks/products/pf/main-wrap-class >}} -{{< blocks/products/products-backtop-button >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md b/ocr/vietnamese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md new file mode 100644 index 000000000..61b973a01 --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/_index.md @@ -0,0 +1,280 @@ +--- +category: general +date: 2026-06-03 +description: Cách sử dụng Aspose để chuyển đổi hình ảnh sang HTML và trích xuất văn + bản từ hình ảnh trong C#. Học cách tạo HTML từ hình ảnh và OCR hình ảnh sang HTML + nhanh chóng. +draft: false +keywords: +- how to use aspose +- convert image to html +- extract text from image +- generate html from image +- ocr image to html +language: vi +og_description: Cách sử dụng Aspose để chuyển đổi hình ảnh sang HTML, trích xuất văn + bản từ hình ảnh và tạo HTML từ hình ảnh bằng OCR trong C#. Theo dõi hướng dẫn đầy + đủ này. +og_title: 'Cách sử dụng Aspose: Chuyển đổi hình ảnh sang HTML với OCR' +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + headline: 'How to Use Aspose: Convert Image to HTML with OCR' + type: TechArticle +- description: How to use Aspose to convert image to HTML and extract text from image + in C#. Learn to generate HTML from image and ocr image to html quickly. + name: 'How to Use Aspose: Convert Image to HTML with OCR' + steps: + - name: Expected Output + text: 'When you open `magazine.html` in a browser, you should see something akin + to this (simplified for illustration):' + - name: What if the image is low‑resolution? + text: Aspose.OCR works best with images that have at least **300 DPI**. If your + file is blurry, try preprocessing it with an image‑enhancement library (e.g., + ImageSharp) before feeding it to the OCR engine. Low quality can affect both + the **extract text from image** accuracy and the fidelity of the genera + - name: Can I control the language of the OCR? + text: 'Yes. Set the `Language` property on the `OcrEngine` before calling `Recognize`:' + - name: How do I get plain text instead of HTML? + text: If you only need the raw string, replace `OutputFormat.HtmlWithLayout` with + `OutputFormat.Text`. The same `recognitionResult.Text` will then contain just + the extracted characters. + - name: Is there a way to embed images into the generated HTML? + text: Aspose.OCR can embed the original image as a base‑64 data URI when you use + `OutputFormat.HtmlWithLayoutAndImages`. This is handy when you want a single + HTML file without external assets. + - name: What about handling large batches? + text: For batch processing, wrap the logic in a `foreach` loop over a list of + file paths. Re‑using the same `OcrEngine` instance reduces overhead and speeds + up the **convert image to html** pipeline. + type: HowTo +tags: +- Aspose +- OCR +- C# +- ImageProcessing +title: 'Cách sử dụng Aspose: Chuyển đổi hình ảnh sang HTML với OCR' +url: /vi/net/text-recognition/how-to-use-aspose-convert-image-to-html-with-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách Sử Dụng Aspose: Chuyển Đổi Hình Ảnh Sang HTML với OCR + +Bạn đã bao giờ tự hỏi **cách sử dụng Aspose** để chuyển một bức ảnh đã quét thành HTML gọn gàng chưa? Có thể bạn có một trang tạp chí, một biên lai, hoặc một ghi chú viết tay và bạn cần giữ nguyên văn bản và bố cục để xuất bản trên web. Tin tốt là bạn không cần viết một trình phân tích tùy chỉnh hay đấu tranh với xử lý ảnh mức thấp—Aspose.OCR sẽ thực hiện phần việc nặng cho bạn. + +Trong hướng dẫn này, chúng ta sẽ đi qua một **ví dụ đầy đủ, có thể chạy được** cho thấy cách **convert image to HTML**, **extract text from image**, và **generate HTML from image** bằng thư viện Aspose OCR trong C#. Khi kết thúc, bạn sẽ có một ứng dụng console nhỏ tạo ra một tệp HTML với bố cục trang gốc nguyên vẹn, sẵn sàng nhúng vào bất kỳ website nào. + +## Yêu cầu trước + +Trước khi bắt đầu, hãy chắc chắn rằng máy của bạn đã có: + +- **.NET 6.0 SDK** hoặc mới hơn (mã chạy được trên .NET Core và .NET Framework). +- **Visual Studio 2022** (hoặc bất kỳ trình soạn thảo nào bạn thích). +- **Aspose.OCR for .NET** – cài đặt qua NuGet: `dotnet add package Aspose.OCR`. +- Một tệp hình ảnh (JPEG/PNG) bạn muốn chuyển đổi, ví dụ `magazine_page.jpg`. + +Không cần tệp cấu hình bổ sung; thư viện đã bao gồm mọi thứ cần thiết cho OCR và tạo bố cục HTML. + +## Bước 1: Thiết Lập Dự Án và Thêm Aspose.OCR + +Đầu tiên, tạo một dự án console mới và thêm gói Aspose OCR. + +```bash +dotnet new console -n AsposeHtmlDemo +cd AsposeHtmlDemo +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Nếu bạn đang dùng Visual Studio, chỉ cần chuột phải vào dự án → *Manage NuGet Packages* → tìm **Aspose.OCR** và cài đặt. Bước này đảm bảo bạn có thể **ocr image to html** mà không gặp thiếu tham chiếu. + +## Bước 2: Khởi Tạo Engine OCR + +Lõi của quy trình là lớp `OcrEngine`. Hãy nghĩ nó như bộ não đọc hình ảnh và quyết định cách xuất kết quả. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +Ở đây chúng ta khởi tạo `OcrEngine`. Bạn không cần cung cấp bất kỳ thông tin xác thực nào cho phiên bản miễn phí; thư viện sẽ sử dụng các mô hình nhận dạng tích hợp sẵn. + +## Bước 3: Tải Ảnh Nguồn + +Tiếp theo, chỉ định engine tới tệp bạn muốn xử lý. Aspose cung cấp phương thức tiện lợi `OcrImage.FromFile` hỗ trợ hầu hết các định dạng ảnh. + +```csharp + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); +``` + +Thay thế `YOUR_DIRECTORY` bằng đường dẫn tuyệt đối hoặc tương đối nơi ảnh của bạn nằm. Nếu ảnh ở cùng thư mục với tệp thực thi, bạn chỉ cần dùng `"magazine_page.jpg"`. + +## Bước 4: Nhận Dạng và Yêu Cầu HTML Với Bố Cục + +Đây là phần cốt lõi của hướng dẫn. Bằng cách truyền `OutputFormat.HtmlWithLayout` chúng ta yêu cầu Aspose **generate HTML from image** đồng thời giữ nguyên vị trí của các khối văn bản, hình ảnh và bảng. + +```csharp + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); +``` + +Thuộc tính `recognitionResult.Text` hiện chứa một tài liệu HTML đầy đủ. Nếu bạn chỉ cần văn bản thuần, có thể dùng `OutputFormat.Text`, nhưng ở đây chúng ta tập trung vào **convert image to html** với độ chính xác bố cục. + +## Bước 5: Lưu Tệp HTML + +Cuối cùng, ghi chuỗi HTML ra đĩa. Điều này tạo ra một tệp sẵn sàng sử dụng mà bạn có thể mở trong bất kỳ trình duyệt nào. + +```csharp + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +Chạy chương trình sẽ tạo ra `magazine.html`. Mở nó, bạn sẽ thấy văn bản của trang gốc được đặt chính xác như trong ảnh nguồn—hoàn hảo cho việc lưu trữ hoặc xuất bản web. + +## Ví Dụ Hoàn Chỉnh + +Dưới đây là chương trình **complete, copy‑paste‑ready**. Không có phần nào bị bỏ qua, vì vậy bạn có thể biên dịch và chạy ngay sau khi đặt đúng đường dẫn. + +```csharp +using Aspose.OCR; +using System.IO; + +class HtmlLayoutDemo +{ + static void Main() + { + // Step 1: Create an OCR engine instance + var ocrEngine = new OcrEngine(); + + // Step 2: Load the source image to be processed + var sourceImage = OcrImage.FromFile(@"YOUR_DIRECTORY/magazine_page.jpg"); + + // Step 3: Recognize the image and request HTML output that preserves the original layout + var recognitionResult = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayout); + + // Step 4: Save the generated HTML to a file + File.WriteAllText(@"YOUR_DIRECTORY/magazine.html", recognitionResult.Text); + + // Optional: Inform the user that the operation completed + System.Console.WriteLine("HTML with layout saved."); + } +} +``` + +### Kết Quả Dự Kiến + +Khi mở `magazine.html` trong trình duyệt, bạn sẽ thấy một cái gì đó tương tự (đơn giản hoá để minh hoạ): + +```html + + + + + OCR Result + + + +
The headline of the article
+
Body paragraph starts here...
+ + + +``` + +Các thuộc tính `style` cụ thể sẽ khác nhau tùy vào ảnh gốc, nhưng cấu trúc đảm bảo **extract text from image** và **generate html from image** diễn ra trong một bước liền mạch. + +## Câu Hỏi Thường Gặp & Trường Hợp Cạnh + +### Ảnh có độ phân giải thấp thì sao? + +Aspose.OCR hoạt động tốt nhất với ảnh có ít nhất **300 DPI**. Nếu tệp của bạn mờ, hãy thử tiền xử lý bằng một thư viện tăng cường ảnh (ví dụ ImageSharp) trước khi đưa vào engine OCR. Chất lượng thấp có thể ảnh hưởng cả độ chính xác **extract text from image** và độ trung thực của bố cục HTML được tạo. + +### Tôi có thể kiểm soát ngôn ngữ của OCR không? + +Có. Đặt thuộc tính `Language` trên `OcrEngine` trước khi gọi `Recognize`: + +```csharp +ocrEngine.Language = Language.English; // or Language.French, etc. +``` + +Điều này cải thiện khả năng nhận dạng khi làm việc với các ký tự không phải tiếng Anh. + +### Làm sao để lấy văn bản thuần thay vì HTML? + +Nếu bạn chỉ cần chuỗi thô, thay `OutputFormat.HtmlWithLayout` bằng `OutputFormat.Text`. Thuộc tính `recognitionResult.Text` sẽ chỉ chứa các ký tự đã trích xuất. + +### Có cách nào nhúng ảnh vào HTML được tạo không? + +Aspose.OCR có thể nhúng ảnh gốc dưới dạng data URI base‑64 khi bạn sử dụng `OutputFormat.HtmlWithLayoutAndImages`. Điều này hữu ích khi bạn muốn một tệp HTML duy nhất mà không cần tài nguyên ngoài. + +```csharp +var result = ocrEngine.Recognize(sourceImage, OutputFormat.HtmlWithLayoutAndImages); +``` + +### Xử lý hàng loạt lớn thì sao? + +Đối với xử lý batch, hãy bọc logic trong một vòng lặp `foreach` qua danh sách các đường dẫn tệp. Việc tái sử dụng cùng một instance của `OcrEngine` giảm tải và tăng tốc quy trình **convert image to html**. + +```csharp +foreach (var file in Directory.GetFiles(@"YOUR_DIRECTORY", "*.jpg")) +{ + var img = OcrImage.FromFile(file); + var html = ocrEngine.Recognize(img, OutputFormat.HtmlWithLayout).Text; + var outPath = Path.ChangeExtension(file, ".html"); + File.WriteAllText(outPath, html); +} +``` + +## Mẹo Cho Mã Sẵn Sàng Sản Xuất + +- **Dispose resources**: Cả `OcrEngine` và `OcrImage` đều triển khai `IDisposable`. Đặt chúng trong câu lệnh `using` để giải phóng bộ nhớ native kịp thời. +- **Error handling**: Bắt `IOException` cho các vấn đề liên quan tới tệp và `OcrException` cho các lỗi nhận dạng. +- **Performance**: Nếu xử lý nhiều ảnh, cân nhắc bật **parallelism** (`Parallel.ForEach`) nhưng hãy chú ý tới mức sử dụng CPU—OCR tiêu tốn nhiều tài nguyên CPU. +- **Logging**: Tích hợp một logger (ví dụ Serilog) để ghi lại điểm tin cậy OCR (`recognitionResult.Confidence`) nhằm giám sát chất lượng. + +## Kết Luận + +Chúng ta vừa tìm hiểu **cách sử dụng Aspose** để **convert image to HTML**, **extract text from image**, và **generate HTML from image** trong vài bước đơn giản. Mẫu mã đầy đủ cho thấy cách **ocr image to html** đồng thời giữ nguyên bố cục, tạo nền tảng vững chắc cho bất kỳ dự án số hoá tài liệu nào. + +Từ đây, bạn có thể: + +- Thử nghiệm các tùy chọn `OutputFormat` khác nhau để phù hợp với nhu cầu. +- Kết hợp đầu ra HTML với một framework CSS để tạo giao diện đáp ứng. +- Đưa văn bản đã trích xuất vào chỉ mục tìm kiếm hoặc pipeline machine‑learning. + +Hãy thử, điều chỉnh các thiết lập và xem Aspose biến ảnh thành nội dung sẵn sàng cho web một cách dễ dàng. Nếu gặp khó khăn, hãy để lại bình luận—chúc bạn lập trình vui! + +![Diagram showing OCR pipeline from image to HTML layout – how to use Aspose](/images/ocr-pipeline.png "how to use aspose") + +--- + + +## Bạn Nên Học Gì Tiếp Theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên đều bao gồm mã mẫu hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Convert Image to Text – Perform OCR on Image from URL](/ocr/english/net/ocr-optimization/perform-ocr-on-image-from-url/) +- [recognize text image with Aspose OCR for multiple languages](/ocr/english/net/ocr-settings/working-with-different-languages/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md b/ocr/vietnamese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md new file mode 100644 index 000000000..2a0d5911f --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/_index.md @@ -0,0 +1,242 @@ +--- +category: general +date: 2026-06-03 +description: Thực hiện OCR trên hình ảnh và trích xuất văn bản từ hình ảnh bằng Aspose.OCR. + Tìm hiểu cách phát hiện các từ sai chính tả và nhận đề xuất sửa lỗi trong một demo + C# duy nhất. +draft: false +keywords: +- perform OCR on image +- extract text from image +- detect misspelled words +- get spelling suggestions +- how to extract text +language: vi +og_description: Thực hiện OCR trên hình ảnh để trích xuất văn bản, sau đó phát hiện + các từ sai chính tả và nhận đề xuất sửa lỗi bằng Aspose.OCR trong C#. +og_title: Thực hiện OCR trên hình ảnh và phát hiện từ sai chính tả trong C# +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image and extract text from image using Aspose.OCR. + Learn how to detect misspelled words and get spelling suggestions in a single + C# demo. + headline: Perform OCR on Image and Detect Misspelled Words in C# + type: TechArticle +tags: +- Aspose OCR +- C# +- Spell Checking +title: Thực hiện OCR trên hình ảnh và phát hiện từ sai chính tả trong C# +url: /vi/net/text-recognition/perform-ocr-on-image-and-detect-misspelled-words-in-c/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Thực hiện OCR trên Hình ảnh và Phát hiện Từ sai chính tả trong C# + +Bạn đã bao giờ tự hỏi làm thế nào để **perform OCR on image** mà không phải rối bời? Bạn không phải là người duy nhất. Dù bạn đang số hoá những lá thư cũ, quét biên lai, hay xây dựng một quy trình tài liệu thông minh, việc trích xuất văn bản sạch sẽ từ ảnh là rào cản đầu tiên. Tin tốt là gì? Với Aspose.OCR bạn có thể tạo giải pháp trong vài phút, và phần thưởng là bạn cũng có thể **detect misspelled words** và **get spelling suggestions** trong cùng một lần chạy. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ứng dụng console C# hoàn chỉnh, sẵn sàng chạy, **extract text from image**, chạy bộ kiểm tra chính tả tiếng Anh, và in ra mỗi lỗi cùng các gợi ý sửa. Khi kết thúc, bạn sẽ biết chính xác **how to extract text**, cách kết nối API kiểm tra chính tả, và dạng đầu ra console dự kiến. + +## Những gì bạn sẽ xây dựng + +- Tải một bitmap (hoặc PNG) chứa các lỗi chính tả. +- Chạy Aspose.OCR để **perform OCR on image** và lấy dữ liệu chuỗi thô. +- Khởi tạo bộ kiểm tra chính tả tiếng Anh tích hợp. +- **Detect misspelled words** và **get spelling suggestions** cho mỗi từ. +- In một báo cáo gọn gàng ra console. + +Không cần dịch vụ bên ngoài, không cần các cuộc gọi HTTP rắc rối—chỉ một gói NuGet duy nhất và một vài dòng code. + +## Yêu cầu trước + +- .NET 6.0 SDK hoặc mới hơn (code cũng chạy trên .NET Framework 4.7+). +- Visual Studio 2022 (hoặc bất kỳ trình soạn thảo nào bạn thích). +- Gói NuGet Aspose.OCR for .NET (`Aspose.OCR`). +- Một file ảnh (`letter_with_typos.png`) đặt ở vị trí bạn có thể tham chiếu từ dự án. + +Nếu bạn chưa từng dùng Aspose, đừng lo—cài đặt gói chỉ cần chạy: + +```bash +dotnet add package Aspose.OCR +``` + +Bây giờ chúng ta cùng đi vào phần thực hiện. + +## Bước 1: Thiết lập dự án và cài đặt Aspose.OCR + +Tạo một dự án console mới và kéo thư viện OCR vào: + +```bash +dotnet new console -n OcrSpellDemo +cd OcrSpellDemo +dotnet add package Aspose.OCR +``` + +Sau khi khôi phục xong, mở `Program.cs`. Chúng ta sẽ thay thế nội dung mặc định bằng toàn bộ mã demo sau, nhưng trước tiên hãy nói về lý do mỗi namespace quan trọng. + +- `Aspose.OCR` – Engine OCR cốt lõi và xử lý ảnh. +- `Aspose.OCR.SpellCheck` – Các tiện ích kiểm tra chính tả đi kèm thư viện. +- `System` – Các lớp nền tảng .NET chuẩn (ví dụ, `Console`). + +## Bước 2: Tải ảnh và Perform OCR on Image + +Công việc thực sự đầu tiên là đưa ảnh vào engine OCR. Aspose.OCR hỗ trợ nhiều định dạng (PNG, JPEG, TIFF). Đây là đoạn mã thực hiện công việc nặng: + +```csharp +// Step 2: Load the image that contains the text to be recognized +var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + +// Step 3: Perform OCR to extract the raw text from the image +var ocrEngine = new OcrEngine(); +var ocrResult = ocrEngine.Recognize(image); +``` + +> **Tại sao điều này quan trọng:** `OcrImage.FromFile` ẩn đi các chi tiết mức pixel, trong khi `OcrEngine.Recognize` chạy mô hình neural đã được huấn luyện để chuyển các glyph hình ảnh thành ký tự Unicode. Thuộc tính `ocrResult.Text` hiện chứa chuỗi thô—đúng là những gì bạn cần để **extract text from image**. + +> **Mẹo chuyên nghiệp:** Nếu ảnh của bạn chứa nhiều ngôn ngữ, bạn có thể đặt `ocrEngine.Language = OcrLanguage.Multilingual;` trước khi gọi `Recognize`. + +## Bước 3: Khởi tạo bộ kiểm tra chính tả tiếng Anh + +Aspose.OCR đi kèm một engine kiểm tra chính tả tích hợp, hiểu tiếng Anh ngay từ đầu. Khởi tạo chỉ cần một dòng: + +```csharp +// Step 4: Initialise the English spell‑checker +var spellChecker = new SpellChecker(OcrLanguage.English); +``` + +> **Tại sao bước này quan trọng:** Kết quả OCR có thể bao gồm các ký tự nhận dạng sai (ví dụ, “l” vs “1”) hoặc các lỗi gõ thực tế từ tài liệu nguồn. Bộ kiểm tra chính tả sẽ quét chuỗi, xác định các token đáng ngờ, và đề xuất các lựa chọn thay thế. + +## Bước 4: Detect Misspelled Words và Get Spelling Suggestions + +Bây giờ chúng ta đưa văn bản OCR vào bộ kiểm tra: + +```csharp +// Step 5: Check the recognized text for misspelled words and obtain suggestions +var misspellings = spellChecker.Check(ocrResult.Text); +``` + +`misspellings` là một collection, mỗi mục chứa từ sai và một mảng các đề xuất sửa. + +## Bước 5: Xuất kết quả + +Cuối cùng, chúng ta duyệt qua collection và in báo cáo dễ đọc: + +```csharp +// Step 6: Output each misspelled word together with its suggested corrections +foreach (var entry in misspellings) +{ + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); +} +``` + +### Đầu ra Console dự kiến + +Giả sử `letter_with_typos.png` chứa câu: + +``` +Ths is an exampel of a lettter with som misspelled wrds. +``` + +Chạy demo sẽ cho ra thứ gì đó như sau: + +``` +Misspelled: Ths + Suggestions: This, Thus, The +Misspelled: exampel + Suggestions: example, exemplar, exampell +Misspelled: lettter + Suggestions: letter, litter, lett +Misspelled: som + Suggestions: some, sum, son +Misspelled: wrds + Suggestions: words, wards, wryds +``` + +Bạn sẽ thấy mỗi lỗi được ghép với một vài gợi ý hợp lý—đúng là những gì bạn cần khi xây dựng UI sửa lỗi thân thiện với người dùng. + +## Ví dụ Hoạt động đầy đủ + +Dưới đây là chương trình **đầy đủ, có thể copy‑paste**. Thay `YOUR_DIRECTORY` bằng đường dẫn thực tế tới file ảnh của bạn. + +```csharp +using Aspose.OCR; +using Aspose.OCR.SpellCheck; +using System; + +class SpellCheckDemo +{ + static void Main() + { + // Step 1: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/letter_with_typos.png"); + + // Step 2: Perform OCR to extract the raw text from the image + var ocrEngine = new OcrEngine(); + var ocrResult = ocrEngine.Recognize(image); + + // Step 3: Initialise the English spell‑checker + var spellChecker = new SpellChecker(OcrLanguage.English); + + // Step 4: Check the recognized text for misspelled words and obtain suggestions + var misspellings = spellChecker.Check(ocrResult.Text); + + // Step 5: Output each misspelled word together with its suggested corrections + foreach (var entry in misspellings) + { + Console.WriteLine($"Misspelled: {entry.Word}"); + Console.WriteLine(" Suggestions: " + string.Join(", ", entry.Suggestions)); + } + + // Optional: Keep console window open when debugging + Console.WriteLine("\nPress any key to exit..."); + Console.ReadKey(); + } +} +``` + +> **Các trường hợp góc cần lưu ý** +> - **Ảnh trống:** Nếu engine OCR trả về chuỗi rỗng, `spellChecker.Check` sẽ chỉ trả về một collection rỗng—không gây lỗi. +> - **Văn bản không phải tiếng Anh:** Thay `OcrLanguage.English` bằng `OcrLanguage.French` (hoặc bất kỳ ngôn ngữ hỗ trợ nào) để **detect misspelled words** trong các locale khác. +> - **Tài liệu lớn:** Đối với PDF đa trang, bạn sẽ lặp qua mỗi trang, thực hiện OCR, sau đó tổng hợp kết quả trước khi kiểm tra chính tả. + +## Tổng quan trực quan (Alt Text hình ảnh) + +![Diagram showing the flow to perform OCR on image, extract text from image, and then detect misspelled words with spelling suggestions](perform-ocr-on-image-flow.png) + +*Biểu đồ trên minh họa quy trình từ đầu đến cuối: ảnh → engine OCR → văn bản thô → bộ kiểm tra chính tả → các đề xuất.* + +## Câu hỏi thường gặp & Mẹo chuyên nghiệp + +| Question | Answer | +|----------|--------| +| **Do I need an internet connection?** | No. Aspose.OCR runs entirely locally; perfect for offline or secure environments. | +| **How accurate is the spell‑checker?** | It uses a dictionary of ~150k English words and fuzzy matching, so most common typos are caught. | +| **Can I customize the dictionary?** | Yes. `SpellChecker.AddUserDictionary("custom.txt")` lets you load domain‑specific terms (e.g., product names). | +| **What if the image is skewed?** | The OCR engine auto‑detects orientation, but you can manually call `ocrEngine.ImagePreprocessing.Rotate(angle)` for stubborn cases. | +| **Is there a way to highlight suggestions in UI?** | After you have the `misspellings` collection, you can map each `entry.Word` back to its position in `ocrResult.Text` and underline it in a RichTextBox or web view. | + +## Kết luận + +Chúng ta vừa cho bạn thấy **how to perform OCR on image**, **extract text from image**, và sau đó **detect misspelled words** đồng thời **getting spelling suggestions**—tất cả chỉ với một ứng dụng console C# ngắn gọn. Ý tưởng cốt lõi rất đơn giản: để Aspose.OCR làm phần nặng của việc nhận dạng ký tự, sau đó để bộ kiểm tra chính tả tích hợp của nó làm sạch đầu ra. Từ đây bạn có thể mở rộng demo thành một dịch vụ xử lý tài liệu toàn diện, tích hợp với API web, hoặc gắn vào một trình soạn thảo desktop. + +Sẵn sàng cho bước tiếp theo? Hãy thử đổi ngôn ngữ sang tiếng Tây Ban Nha, đưa vào một PDF đa trang, hoặc xây dựng một giao diện WPF nhỏ cho phép người dùng nhấp vào từ để chấp nhận đề xuất. Các khối xây dựng đã sẵn sàng—chỉ cần tiếp tục thử nghiệm. + +Nếu bạn gặp bất kỳ khó khăn nào hoặc có ý tưởng mở rộng, hãy để lại bình luận bên dưới. Chúc bạn lập trình vui vẻ! + +## Bạn nên học gì tiếp theo? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên đều bao gồm mã mẫu đầy đủ với các giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md b/ocr/vietnamese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md new file mode 100644 index 000000000..c11c200ad --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/_index.md @@ -0,0 +1,273 @@ +--- +category: general +date: 2026-06-03 +description: Thực hiện OCR trên hình ảnh bằng Aspose OCR trong C#. Tìm hiểu cách tải + hình ảnh để OCR và trích xuất văn bản Hindi từ hình ảnh offline với mã hướng dẫn + từng bước. +draft: false +keywords: +- perform OCR on image +- load image for OCR +- extract Hindi text image +language: vi +og_description: Thực hiện OCR trên hình ảnh bằng Aspose OCR trong C#. Hướng dẫn này + cho thấy cách tải hình ảnh để OCR và trích xuất văn bản Hindi từ hình ảnh một cách + offline, kèm theo mã có thể chạy được. +og_title: Thực hiện OCR trên hình ảnh – Hướng dẫn Aspose OCR tiếng Hindi +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + headline: Perform OCR on Image with Aspose OCR – Hindi Guide + type: TechArticle +- description: Perform OCR on image using Aspose OCR in C#. Learn how to load image + for OCR and extract Hindi text image offline with step‑by‑step code. + name: Perform OCR on Image with Aspose OCR – Hindi Guide + steps: + - name: Create the OCR Engine Instance + text: The engine is the heart of Aspose OCR. Instantiating it gives you access + to all the settings you’ll tweak later. + - name: Point the Engine to Offline Resources + text: Aspose ships language packs that you can store locally. Setting `ResourcesFolder` + tells the engine where to look. + - name: Force Offline Mode + text: You might wonder, “Do I really need to disable online lookup?” If you’re + working behind a firewall or just want deterministic results, set `UseOfflineResources` + to `true`. + - name: Select Hindi as the Recognition Language + text: Here we **extract Hindi text image** by telling the engine which language + to expect. This dramatically improves accuracy. + - name: Load Image for OCR + text: Now we actually **load image for OCR**. The `OcrImage.FromFile` method reads + the bitmap into a format the engine understands. + - name: Run the Recognition + text: With everything set, we finally **perform OCR on image** by calling `Recognize`. + - name: Output the Recognized Text + text: The result object contains a `Text` property that holds the extracted string. + We simply write it to the console. + type: HowTo +tags: +- Aspose OCR +- C# +- Hindi OCR +title: Thực hiện OCR trên hình ảnh bằng Aspose OCR – Hướng dẫn tiếng Hindi +url: /vi/net/text-recognition/perform-ocr-on-image-with-aspose-ocr-hindi-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Thực hiện OCR trên Hình ảnh với Aspose OCR – Hướng dẫn tiếng Hindi + +Bạn đã bao giờ cần **thực hiện OCR trên hình ảnh** nhưng gặp khó khăn trong việc lấy các ký tự Hindi ra khỏi chúng chưa? Bạn không đơn độc—nhiều nhà phát triển gặp phải rào cản này khi lần đầu tiên cố gắng đọc các script không phải Latin. Tin tốt là Aspose OCR giúp quá trình này trở nên rất dễ dàng, và bạn thậm chí có thể thực hiện hoàn toàn offline. + +Trong hướng dẫn này, chúng ta sẽ **tải hình ảnh cho OCR**, chỉ định engine tới các gói ngôn ngữ offline của bạn, và cuối cùng **trích xuất văn bản Hindi từ hình ảnh** mà không cần kết nối internet. Khi hoàn thành, bạn sẽ có một ứng dụng console C# sẵn sàng chạy, đọc một biên lai tiếng Hindi và in văn bản ra console. + +## Những gì bạn cần + +- **.NET 6.0** hoặc mới hơn (mã cũng chạy trên .NET Framework 4.7+) +- **Aspose.OCR for .NET** package NuGet + `dotnet add package Aspose.OCR` +- Thư mục chứa **các tài nguyên ngôn ngữ Hindi offline** (tải từ cổng thông tin của Aspose) +- Tập tin hình ảnh có văn bản Hindi, ví dụ `receipt_hindi.png` + +Đó là tất cả—không có dịch vụ bên ngoài, không có khóa API, chỉ có mã thuần. + +## Thực hiện OCR trên Hình ảnh – Triển khai từng bước + +Dưới đây chúng tôi chia quy trình thành bảy bước rõ ràng. Mỗi bước được giải thích **tại sao** nó quan trọng, không chỉ **cái gì** cần gõ. + +### Bước 1: Tạo thể hiện OCR Engine + +Engine là trái tim của Aspose OCR. Khởi tạo nó cho phép bạn truy cập vào tất cả các cài đặt sẽ được điều chỉnh sau này. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; + +class OfflineLanguageDemo +{ + static void Main() + { + // Step 1: Create the OCR engine instance + var ocrEngine = new OcrEngine(); +``` + +> **Tại sao?** +> Nếu không có `OcrEngine` bạn sẽ không có đối tượng để gọi `Recognize`. Hãy nghĩ nó như “máy ảnh” sẽ quét ảnh của bạn sau này. + +### Bước 2: Chỉ định Engine tới tài nguyên offline + +Aspose cung cấp các gói ngôn ngữ mà bạn có thể lưu cục bộ. Đặt `ResourcesFolder` cho engine biết nơi tìm kiếm. + +```csharp + // Step 2: Point the engine to the folder containing offline language data files + ocrEngine.Settings.ResourcesFolder = @"YOUR_DIRECTORY/Resources"; +``` + +> **Mẹo:** +> Sử dụng đường dẫn tuyệt đối trong quá trình phát triển, sau đó chuyển sang đường dẫn tương đối hoặc thiết lập cấu hình cho môi trường production. + +### Bước 3: Buộc chế độ Offline + +Bạn có thể tự hỏi, “Có thực sự cần tắt tra cứu trực tuyến không?” +Nếu bạn làm việc sau tường lửa hoặc chỉ muốn kết quả xác định, hãy đặt `UseOfflineResources` thành `true`. + +```csharp + // Step 3: Instruct the engine to use only the offline resources (no online lookup) + ocrEngine.Settings.UseOfflineResources = true; +``` + +> **Pro tip:** +> Để cờ này là `false` có thể khiến engine tải thêm dữ liệu, làm tăng độ trễ và có thể vi phạm chính sách bảo mật. + +### Bước 4: Chọn Hindi làm ngôn ngữ nhận dạng + +Ở đây chúng ta **trích xuất văn bản Hindi từ hình ảnh** bằng cách cho engine biết ngôn ngữ mong đợi. Điều này cải thiện độ chính xác đáng kể. + +```csharp + // Step 4: Select the desired language for recognition (Hindi in this case) + ocrEngine.Settings.Language = OcrLanguage.Hindi; +``` + +> **Tại sao nó hữu ích:** +> Các engine OCR sử dụng mô hình ký tự riêng cho từng ngôn ngữ. Khi khóa vào Hindi, bạn tránh việc engine phải đoán trong hàng chục script. + +### Bước 5: Tải hình ảnh cho OCR + +Bây giờ chúng ta thực sự **tải hình ảnh cho OCR**. Phương thức `OcrImage.FromFile` đọc bitmap vào định dạng mà engine hiểu. + +```csharp + // Step 5: Load the image that contains the text to be recognized + var image = OcrImage.FromFile(@"YOUR_DIRECTORY/Images/receipt_hindi.png"); +``` + +> **Cạm bẫy phổ biến:** +> Cung cấp đường dẫn có dấu gạch chéo ngược trên Windows vẫn hoạt động, nhưng dùng `Path.Combine` sẽ làm mã của bạn đa nền tảng hơn. + +### Bước 6: Chạy quá trình nhận dạng + +Với mọi thứ đã sẵn sàng, cuối cùng chúng ta **thực hiện OCR trên hình ảnh** bằng cách gọi `Recognize`. + +```csharp + // Step 6: Perform OCR on the image + var result = ocrEngine.Recognize(image); +``` + +> **Đang xảy ra gì?** +> Engine quét từng pixel, so khớp mẫu với cơ sở dữ liệu glyph Hindi, và tạo ra một chuỗi ký tự Unicode. + +### Bước 7: Xuất văn bản đã nhận dạng + +Đối tượng kết quả chứa thuộc tính `Text` giữ chuỗi đã trích xuất. Chúng ta chỉ cần ghi nó ra console. + +```csharp + // Step 7: Output the recognized text + System.Console.WriteLine(result.Text); + } +} +``` + +> **Kết quả mong đợi:** +> Nếu `receipt_hindi.png` chứa “भुगतान सफल”, console sẽ in đúng dòng đó, giữ nguyên dấu diacritics. + +## Tải hình ảnh cho OCR – Chuẩn bị tài nguyên + +Nếu bạn thắc mắc liệu có thể cung cấp engine một stream thay vì file không, câu trả lời là có. Thay `OcrImage.FromFile` bằng: + +```csharp +using (var stream = File.OpenRead(@"YOUR_DIRECTORY/Images/receipt_hindi.png")) +{ + var image = OcrImage.FromStream(stream); + var result = ocrEngine.Recognize(image); + Console.WriteLine(result.Text); +} +``` + +> **Tại sao dùng stream?** +> Streams cho phép bạn làm việc với hình ảnh lưu trong cơ sở dữ liệu, blob cloud, hoặc tài nguyên nhúng—rất phù hợp cho các dịch vụ mở rộng. + +## Trích xuất văn bản Hindi từ hình ảnh – Xử lý các trường hợp đặc biệt + +1. **Thiếu gói ngôn ngữ** – Nếu không tìm thấy gói Hindi, `Recognize` sẽ ném ngoại lệ. Bao quanh lời gọi trong try/catch và ghi lại thông báo thân thiện. +2. **Hình ảnh độ phân giải thấp** – Độ chính xác OCR giảm dưới 300 dpi. Tiền xử lý ảnh (resize, sharpen) trước khi tải. +3. **Tài liệu đa ngôn ngữ** – Bạn có thể bật nhiều ngôn ngữ: + `ocrEngine.Settings.Language = OcrLanguage.Hindi | OcrLanguage.English;` + +Những điều chỉnh này giúp quy trình **thực hiện OCR trên hình ảnh** của bạn luôn ổn định trong môi trường production. + +## Chạy ví dụ đầy đủ + +Lưu đoạn mã dưới đây thành `Program.cs`, thay thế các đường dẫn placeholder, và chạy: + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class OfflineLanguageDemo +{ + static void Main() + { + // Initialize engine + var ocrEngine = new OcrEngine(); + + // Offline resources folder + ocrEngine.Settings.ResourcesFolder = @"C:\OCRResources"; + + // Force offline mode + ocrEngine.Settings.UseOfflineResources = true; + + // Hindi language only + ocrEngine.Settings.Language = OcrLanguage.Hindi; + + // Load image for OCR + var imagePath = @"C:\OCRResources\Images\receipt_hindi.png"; + var image = OcrImage.FromFile(imagePath); + + // Perform OCR on image + var result = ocrEngine.Recognize(image); + + // Output extracted Hindi text image + Console.WriteLine("Recognized text:"); + Console.WriteLine(result.Text); + } +} +``` + +Khi bạn thực thi `dotnet run`, bạn sẽ thấy đầu ra giống như: + +``` +Recognized text: +भुगतान सफल +धन्यवाद +``` + +Nếu nhận được chuỗi rỗng, hãy kiểm tra lại **ResourcesFolder** đã trỏ đúng tới thư mục chứa `Hindi.traineddata` và ảnh đủ rõ. + +## Kết luận + +Chúng ta đã đi qua cách **thực hiện OCR trên hình ảnh** bằng Aspose OCR, bao quát mọi thứ từ **tải hình ảnh cho OCR** đến **trích xuất văn bản Hindi từ hình ảnh** trong một kịch bản hoàn toàn offline. Mã hoàn chỉnh, có thể chạy được ở trên cung cấp nền tảng vững chắc, và các mẹo về stream, xử lý lỗi, hỗ trợ đa ngôn ngữ sẽ giúp bạn điều chỉnh giải pháp cho các dự án thực tế. + +Sẵn sàng cho bước tiếp theo? Hãy thử chuyển ngôn ngữ sang **OcrLanguage.Tamil** hoặc đưa ảnh từ Azure Blob storage. Bạn cũng có thể thử nghiệm các cài đặt `ImagePreprocessing` để tăng độ chính xác trên các biên lai nhiễu. + +Có câu hỏi hoặc gặp khó khăn? Để lại bình luận—chúc lập trình vui! + +![Perform OCR on image example + + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã đầy đủ với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Trích xuất văn bản hình ảnh C# với lựa chọn ngôn ngữ bằng Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Nhận dạng văn bản hình ảnh với Aspose OCR cho nhiều ngôn ngữ](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [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 diff --git a/ocr/vietnamese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md b/ocr/vietnamese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..2a9e14b94 --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-06-03 +description: Thực hiện OCR trên PDF và chuyển đổi PDF đã quét thành PDF có thể tìm + kiếm bằng Aspose.OCR. Tìm hiểu cách nhận dạng văn bản từ PDF và tạo PDF có thể tìm + kiếm trong vài phút. +draft: false +keywords: +- perform OCR on PDF +- recognize text from PDF +- how to create searchable PDF +- convert scanned PDF to searchable PDF +- convert image to searchable PDF +language: vi +og_description: Thực hiện OCR trên PDF và ngay lập tức tạo PDF có thể tìm kiếm. Hướng + dẫn này trình bày chi tiết cách nhận dạng văn bản từ PDF bằng Aspose.OCR. +og_title: Thực hiện OCR trên PDF – Hướng dẫn C# đầy đủ +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + headline: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + type: TechArticle +- description: Perform OCR on PDF and convert scanned PDF to searchable PDF using + Aspose.OCR. Learn how to recognize text from PDF and create searchable PDFs in + minutes. + name: Perform OCR on PDF with Aspose.OCR – Complete C# Guide + steps: + - name: 1. Large Files & Memory Management + text: If you’re processing PDFs larger than 100 MB, consider using `OcrEngineSettings.MemoryLimit` + to cap memory usage. Additionally, process pages in batches to avoid `OutOfMemoryException`. + - name: 2. Language Support + text: 'By default Aspose.OCR assumes English. To recognize other languages, set + the `Language` property:' + - name: 3. Multi‑Threaded Scenarios + text: '`OcrEngine` is **not** thread‑safe. If you need parallel processing, create + a separate engine per thread.' + - name: 4. Debugging OCR Accuracy + text: 'You can extract the plain text from `ocrResult` for debugging:' + - name: 5. Licensing Gotchas + text: 'When you run the evaluation version, Aspose adds a watermark to the output + PDF. Register your license early in the application:' + type: HowTo +- questions: + - answer: Absolutely. Replace `OcrImage.FromFile("input.pdf")` with the path to + your image file. The engine will rasterize the image and embed the OCR layer + just the same. + question: Can I use this to convert a single image (PNG/JPEG) to a searchable + PDF? + - answer: The engine will overlay the OCR text on top of existing content, so native + text stays selectable while scanned pages become searchable. + question: What if my PDF has both scanned pages and native text? + - answer: 'Accuracy hinges on source quality. Clean, high‑resolution scans (>300 + dpi) give >95 % accuracy. For noisy documents, enable `PreprocessSettings` (deskew, + despeckle) before calling `Recognize`. --- ## Next Steps – Extending Your OCR + Toolkit Now that you can **recognize text from PDF** and **convert s' + question: How accurate is the OCR? + type: FAQPage +tags: +- Aspose +- OCR +- C# +- PDF +title: Thực hiện OCR trên PDF với Aspose.OCR – Hướng dẫn C# đầy đủ +url: /vi/net/text-recognition/perform-ocr-on-pdf-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Thực hiện OCR trên PDF với Aspose.OCR – Hướng dẫn C# đầy đủ + +Bạn đã bao giờ tự hỏi **cách thực hiện OCR trên file PDF** mà không phải vật lộn với hàng chục công cụ dòng lệnh chưa? Bạn không phải là người duy nhất. Dù bạn đang số hoá hoá đơn, lưu trữ các báo cáo cũ, hay chỉ cần một phiên bản có thể tìm kiếm của hợp đồng đã quét, việc biến một PDF tĩnh thành tài liệu có thể tìm kiếm thực sự là một bước đột phá. + +Trong hướng dẫn này, chúng ta sẽ đi qua **cách tạo file PDF có thể tìm kiếm** từ các PDF đã quét (và thậm chí từ các hình ảnh thông thường) bằng Aspose.OCR cho .NET. Khi kết thúc, bạn sẽ có thể **nhận dạng văn bản từ PDF** chỉ với vài dòng mã C#, và bạn sẽ hiểu lý do đằng sau mỗi bước để có thể áp dụng giải pháp vào dự án của mình. + +> **Điểm nhanh:** Toàn bộ quy trình chỉ gồm ba việc—khởi tạo engine OCR, cung cấp nguồn (PDF hoặc hình ảnh), và lưu kết quả PDF có thể tìm kiếm. Hãy cùng bắt đầu. + +--- + +## Những gì bạn cần + +Trước khi bắt đầu, hãy chắc chắn bạn đã có: + +| Yêu cầu | Lý do quan trọng | +|--------------|----------------| +| **.NET 6.0+** (hoặc .NET Framework 4.6+) | Aspose.OCR nhắm tới các runtime hiện đại; các phiên bản cũ hơn có thể thiếu các cập nhật API. | +| **Gói NuGet Aspose.OCR for .NET** | Cung cấp lớp `OcrEngine` và các tiện ích xử lý PDF. | +| **Giấy phép Aspose hợp lệ** (hoặc dùng bản đánh giá miễn phí) | Không có giấy phép, bạn sẽ gặp giới hạn 30 ngày và dấu watermark. | +| **PDF đã quét** (hoặc file hình ảnh) mà bạn muốn biến thành có thể tìm kiếm | Đây là tài liệu nguồn cho OCR. | +| **Visual Studio 2022** (hoặc bất kỳ trình soạn thảo C# nào) | Giúp việc debug dễ dàng hơn, nhưng bất kỳ IDE nào cũng được. | + +Bạn có thể cài đặt thư viện bằng lệnh NuGet sau: + +```bash +dotnet add package Aspose.OCR +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn đang làm việc trên pipeline CI, hãy thêm file giấy phép vào artefacts của build và tải nó tại thời gian chạy để tránh việc hard‑code đường dẫn. + +--- + +## Thực hiện OCR trên PDF – Cài đặt Aspose.OCR + +Điều đầu tiên chúng ta cần là một thể hiện `OcrEngine` mới. Hãy nghĩ nó như bộ não sẽ đọc tài liệu của bạn. + +```csharp +// Step 1: Create an OCR engine instance +var ocrEngine = new OcrEngine(); +``` + +Tại sao phải tạo một thể hiện mới mỗi lần? Engine lưu trữ cấu hình (như cài đặt ngôn ngữ) có thể khác nhau giữa các tài liệu. Khởi tạo lại mỗi lần chạy đảm bảo môi trường sạch sẽ và tránh xung đột giữa các công việc. + +--- + +## Cách tạo PDF có thể tìm kiếm – Cấu hình mật khẩu (Tùy chọn) + +Nếu PDF của bạn được bảo vệ, bạn phải cung cấp mật khẩu cho engine trước khi nó có thể đọc các trang: + +```csharp +// Step 2: (Optional) Provide the password if the PDF is protected +ocrEngine.Settings.PdfPassword = "mySecret"; +``` + +Bỏ qua bước này trên file được bảo vệ sẽ gây ra ngoại lệ `PdfPasswordException`. Luôn bao quanh bằng try‑catch nếu bạn không chắc trạng thái bảo vệ. + +--- + +## Chuyển PDF đã quét thành PDF có thể tìm kiếm – Tải nguồn + +Aspose.OCR làm việc với abstraction `OcrImage`, có thể bao bọc PDF, TIFF, JPEG, v.v. Đây là cách bạn nạp một PDF đã quét vào bộ nhớ: + +```csharp +// Step 3: Load the scanned PDF that will be converted to a searchable PDF +var sourcePdf = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); +``` + +Ở phía sau, `FromFile` sẽ phân tích mỗi trang thành các ảnh raster mà engine OCR có thể xử lý. Nếu bạn có PDF đa trang, engine sẽ tự động lặp qua mọi trang. + +--- + +## Nhận dạng văn bản từ PDF – Thực hiện OCR + +Bây giờ là phần cốt lõi của tutorial: yêu cầu engine nhận dạng văn bản và xuất ra PDF có thể tìm kiếm. + +```csharp +// Step 4: Perform OCR and request a searchable PDF as the output format +var ocrResult = ocrEngine.Recognize(sourcePdf, OutputFormat.SearchablePdf); +``` + +`OutputFormat.SearchablePdf` chỉ cho engine chèn một lớp văn bản vô hình lên trên các ảnh quét gốc. PDF kết quả vẫn giữ nguyên độ trung thực hình ảnh của bản quét đồng thời trở nên hoàn toàn có thể tìm kiếm—đúng như bạn cần cho các cuộc kiểm toán tuân thủ. + +--- + +## Chuyển hình ảnh thành PDF có thể tìm kiếm – Lưu kết quả + +Cuối cùng, ghi dữ liệu nhị phân ra đĩa: + +```csharp +// Step 5: Save the resulting searchable PDF to disk +File.WriteAllBytes("YOUR_DIRECTORY/output.pdf", ocrResult.Binary); +Console.WriteLine("Searchable PDF created."); +``` + +Thuộc tính `Binary` chứa các byte PDF thô. Bạn cũng có thể stream chúng trực tiếp tới phản hồi web nếu đang xây dựng một API. + +--- + +![Sơ đồ mô tả luồng chuyển đổi OCR để tạo PDF có thể tìm kiếm](https://example.com/ocr-flow.png "Sơ đồ luồng thực hiện OCR trên PDF") + +*Văn bản thay thế hình ảnh: Sơ đồ luồng thực hiện OCR trên PDF mô tả cách một PDF đã quét được chuyển thành PDF có thể tìm kiếm.* + +--- + +## Các trường hợp đặc biệt & Mẹo thực tiễn + +### 1. File lớn & Quản lý bộ nhớ +Nếu bạn xử lý các PDF lớn hơn 100 MB, hãy cân nhắc sử dụng `OcrEngineSettings.MemoryLimit` để giới hạn mức sử dụng bộ nhớ. Ngoài ra, xử lý các trang theo lô để tránh `OutOfMemoryException`. + +```csharp +ocrEngine.Settings.MemoryLimit = 512; // MB +``` + +### 2. Hỗ trợ ngôn ngữ +Mặc định Aspose.OCR giả định tiếng Anh. Để nhận dạng các ngôn ngữ khác, đặt thuộc tính `Language`: + +```csharp +ocrEngine.Settings.Language = Language.French; // or Language.Multilingual +``` + +### 3. Kịch bản đa luồng +`OcrEngine` **không** thread‑safe. Nếu bạn cần xử lý song song, hãy tạo một engine riêng cho mỗi luồng. + +### 4. Debug độ chính xác OCR +Bạn có thể trích xuất văn bản thô từ `ocrResult` để debug: + +```csharp +string plainText = ocrResult.Text; +Console.WriteLine(plainText); +``` + +Nếu kết quả trông rối mắt, hãy thử nghiệm với `PreprocessSettings` (ví dụ: deskew, despeckle) để cải thiện chất lượng. + +### 5. Những lưu ý về giấy phép +Khi bạn chạy phiên bản đánh giá, Aspose sẽ thêm watermark vào PDF đầu ra. Đăng ký giấy phép sớm trong ứng dụng: + +```csharp +var license = new License(); +license.SetLicense("Aspose.OCR.lic"); +``` + +--- + +## Ví dụ hoàn chỉnh – Từ đầu đến cuối + +Dưới đây là chương trình đầy đủ, sẵn sàng chạy, bao gồm tất cả các mẹo ở trên. Bạn có thể sao chép‑dán vào một dự án console mới. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Settings; +using System; +using System.IO; + +class PdfOcrDemo +{ + static void Main() + { + // Load license (replace with your actual license file) + var license = new License(); + license.SetLicense("Aspose.OCR.lic"); + + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine(); + + // Optional: set PDF password if needed + // ocrEngine.Settings.PdfPassword = "mySecret"; + + // Optional: tweak memory usage for large files + ocrEngine.Settings.MemoryLimit = 1024; // MB + + // 2️⃣ Load scanned PDF (or image) – adjust path as required + var source = OcrImage.FromFile("YOUR_DIRECTORY/input.pdf"); + + // 3️⃣ Perform OCR – ask for a searchable PDF output + var result = ocrEngine.Recognize(source, OutputFormat.SearchablePdf); + + // 4️⃣ Save the searchable PDF + string outputPath = Path.Combine("YOUR_DIRECTORY", "output.pdf"); + File.WriteAllBytes(outputPath, result.Binary); + + Console.WriteLine($"Searchable PDF created at: {outputPath}"); + } +} +``` + +**Kết quả mong đợi:** Sau khi chạy, bạn sẽ thấy một dòng console xác nhận vị trí file. Mở `output.pdf` bằng bất kỳ trình xem PDF nào; thử gõ một từ mà bạn biết có trong bản quét gốc. Nếu từ đó được highlight, bạn đã **thực hiện OCR trên PDF** thành công và tạo ra một tài liệu có thể tìm kiếm. + +--- + +## Câu hỏi thường gặp + +**H: Tôi có thể dùng cách này để chuyển một hình ảnh đơn (PNG/JPEG) thành PDF có thể tìm kiếm không?** +Đ: Chắc chắn rồi. Thay `OcrImage.FromFile("input.pdf")` bằng đường dẫn tới file hình ảnh của bạn. Engine sẽ rasterize hình ảnh và chèn lớp OCR tương tự. + +**H: Nếu PDF của tôi có cả trang quét và văn bản gốc thì sao?** +Đ: Engine sẽ chồng lớp văn bản OCR lên nội dung hiện có, vì vậy văn bản gốc vẫn có thể chọn được trong khi các trang quét trở nên có thể tìm kiếm. + +**H: Độ chính xác của OCR như thế nào?** +Đ: Độ chính xác phụ thuộc vào chất lượng nguồn. Các bản quét sạch, độ phân giải cao (>300 dpi) thường đạt >95 % độ chính xác. Đối với tài liệu nhiễu, bật `PreprocessSettings` (deskew, despeckle) trước khi gọi `Recognize`. + +--- + +## Bước tiếp theo – Mở rộng bộ công cụ OCR của bạn + +Bây giờ bạn đã có thể **nhận dạng văn bản từ PDF** và **chuyển PDF đã quét thành PDF có thể tìm kiếm**, hãy cân nhắc các chủ đề tiếp theo: + +- **Xử lý batch**: Duyệt qua một thư mục các PDF và tự động tạo phiên bản có thể tìm kiếm. +- **Trích xuất văn bản**: Sử dụng `ocrResult.Text` để đưa vào chỉ mục tìm kiếm (ví dụ: Elasticsearch). +- **Gói ngôn ngữ tùy chỉnh**: Tải xuống dữ liệu ngôn ngữ bổ sung từ Aspose để hỗ trợ các script châu Á. +- **Tuân thủ PDF/A**: Kết hợp Aspose.PDF với kết quả OCR để tạo PDF sẵn sàng lưu trữ lâu dài. + +Mỗi mục trên dựa trên các bước cốt lõi mà chúng ta đã đề cập, vì vậy bạn đã sẵn sàng mở rộng giải pháp của mình. + +--- + +## Kết luận + +Chúng tôi vừa chỉ cho bạn **cách thực hiện OCR trên PDF** bằng Aspose.OCR, biến các PDF đã quét thành PDF có thể tìm kiếm hoàn toàn, và thậm chí đã đề cập đến việc chuyển đổi hình ảnh đơn thành PDF có thể tìm kiếm. Mã nguồn + +## Bạn nên học gì tiếp theo? + +Các tutorial sau đây đề cập đến các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật đã được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoàn chỉnh với giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Recognize PDF Text – OCR Operations with Aspose.OCR for Java](/ocr/english/java/ocr-operations/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md b/ocr/vietnamese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9aa1f367c --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/_index.md @@ -0,0 +1,277 @@ +--- +category: general +date: 2026-06-03 +description: Hướng dẫn OCR phụ đề video, chỉ cách trích xuất khung hình từ video và + đọc văn bản từ các tệp video như MP4 bằng Aspose.OCR. +draft: false +keywords: +- video subtitle ocr +- extract frames from video +- read text from video +- extract text from mp4 +language: vi +og_description: Học OCR phụ đề video với Aspose.OCR. Trích xuất khung hình từ video, + đọc văn bản từ video và trích xuất văn bản từ MP4 trong vài phút. +og_title: OCR phụ đề video trong C# – Hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-06-03' + description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + headline: Video Subtitle OCR in C# – Complete Guide + type: TechArticle +- description: Video subtitle OCR tutorial showing how to extract frames from video + and read text from video files like MP4 using Aspose.OCR. + name: Video Subtitle OCR in C# – Complete Guide + steps: + - name: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + text: Decodes an MP4 (or any supported format) into individual `Bitmap` frames. + - name: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + text: Limits the OCR region to the subtitle band so the engine isn’t distracted + by the whole picture. + - name: Processes each frame with Aspose’s `VideoOcrProcessor`. + text: Processes each frame with Aspose’s `VideoOcrProcessor`. + - name: Prints the recognized subtitle text to the console. + text: Prints the recognized subtitle text to the console. + type: HowTo +tags: +- C# +- Aspose.OCR +- video-processing +title: OCR phụ đề video trong C# – Hướng dẫn toàn diện +url: /vi/net/text-recognition/video-subtitle-ocr-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR phụ đề video trong C# – Hướng dẫn đầy đủ + +Bạn đã bao giờ cần **video subtitle ocr** nhưng không biết bắt đầu từ đâu? Bạn không phải là người duy nhất. Dù bạn đang số hoá các bản ghi bài giảng, trích xuất phụ đề từ video đào tạo, hay chỉ đơn giản tò mò về cách đọc văn bản từ video, hướng dẫn này sẽ chỉ cho bạn cách thực hiện bằng C# và Aspose.OCR. + +Trong vài phút tới, chúng ta sẽ trích xuất các khung hình từ video, chạy OCR trên các khung hình đó, và cuối cùng hiển thị văn bản phụ đề từng khung. Khi kết thúc, bạn sẽ có thể **read text from video** các tệp—bao gồm MP4—mà không cần tìm kiếm công cụ của bên thứ ba. + +## Những gì bạn sẽ xây dựng + +1. Giải mã một MP4 (hoặc bất kỳ định dạng nào được hỗ trợ) thành các khung `Bitmap` riêng lẻ. +2. Giới hạn vùng OCR chỉ ở dải phụ đề để engine không bị phân tâm bởi toàn bộ hình ảnh. +3. Xử lý mỗi khung hình bằng `VideoOcrProcessor` của Aspose. +4. In ra văn bản phụ đề đã nhận dạng lên console. + +Không có phần thừa, chỉ một ví dụ hoạt động từ đầu đến cuối mà bạn có thể đưa vào dự án thực tế. + +## Yêu cầu trước + +- **.NET 6.0** trở lên (mã cũng hoạt động trên .NET Framework 4.7+). +- **Aspose.OCR for .NET** – cài đặt qua NuGet: `Install-Package Aspose.OCR`. +- Một tệp video (MP4 hoạt động tốt). +- Một cách để giải mã các khung video – bản demo sử dụng một phương thức placeholder, nhưng bạn có thể tích hợp FFmpeg, OpenCV, hoặc bất kỳ thư viện nào trả về đối tượng `Bitmap`. + +> Mẹo: Nếu bạn đang dùng Windows, gói `System.Drawing.Common` hoạt động tốt cho `Bitmap`. Trên Linux/macOS bạn sẽ cần phụ thuộc native `libgdiplus`. + +## Bước 1 – Trích xuất khung hình từ video + +Rào cản đầu tiên là chuyển một hình ảnh động thành các hình tĩnh. Phương thức `GetVideoFrames` dưới đây được để trống cố ý; hãy thay thế nó bằng bộ giải mã yêu thích của bạn. Dưới đây là một bản phác thảo nhanh sử dụng FFmpeg‑Core (chỉ để minh họa cấu trúc dữ liệu): + +```csharp +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +/// +/// Extracts every frame from the supplied video file and yields it as a Bitmap. +/// You can swap this implementation for OpenCV, MediaToolkit, etc. +/// +static IEnumerable GetVideoFrames(string videoPath) +{ + // Create a temporary folder for the extracted PNGs + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + // FFmpeg command: -i input -vf fps=1 output_%04d.png (1 fps for demo) + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + Process ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + // Clone the bitmap so the file can be deleted later + yield return new Bitmap(bmp); + } + + // Clean up + Directory.Delete(tempDir, true); +} +``` + +> **Tại sao điều này quan trọng:** Việc trích xuất khung hình cung cấp cho engine OCR một hình ảnh tĩnh để làm việc, giúp cải thiện độ chính xác đáng kể so với việc cố gắng đọc trực tiếp từ luồng video. + +## Bước 2 – Thiết lập VideoOcrProcessor + +Bây giờ chúng ta đã có một chuỗi các đối tượng `Bitmap`, chúng ta có thể đưa chúng cho Aspose.OCR. `VideoOcrProcessor` cho phép chúng ta định nghĩa một **Region of Interest (ROI)** – hoàn hảo cho phụ đề thường nằm ở trên hoặc dưới khung hình. + +```csharp +using Aspose.OCR.Video; +using System.Drawing; + +// Create the processor and focus on the top 200 pixels (typical subtitle band) +var ocrProcessor = new VideoOcrProcessor +{ + // ROI = new Rectangle(x, y, width, height) + Roi = new Rectangle(0, 0, 1920, 200) // adjust width/height to your video resolution +}; +``` + +> **Tại sao giới hạn ROI?** Bằng cách bỏ qua phần còn lại của hình ảnh, chúng ta giảm nhiễu, rút ngắn thời gian xử lý và tránh các kết quả dương tính giả từ đồ họa nền. + +## Bước 3 – Chạy OCR trên chuỗi khung hình + +Khi bộ xử lý đã sẵn sàng, việc đưa các khung hình vào chỉ cần một dòng lệnh. Phương thức `Process` trả về một enumerable các đối tượng `OcrResult`, mỗi đối tượng chứa văn bản đã nhận dạng cho khung hình tương ứng. + +```csharp +IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + +// Execute OCR on every extracted frame +IEnumerable ocrResults = ocrProcessor.Process(videoFrames); +``` + +> **Điều gì đang diễn ra bên trong?** Aspose.OCR nội bộ chuẩn hoá mỗi bitmap, chạy bộ nhận dạng dựa trên mạng nơ-ron, và sau đó xử lý hậu kỳ kết quả để cải thiện dấu câu và ngắt dòng. + +## Bước 4 – Hiển thị văn bản đã trích xuất + +Cuối cùng, chúng ta lặp qua các kết quả và in mỗi dòng phụ đề. Bạn cũng có thể ghi chúng vào tệp SRT, cơ sở dữ liệu, hoặc đưa chúng vào dịch vụ dịch thuật. + +```csharp +int frameIndex = 0; +foreach (var result in ocrResults) +{ + // result.Text contains the plain‑text subtitle for this frame + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); +} +``` + +### Ví dụ hoàn chỉnh hoạt động + +Kết hợp mọi thứ lại sẽ tạo ra một chương trình console tự chứa: + +```csharp +using Aspose.OCR.Video; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Diagnostics; +using System.IO; + +class VideoSubtitleOcrDemo +{ + static void Main() + { + // 1️⃣ Extract frames from the MP4 (replace with your own decoder) + IEnumerable videoFrames = GetVideoFrames(@"C:\Videos\lecture.mp4"); + + // 2️⃣ Configure OCR – focus on the subtitle band + var ocrProcessor = new VideoOcrProcessor + { + Roi = new Rectangle(0, 0, 1920, 200) // tweak for your video size + }; + + // 3️⃣ Run OCR across all frames + IEnumerable ocrResults = ocrProcessor.Process(videoFrames); + + // 4️⃣ Output the recognized subtitle text + int frameIndex = 0; + foreach (var result in ocrResults) + { + Console.WriteLine($"Frame {frameIndex++}: {result.Text}"); + } + } + + // -------------------------------------------------------------------- + // Helper: extract one‑frame‑per‑second PNGs using FFmpeg. + // Replace this with any library that can return Bitmap objects. + // -------------------------------------------------------------------- + static IEnumerable GetVideoFrames(string videoPath) + { + string tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(tempDir); + + var startInfo = new ProcessStartInfo + { + FileName = "ffmpeg", + Arguments = $"-i \"{videoPath}\" -vf fps=1 \"{tempDir}\\frame_%04d.png\" -hide_banner -loglevel error", + RedirectStandardOutput = true, + UseShellExecute = false, + CreateNoWindow = true + }; + using var ffmpeg = Process.Start(startInfo); + ffmpeg.WaitForExit(); + + foreach (var file in Directory.GetFiles(tempDir, "frame_*.png")) + { + using var bmp = new Bitmap(file); + yield return new Bitmap(bmp); + } + + Directory.Delete(tempDir, true); + } +} +``` + +**Kết quả mong đợi (mẫu)** + +``` +Frame 0: Welcome to the Introduction to Machine Learning. +Frame 1: In this lecture we will cover... +Frame 2: ... +``` + +Nếu OCR gặp khó khăn với một khung hình cụ thể, bạn sẽ thấy một chuỗi trống – đó là dấu hiệu để điều chỉnh ROI hoặc tăng tốc độ trích xuất khung. + +## Những khó khăn thường gặp & Cách khắc phục + +| Vấn đề | Nguyên nhân | Cách khắc phục | +|-------|-------------|----------------| +| **Garbage characters** | Khung hình độ phân giải thấp hoặc nén mạnh | Trích xuất khung ở bitrate cao hơn, hoặc tăng kích thước bitmap trước khi OCR (`Bitmap.Clone(new Size(...), ...)`). | +| **No text returned** | ROI không thực sự bao phủ dải phụ đề | Xác minh tọa độ hình chữ nhật (sử dụng công cụ chụp màn hình để đo). | +| **Performance bottleneck** | Xử lý mọi khung ở 30 fps là quá mức cần thiết | Giảm mẫu xuống 1‑2 fps cho hầu hết các luồng phụ đề; bạn vẫn có thể nắm bắt mọi thay đổi phụ đề. | +| **FFmpeg not found** | `ffmpeg.exe` không có trong `PATH` | Cung cấp đường dẫn đầy đủ trong `ProcessStartInfo.FileName` hoặc cài đặt FFmpeg toàn cục. | + +## Mở rộng giải pháp + +- **Export to SRT** – nối các dấu thời gian với văn bản OCR và ghi thành tệp SubRip. +- **Multi‑language support** – đặt `ocrProcessor.Language = OcrLanguage.Spanish` (hoặc bất kỳ ngôn ngữ nào được hỗ trợ). +- **Real‑time processing** – truyền khung trực tiếp từ luồng trực tiếp thay vì đọc từ đĩa. + +Tất cả các biến thể này vẫn xoay quanh các ý tưởng cốt lõi là **extract frames from video**, **read text from video**, và **extract text from mp4**. + +## Kết luận + +Chúng ta vừa đi qua một quy trình **video subtitle ocr** hoàn chỉnh trong C#. Bằng cách trích xuất khung hình từ video, tập trung OCR vào dải phụ đề, và lặp qua các kết quả, bạn có thể một cách đáng tin cậy **read text from video** các tệp như MP4. Mã đã sẵn sàng để sao chép‑dán, và thiết kế mô-đun cho phép bạn thay thế bất kỳ bộ giải mã khung nào bạn muốn. + +Bước tiếp theo? Hãy thử xuất kết quả ra tệp SRT, thử nghiệm với các kích thước ROI khác nhau, hoặc đưa phụ đề vào API dịch thuật để có phụ đề đa ngôn ngữ. Không gì là không thể khi bạn đã nắm vững các kiến thức cơ bản về trích xuất văn bản từ video. + +Chúc lập trình vui vẻ, và hy vọng phụ đề của bạn luôn rõ ràng như pha lê! + +## Bạn nên học gì tiếp theo? + +Các hướng dẫn sau đây bao gồm các chủ đề liên quan chặt chẽ, xây dựng trên các kỹ thuật được trình bày trong hướng dẫn này. Mỗi tài nguyên bao gồm các ví dụ mã hoạt động đầy đủ với các giải thích từng bước để giúp bạn làm chủ các tính năng API bổ sung và khám phá các cách triển khai thay thế trong dự án của mình. + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [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