From 044309c1e0c3a6410115d822a9ad5f09d172db30 Mon Sep 17 00:00:00 2001 From: Muhammad Adil Date: Mon, 25 May 2026 11:39:56 +0000 Subject: [PATCH] Add 9 ocr net tutorials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Categories: ocr-configuration, ocr-optimization, text-recognition Source: AI Search API Tutorials: - recognize text from image with Aspose OCR – Complete C# Guide - How to Use OCR in C# – Recognize Chinese Text from JPG - OCR Russian Text in C# – Complete Guide Using Aspose OCR - Extract Text from Image in C# – Complete Aspose OCR Guide - Preprocess Image for OCR – Complete Aspose C# Guide - Extract Text from Image in ASP.NET Core Minimal API – Complete Guide - c# OCR tutorial: Extract Text from PNG Receipts with Aspose - Create OCR Engine in C# – Complete Guide - Convert TIFF to Text in C# – Complete Batch OCR Guide Auto-generated by Professionalize.Tutorials Agent --- ocr/arabic/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/arabic/net/ocr-optimization/_index.md | 1 + .../_index.md | 231 +++++++++++++ ocr/arabic/net/text-recognition/_index.md | 19 +- .../_index.md | 220 ++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 298 +++++++++++++++++ .../_index.md | 306 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/chinese/net/ocr-configuration/_index.md | 6 +- .../_index.md | 264 +++++++++++++++ ocr/chinese/net/ocr-optimization/_index.md | 3 + .../_index.md | 229 +++++++++++++ ocr/chinese/net/text-recognition/_index.md | 10 +- .../_index.md | 218 ++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 310 +++++++++++++++++ .../_index.md | 296 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 207 ++++++++++++ ocr/czech/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/czech/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/czech/net/text-recognition/_index.md | 21 +- .../_index.md | 221 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 298 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 208 ++++++++++++ ocr/dutch/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/dutch/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/dutch/net/text-recognition/_index.md | 17 +- .../_index.md | 222 +++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 313 +++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 209 ++++++++++++ ocr/english/net/ocr-configuration/_index.md | 4 +- .../_index.md | 267 +++++++++++++++ ocr/english/net/ocr-optimization/_index.md | 4 +- .../_index.md | 231 +++++++++++++ ocr/english/net/text-recognition/_index.md | 17 +- .../_index.md | 221 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 313 +++++++++++++++++ .../_index.md | 301 +++++++++++++++++ .../_index.md | 306 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/french/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/french/net/ocr-optimization/_index.md | 2 + .../_index.md | 229 +++++++++++++ ocr/french/net/text-recognition/_index.md | 17 +- .../_index.md | 218 ++++++++++++ .../_index.md | 204 ++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 313 +++++++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 210 ++++++++++++ ocr/german/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/german/net/ocr-optimization/_index.md | 4 +- .../_index.md | 231 +++++++++++++ ocr/german/net/text-recognition/_index.md | 21 +- .../_index.md | 220 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 295 ++++++++++++++++ .../_index.md | 301 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/greek/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/greek/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/greek/net/text-recognition/_index.md | 17 +- .../_index.md | 221 ++++++++++++ .../_index.md | 204 ++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 313 +++++++++++++++++ .../_index.md | 300 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/hindi/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/hindi/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/hindi/net/text-recognition/_index.md | 38 ++- .../_index.md | 220 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 293 ++++++++++++++++ .../_index.md | 299 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 209 ++++++++++++ ocr/hongkong/net/ocr-configuration/_index.md | 4 +- .../_index.md | 264 +++++++++++++++ ocr/hongkong/net/ocr-optimization/_index.md | 2 + .../_index.md | 221 ++++++++++++ ocr/hongkong/net/text-recognition/_index.md | 17 +- .../_index.md | 218 ++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 290 ++++++++++++++++ .../_index.md | 298 +++++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 209 ++++++++++++ ocr/hungarian/net/ocr-configuration/_index.md | 6 +- .../_index.md | 268 +++++++++++++++ ocr/hungarian/net/ocr-optimization/_index.md | 3 + .../_index.md | 231 +++++++++++++ ocr/hungarian/net/text-recognition/_index.md | 17 +- .../_index.md | 219 ++++++++++++ .../_index.md | 204 ++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 314 ++++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 211 ++++++++++++ .../net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/indonesian/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/indonesian/net/text-recognition/_index.md | 17 +- .../_index.md | 218 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 293 ++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 209 ++++++++++++ ocr/italian/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/italian/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/italian/net/text-recognition/_index.md | 17 +- .../_index.md | 220 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 300 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/japanese/net/ocr-configuration/_index.md | 3 +- .../_index.md | 264 +++++++++++++++ ocr/japanese/net/ocr-optimization/_index.md | 2 + .../_index.md | 227 +++++++++++++ ocr/japanese/net/text-recognition/_index.md | 19 +- .../_index.md | 218 ++++++++++++ .../_index.md | 201 +++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 310 +++++++++++++++++ .../_index.md | 298 +++++++++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 207 ++++++++++++ ocr/korean/net/ocr-configuration/_index.md | 5 +- .../_index.md | 264 +++++++++++++++ ocr/korean/net/ocr-optimization/_index.md | 8 +- .../_index.md | 229 +++++++++++++ ocr/korean/net/text-recognition/_index.md | 16 +- .../_index.md | 220 ++++++++++++ .../_index.md | 214 ++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 300 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 207 ++++++++++++ ocr/polish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/polish/net/ocr-optimization/_index.md | 3 + .../_index.md | 231 +++++++++++++ ocr/polish/net/text-recognition/_index.md | 19 +- .../_index.md | 218 ++++++++++++ .../_index.md | 205 ++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 292 ++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 213 ++++++++++++ .../net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/portuguese/net/ocr-optimization/_index.md | 4 +- .../_index.md | 231 +++++++++++++ ocr/portuguese/net/text-recognition/_index.md | 17 +- .../_index.md | 220 ++++++++++++ .../_index.md | 204 ++++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 299 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/russian/net/ocr-configuration/_index.md | 6 +- .../_index.md | 266 +++++++++++++++ ocr/russian/net/ocr-optimization/_index.md | 3 + .../_index.md | 231 +++++++++++++ ocr/russian/net/text-recognition/_index.md | 17 +- .../_index.md | 220 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 314 ++++++++++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 213 ++++++++++++ ocr/spanish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/spanish/net/ocr-optimization/_index.md | 2 + .../_index.md | 231 +++++++++++++ ocr/spanish/net/text-recognition/_index.md | 18 +- .../_index.md | 221 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 301 +++++++++++++++++ .../_index.md | 306 +++++++++++++++++ .../_index.md | 211 ++++++++++++ ocr/swedish/net/ocr-configuration/_index.md | 6 +- .../_index.md | 266 +++++++++++++++ ocr/swedish/net/ocr-optimization/_index.md | 5 + .../_index.md | 230 +++++++++++++ ocr/swedish/net/text-recognition/_index.md | 17 +- .../_index.md | 221 ++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 303 +++++++++++++++++ .../_index.md | 294 ++++++++++++++++ .../_index.md | 298 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 210 ++++++++++++ ocr/thai/net/ocr-configuration/_index.md | 4 +- .../_index.md | 264 +++++++++++++++ ocr/thai/net/ocr-optimization/_index.md | 3 + .../_index.md | 231 +++++++++++++ ocr/thai/net/text-recognition/_index.md | 17 +- .../_index.md | 220 ++++++++++++ .../_index.md | 203 +++++++++++ .../_index.md | 302 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 298 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 209 ++++++++++++ ocr/turkish/net/ocr-configuration/_index.md | 4 +- .../_index.md | 267 +++++++++++++++ ocr/turkish/net/ocr-optimization/_index.md | 2 + .../_index.md | 224 +++++++++++++ ocr/turkish/net/text-recognition/_index.md | 16 +- .../_index.md | 221 ++++++++++++ .../_index.md | 202 +++++++++++ .../_index.md | 304 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 299 +++++++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 209 ++++++++++++ .../net/ocr-configuration/_index.md | 4 +- .../_index.md | 266 +++++++++++++++ ocr/vietnamese/net/ocr-optimization/_index.md | 2 + .../_index.md | 232 +++++++++++++ ocr/vietnamese/net/text-recognition/_index.md | 17 +- .../_index.md | 220 ++++++++++++ .../_index.md | 205 ++++++++++++ .../_index.md | 305 +++++++++++++++++ .../_index.md | 312 +++++++++++++++++ .../_index.md | 299 +++++++++++++++++ .../_index.md | 307 +++++++++++++++++ .../_index.md | 211 ++++++++++++ 276 files changed, 54446 insertions(+), 70 deletions(-) create mode 100644 ocr/arabic/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/arabic/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/arabic/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/arabic/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/arabic/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/arabic/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/arabic/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/arabic/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/arabic/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/chinese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/chinese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/chinese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/chinese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/chinese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/chinese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/chinese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/chinese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/chinese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/czech/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/czech/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/czech/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/czech/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/czech/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/czech/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/czech/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/czech/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/czech/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/dutch/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/dutch/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/dutch/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/dutch/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/dutch/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/dutch/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/dutch/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/dutch/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/dutch/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/english/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/english/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/english/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/english/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/english/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/english/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/english/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/english/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/english/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/french/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/french/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/french/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/french/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/french/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/french/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/french/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/french/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/french/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/german/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/german/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/german/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/german/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/german/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/german/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/german/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/german/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/german/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/greek/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/greek/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/greek/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/greek/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/greek/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/greek/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/greek/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/greek/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/greek/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/hindi/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/hindi/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/hindi/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/hindi/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/hindi/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/hindi/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/hindi/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/hindi/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/hindi/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/hongkong/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/hongkong/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/hongkong/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/hongkong/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/hongkong/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/hongkong/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/hongkong/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/hongkong/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/hongkong/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/hungarian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/hungarian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/hungarian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/hungarian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/hungarian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/hungarian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/hungarian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/hungarian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/hungarian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/indonesian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/indonesian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/indonesian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/indonesian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/indonesian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/indonesian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/indonesian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/indonesian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/indonesian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/italian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/italian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/italian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/italian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/italian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/italian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/italian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/italian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/italian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/japanese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/japanese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/japanese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/japanese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/japanese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/japanese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/japanese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/japanese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/japanese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/korean/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/korean/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/korean/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/korean/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/korean/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/korean/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/korean/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/korean/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/korean/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/polish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/polish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/polish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/polish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/polish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/polish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/polish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/polish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/polish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/portuguese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/portuguese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/portuguese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/portuguese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/portuguese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/portuguese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/portuguese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/portuguese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/portuguese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/russian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/russian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/russian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/russian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/russian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/russian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/russian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/russian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/russian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/spanish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/spanish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/spanish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/spanish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/spanish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/spanish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/spanish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/spanish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/spanish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/swedish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/swedish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/swedish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/swedish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/swedish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/swedish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/swedish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/swedish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/swedish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/thai/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/thai/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/thai/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/thai/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/thai/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/thai/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/thai/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/thai/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/thai/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/turkish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/turkish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/turkish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/turkish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/turkish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/turkish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/turkish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/turkish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/turkish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md create mode 100644 ocr/vietnamese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md create mode 100644 ocr/vietnamese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md create mode 100644 ocr/vietnamese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md diff --git a/ocr/arabic/net/ocr-configuration/_index.md b/ocr/arabic/net/ocr-configuration/_index.md index 64743e9bd..6d1c242e5 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 مع القوائم بسهولة. عزّز الإنتاجية واستخراج البيانات في تطبيقاتك. +### [إنشاء محرك OCR في C# – دليل كامل](./create-ocr-engine-in-c-complete-guide/) +دليل شامل لإنشاء محرك OCR باستخدام C# مع Aspose.OCR، يغطي الإعداد، التكوين، واستخدامه في التطبيقات. ### حالات الاستخدام الشائعة - **استخراج نصوص الصور** من الفواتير الممسوحة لأتمتة المحاسبة. @@ -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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/arabic/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..c01d0cf5e --- /dev/null +++ b/ocr/arabic/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: إنشاء محرك OCR بلغة C# وتعلم كيفية التحقق من وضع التقييم وحالة الترخيص + في بضع أسطر من الشيفرة. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: ar +og_description: إنشاء محرك OCR بلغة C# ورؤية فورية لكيفية اكتشاف وضع التقييم وعرض + حالة الترخيص. +og_title: إنشاء محرك OCR بلغة C# – دليل خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: إنشاء محرك OCR بلغة C# – دليل شامل +url: /ar/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# إنشاء محرك OCR في C# – دليل كامل + +هل تساءلت يومًا كيف **create OCR engine** كائنات في C# دون البحث في وثائق لا نهائية؟ لست وحدك. يواجه العديد من المطورين صعوبة عندما يحتاجون إلى تشغيل محرك OCR، والتحقق مما إذا كان يعمل في وضع التجربة، وعرض حالة الترخيص للمستخدمين. + +في هذا البرنامج التعليمي سنستعرض مثالًا مختصرًا وشاملًا **creates an OCR engine**، يتحقق من **OCR engine evaluation mode**، ويطبع رسالة ودية حول حالة الترخيص. في النهاية ستحصل على تطبيق كونسول جاهز للتنفيذ ونموذج ذهني واضح للتعامل مع ترخيص OCR في مشاريعك الخاصة. + +## ما ستتعلمه + +- كيفية إنشاء كائن `OcrEngine` (جوهر أي سير عمل OCR). +- لماذا يهم اكتشاف **evaluation mode** للامتثال وتجربة المستخدم. +- أفضل طريقة **check OCR license** الحالة والتعامل مع الحالات غير المتوقعة. +- الأخطاء الشائعة—المراجع الفارغة، معالجة الاستثناءات، وتعارض الإصدارات. + +لا تحتاج إلى أدوات خارجية بخلاف SDK الـ OCR الذي قمت بتثبيته بالفعل. إذا كنت مرتاحًا مع أساسيات C#، فأنت جاهز للبدء. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يتوافق مع .NET Core و .NET Framework). +- SDK للـ OCR يحتوي على فئة `OcrEngine` مع خاصية `IsEvaluation` (على سبيل المثال، `MyOcrSdk` الافتراضي). +- محرر نصوص أو بيئة تطوير (Visual Studio، VS Code، Rider—اختر ما تفضله). + +هذا كل ما تحتاجه. لنبدأ. + +## الخطوة 1: إعداد مشروع كونسول جديد + +أولًا، أنشئ تطبيق كونسول جديد لتشغيل الكود بمعزل. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +افتح الملف `Program.cs` الذي تم إنشاؤه. سنستبدل محتوياته بمثال كامل **creates OCR engine** ويتعامل مع الترخيص. + +## الخطوة 2: استيراد مساحة أسماء SDK الـ OCR + +بافتراض أن الـ SDK مضاف عبر NuGet (`MyOcrSdk` هو مجرد مثال)، أضف توجيه `using` في أعلى الملف. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +إذا لم تقم بإضافة الحزمة بعد، نفّذ: + +```bash +dotnet add package MyOcrSdk +``` + +> **نصيحة محترف:** احرص على تحديث نسخة الـ SDK بانتظام؛ الإصدارات الأحدث غالبًا ما تحسّن اكتشاف وضع التجربة. + +## الخطوة 3: إنشاء كائن محرك OCR + +الآن نصل أخيرًا إلى **create OCR engine**. هذا هو قلب أي سير عمل OCR—فكر فيه كالعقل الذي سيقرأ الصور لاحقًا. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +لماذا هذه الخطوة حاسمة؟ فـ `OcrEngine` يجمع كل الإعدادات، حزم اللغات، وبيانات الترخيص. بدونها لا يمكنك معالجة الصور أو الاستعلام عن علم التجربة. + +> **ملاحظة جانبية:** بعض الـ SDK تسمح بتمرير كائن إعدادات إلى المُنشئ (مثل اللغة، DPI). إذا كنت بحاجة إلى إعدادات مخصصة، عدّل السطر وفقًا لذلك. + +## الخطوة 4: تحديد وضع تقييم محرك OCR + +معظم موردي OCR يوزعون نسخة تجريبية تعمل في **evaluation mode** حتى يتم توفير مفتاح ترخيص صالح. معرفة ما إذا كنت في وضع التجربة يتيح لك عرض إشارات UI مناسبة أو تقييد بعض الميزات. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +خاصية `IsEvaluation` تُعيد `true` عندما يكون المحرك غير مرخص أو يستخدم نسخة تجريبية محدودة الوقت. إنها طريقة سريعة وموثوقة لحماية الميزات المدفوعة. + +### ماذا لو كانت الخاصية غير موجودة؟ + +قد تُظهر إصدارات SDK القديمة طريقة مثل `GetLicenseInfo()` بدلاً من ذلك. في هذه الحالة، ستفحص الكائن المرجع عن علم `IsTrial`. دائمًا راجع سجل تغييرات الـ SDK عند الترقية. + +## الخطوة 5: عرض حالة الترخيص الحالية + +أخيرًا، لنظهر للمستخدم ما إذا كان المحرك مرخصًا أم لا يزال في وضع التجربة. سطر `Console.WriteLine` بسيط يكفي، ويمكنك تكييفه لتطبيقات GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +المعامل الثلاثي يبقي الكود منظمًا، والرسائل واضحة بما يكفي للمستخدم النهائي أو للمطورين الذين يقرؤون السجلات. + +## مثال كامل يعمل + +بجمع كل ما سبق، إليك برنامج مستقل يمكنك نسخه ولصقه في `Program.cs` وتشغيله باستخدام `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### النتيجة المتوقعة + +- **نسخة تجريبية:** + `Running in evaluation mode – limited functionality.` + +- **نسخة مرخصة:** + `Licensed – full OCR capabilities enabled.` + +إذا رمى الـ SDK استثناءً (مثل عدم وجود DLL أصلي)، سيطبع كتلة `catch` رسالة خطأ مفيدة بدلاً من تعطل التطبيق بالكامل. + +## معالجة الحالات الطرفية والأخطاء الشائعة + +### 1. كائنات محرك فارغة + +على الرغم من أن المُنشئ عادةً ما يُعيد كائنًا صالحًا، قد تُعيد بعض الـ SDK `null` إذا كانت الاعتمادات الأصلية مفقودة. احمِ نفسك من ذلك: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. انتهاء صلاحية الترخيص أثناء التشغيل + +قد تنتهي صلاحية الترخيص التجريبي أثناء الجلسة. أعد استدعاء `IsEvaluation` بشكل دوري إذا كان تطبيقك يبقى فعالًا لفترة طويلة. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. اختلاف أسماء الخصائص بين الإصدارات + +الإصدارات القديمة قد تُظهر `engine.EvaluationMode` أو `engine.License.IsTrial`. عند الترقية، ابحث في ملاحظات الإصدار عن تغييرات كسرية. + +### 4. السيناريوهات متعددة الخيوط + +إذا قمت بإنشاء عدة عمال OCR، أنشئ **one OCR engine per thread** ما لم يدعم الـ SDK مشاركة آمنة بين الخيوط صراحةً. مشاركة محرك واحد قد تؤدي إلى ظروف سباق وقراءات ترخيص غير صحيحة. + +## نصائح محترف للاستخدام في الإنتاج + +- **خزن حالة الترخيص** بعد الفحص الأول لتجنب استدعاءات الخصائص غير الضرورية. +- **سجّل مفتاح الترخيص** (مُخفى) عند بدء التشغيل لتوفير سجل تدقيق—يساعد فرق الدعم على تشخيص مشاكل الترخيص. +- **قدّم زر UI** يُخبر المستخدمين أنهم في وضع التجربة ويعرض زر “شراء الترخيص”. +- **أتمتة تجديد الترخيص** باستخدام API التفعيل المتوفر في الـ SDK، إذا كان موجودًا، لتوفير تجربة سلسة للمستخدم. + +## الخلاصة + +لقد **created OCR engine** في بضع أسطر فقط، فحصنا **OCR engine evaluation mode**، وطبعنا رسالة واضحة عن **OCR licensing status**. المثال الكامل يعمل فورًا، يتعامل مع الأخطاء بأناقة، ويوضح “السبب” وراء كل خطوة—حتى تتمكن من تكييفه لتطبيقات سطح المكتب، الويب، أو الخدمات الخلفية. + +الخطوات التالية قد تشمل: + +- تمرير الصور إلى `engine.Recognize` ومعالجة دعم متعدد اللغات. +- استخدام **check OCR license** APIs لتفعيل المفتاح المشتراة برمجيًا. +- دمجها مع أطر UI (WinForms، WPF، MAUI) لعرض شارات الترخيص. + +جرّب ذلك، وستحصل على أساس OCR قوي لأي تطبيق. برمجة سعيدة! + +## دروس ذات صلة + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/ocr-optimization/_index.md b/ocr/arabic/net/ocr-optimization/_index.md index 1ca8c92a0..35ed9add4 100644 --- a/ocr/arabic/net/ocr-optimization/_index.md +++ b/ocr/arabic/net/ocr-optimization/_index.md @@ -73,6 +73,7 @@ weight: 25 حسّن دقة OCR مع Aspose.OCR for .NET. صحّح الأخطاء الإملائية، خصّص القواميس، واحصل على نص خالٍ من الأخطاء بسهولة. ### [حفظ النتيجة متعددة الصفحات كمستند في التعرف على الصور باستخدام OCR](./save-multipage-result-as-document/) افتح إمكانات Aspose.OCR for .NET. احفظ نتائج OCR متعددة الصفحات كمستندات بسهولة من خلال هذا الدليل الشامل خطوة بخطوة. +### [معالجة الصورة مسبقًا للتعرف الضوئي على الأحرف – دليل كامل Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) ## الأسئلة المتكررة diff --git a/ocr/arabic/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/arabic/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..a75dccfa5 --- /dev/null +++ b/ocr/arabic/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: معالجة الصورة مسبقًا للتعرف الضوئي على الأحرف باستخدام Aspose لتحسين + دقة التعرف وتشغيل التعرف على ملفات JPEG. تعلم كيفية استخراج النص باستخدام Aspose + في دليل واضح خطوة بخطوة. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: ar +og_description: قم بتهيئة الصورة للتعرف الضوئي على الأحرف باستخدام Aspose لتعزيز دقة + التعرف. اتبع هذا الدليل لتشغيل التعرف الضوئي على الأحرف على ملفات JPEG واستخراج + النص باستخدام Aspose في C#. +og_title: معالجة مسبقة للصورة للتعرف الضوئي على الأحرف – دليل Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: معالجة الصورة مسبقًا للتعرف الضوئي على الأحرف – دليل Aspose C# الكامل +url: /ar/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# معالجة الصورة للتعرف الضوئي على الأحرف – دليل Aspose C# الكامل + +هل تساءلت يومًا كيف **معالجة الصورة للتعرف الضوئي على الأحرف** بحيث يخرج النص نظيفًا في كل مرة؟ لست وحدك—المطورون يواجهون باستمرار مسحًا ضوضائيًا، صور JPEG منخفضة التباين، وإضاءة غير متوقعة. الخبر السار؟ مع بعض التعديلات الذكية يمكنك **تحسين دقة التعرف الضوئي على الأحرف** بشكل كبير، وAspose يجعل العملية سهلة. + +في هذا الدرس سنستعرض مثالًا واقعيًا يوضح لك كيفية **تشغيل التعرف الضوئي على الأحرف على JPEG**، تطبيق خط أنابيب مخصص لمعالجة الصور، وأخيرًا **استخراج النص باستخدام Aspose**. في النهاية ستحصل على مقطع C# جاهز للنسخ يمكنك وضعه في أي مشروع .NET. + +## ما ستتعلمه + +- لماذا تهم المعالجة المسبقة وأي الفلاتر تعطي أكبر فائدة. +- كيفية تكوين `ImageProcessingOptions` في Aspose.OCR لتصحيح الميل، إزالة الضوضاء، التحويل إلى ثنائي، وتعزيز التباين. +- الكود الدقيق المطلوب **لتشغيل التعرف الضوئي على الأحرف على ملفات JPEG** واسترجاع نص نظيف. +- نصائح ومخاطر تساعد على إبقاء خط أنابيب التعرف الضوئي على الأحرف قويًا في بيئة الإنتاج. + +لا تحتاج إلى خبرة سابقة مع Aspose؛ فقط خلفية أساسية في C# وVisual Studio (أو بيئة التطوير المفضلة لديك). لنبدأ. + +![مثال على معالجة الصورة للتعرف الضوئي على الأحرف](preprocess-ocr.png "معالجة الصورة للتعرف الضوئي على الأحرف") + +## الخطوة 1: إعداد محرك Aspose.OCR – معالجة الصورة للتعرف الضوئي على الأحرف + +أولاً وقبل كل شيء. نحتاج إلى كائن `OcrEngine` ويجب أن نخبره بأي لغة نتوقعها. في معظم الحالات تكون الإنجليزية هي الافتراضية، لكن يمكنك استبدالها بالفرنسية أو الألمانية، إلخ، عن طريق تغيير تعداد `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**لماذا هذا مهم:** المحرك هو قلب العملية؛ بدونّه لا يمكنك تطبيق أي من فلاتر الصورة التي تقوم فعليًا **بمعالجة الصورة للتعرف الضوئي على الأحرف**. فكر فيه كالمطبخ حيث تُخلط جميع المكونات. + +## الخطوة 2: بناء خط أنابيب مخصص لمعالجة الصور – تحسين دقة التعرف الضوئي على الأحرف + +الآن يأتي الجزء الشهي. يتيح لك Aspose ربط عدة فلاتر معًا. أدناه نفعّل أربعة من أكثرها فعالية: + +1. **Deskew** – يسطّح المستندات المائلة (الحد الأقصى 5° افتراضيًا). +2. **Denoise** – ينعّم الخلفيات المحببة للضوضاء. +3. **Binarize** – يحول الصورة إلى أبيض وأسود باستخدام عتبة. +4. **ContrastBoost** – يجعل الأحرف الخفيفة تبرز. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**نصيحة احترافية:** إذا كانت صورك المصدرية واضحة بالفعل، يمكنك خفض قيمة `Strength` أو إيقاف تشغيل فلتر بالكامل. المعالجة الزائدة قد تمحو الأحرف الخفيفة أحيانًا، لذا جرب مع عينات حقيقية. + +## الخطوة 3: تحميل ملف JPEG (أو أي صورة) وتشغيل التعرف الضوئي على الأحرف – تشغيل التعرف الضوئي على الأحرف على JPEG + +يعمل Aspose مع أي تنسيق صورة يمكن لـ .NET قراءته—JPEG، PNG، BMP، إلخ. إليك كيفية تمرير ملف JPEG إلى المحرك وبدء عملية التعرف. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**لماذا JPEG؟** غالبًا ما تُدخل ضغط JPEG عيوبًا تُربك محرك التعرف. خط أنابيب المعالجة المسبقة لدينا، خاصةً خطوات إزالة الضوضاء والتحويل إلى ثنائي، يخفف هذه المشكلات، مما يتيح لك **تشغيل التعرف الضوئي على الأحرف على JPEG** بثقة. + +## الخطوة 4: إخراج النص المعترف به – استخراج النص باستخدام Aspose + +أخيرًا، نكتب النص إلى وحدة التحكم، ملف، أو أي خدمة لاحقة. لأغراض العرض، وحدة التحكم كافية. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +عند تشغيل البرنامج، يجب أن ترى شيئًا مثل: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +إذا كان الإخراج مشوشًا، عد إلى **الخطوة 2** واضبط إعدادات الفلاتر. التعديلات الصغيرة غالبًا ما تحقق تحسينات كبيرة في **تحسين دقة التعرف الضوئي على الأحرف**. + +## الحالات الشائعة وكيفية التعامل معها + +| الحالة | التعديل المقترح | +|-----------|----------------------| +| **صور داكنة جدًا** | زيادة `ContrastBoost.Level` إلى 1.5 أو أعلى. | +| **ميل > 5°** | رفع `DeskewOptions.MaxAngle` (مثلاً 10.0) أو تدوير الصورة يدويًا مسبقًا. | +| **نص ملون على خلفية ملونة** | استخدام `BinarizeOptions` مع عتبة مخصصة أو التحويل إلى `AdaptiveBinarizeOptions`. | +| **ملفات كبيرة ( > 5 MB )** | تحميل الصورة إلى `MemoryStream` أولاً لتجنب مشاكل قفل الملف. | + +هذه التعديلات تحافظ على مرونة خط الأنابيب وتجعله مستقبليًا، خاصةً عندما تحتاج إلى **استخراج النص باستخدام Aspose** من مصادر متنوعة. + +## مثال كامل يعمل – جميع الخطوات في مكان واحد + +فيما يلي البرنامج الكامل جاهز للنسخ واللصق. يتوافق مع .NET 6+ ويتطلب حزمة NuGet `Aspose.OCR` فقط. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +احفظه باسم `Program.cs`، أضف حزمة Aspose.OCR (`dotnet add package Aspose.OCR`)، ثم شغّل `dotnet run`. سترى النص المنقح يُطبع على وحدة التحكم. + +## ملخص – لماذا يعمل هذا النهج + +- **معالجة الصورة للتعرف الضوئي على الأحرف**: يزيل خط الأنابيب أكثر مصادر الأخطاء شيوعًا (الميل، الضوضاء، انخفاض التباين). +- **تحسين دقة التعرف الضوئي على الأحرف**: كل فلتر مُضبط لتعزيز نسبة الإشارة إلى الضوضاء التي يراها المحرك. +- **تشغيل التعرف الضوئي على الأحرف على JPEG**: حتى الصور المضغوطة تصبح قابلة للقراءة بعد تصحيح الميل والتحويل إلى ثنائي. +- **استخراج النص باستخدام Aspose**: تُعيد طريقة `Recognize` سلسلة نصية عادية، جاهزة لأي منطق لاحق. + +معًا، تمنحك هذه الخطوات حل OCR موثوقًا ومناسبًا للإنتاج في بضع أسطر فقط. + +## الخطوات التالية والمواضيع ذات الصلة + +- **معالجة دفعات** – التكرار على مجلد من الصور وكتابة كل نتيجة إلى ملف `.txt`. +- **حزم اللغات** – استبدال `OcrLanguage.English` بـ `OcrLanguage.Spanish` أو إضافة قواميس مخصصة. +- **استخراج PDF** – دمج Aspose.OCR مع Aspose.PDF لاستخراج النص مباشرةً من ملفات PDF الممسوحة. +- **تحسين الأداء** – تشغيل المحرك بالتوازي باستخدام `Parallel.ForEach` لأحمال عمل كبيرة. + +لا تتردد في تجربة قيم الفلاتر، تجربة تنسيقات صور مختلفة، أو ربط فلاتر Aspose إضافية مثل `SharpnessOptions`. السماء هي الحد عندما تتقن الأساسيات. + +--- + +*برمجة سعيدة! إذا واجهت أي مشاكل، اترك تعليقًا أدناه وسنقوم بحلها معًا.* + +## دروس ذات صلة + +- [معالجة صورة OCR باستخدام فلاتر Aspose.OCR لـ .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [استخراج النص من الصورة – تحسين 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/text-recognition/_index.md b/ocr/arabic/net/text-recognition/_index.md index 58e5dde95..848293793 100644 --- a/ocr/arabic/net/text-recognition/_index.md +++ b/ocr/arabic/net/text-recognition/_index.md @@ -52,12 +52,27 @@ url: /ar/net/text-recognition/ ### [وضع اكتشاف المناطق بتقنية التعرف الضوئي على الحروف (OCR) في التعرف على الصور بتقنية التعرف الضوئي على الحروف (OCR).](./ocr-detect-areas-mode/) قم بتحسين تطبيقات .NET الخاصة بك باستخدام Aspose.OCR للتعرف الفعال على نص الصورة. استكشف وضع مناطق اكتشاف التعرف الضوئي على الحروف (OCR) للحصول على نتائج دقيقة. ### [التعرف على PDF في التعرف على الصور OCR](./recognize-pdf/) -أطلق العنان لإمكانات التعرف الضوئي على الحروف في .NET باستخدام Aspose.OCR. استخراج النص من ملفات PDF دون عناء. قم بالتنزيل الآن للحصول على تجربة تكامل سلسة. +أطلق العنان لإمكانات التعرف الضوئي على الحروف في .NET باستخدام Aspose.OCR. استخراج النص من ملفات PDF دون عناء. قم بتنزيل الآن للحصول على تجربة تكامل سلسة. ### [التعرف على الجدول في التعرف على الصور OCR](./recognize-table/) أطلق العنان لإمكانات Aspose.OCR لـ .NET من خلال دليلنا الشامل حول التعرف على الجداول في التعرف على الصور باستخدام OCR. +### [التعرف على النص من صورة باستخدام Aspose OCR – دليل C# كامل](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +دليل شامل لاستخدام Aspose OCR مع C# لاستخراج النص من الصور بسهولة. +### [استخراج النص من صورة باستخدام C# – دليل كامل لـ Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +دليل شامل لاستخدام Aspose OCR مع C# لاستخراج النص من الصور بسهولة ودقة. +### [كيفية استخدام OCR في C# – التعرف على النص الصيني من JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +تعلم خطوة بخطوة كيفية استخدام Aspose.OCR مع C# لاستخراج النص الصيني من ملفات JPG بدقة وسهولة. +### [التعرف على النص الروسي باستخدام OCR في C# – دليل كامل باستخدام Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +دليل شامل لاستخدام Aspose OCR مع C# لاستخراج النص الروسي من الصور بسهولة ودقة. +### [استخراج النص من صورة في ASP.NET Core Minimal API – دليل كامل](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +دليل شامل لاستخدام ASP.NET Core Minimal API لاستخراج النص من الصور بسهولة ودقة. +### [دروس OCR بلغة C#: استخراج النص من إيصالات PNG باستخدام Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +تعلم كيفية استخراج النص من إيصالات PNG باستخدام Aspose OCR في C# خطوة بخطوة. +### [تحويل TIFF إلى نص في C# – دليل OCR دفعي كامل](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +تعلم كيفية تحويل ملفات TIFF إلى نص باستخدام 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/arabic/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/arabic/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..50030e21a --- /dev/null +++ b/ocr/arabic/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: دروس OCR بلغة C# تُظهر كيفية تحميل ملف صورة C# والتعرف على نص PNG من + إيصال باستخدام Aspose OCR – دليل خطوة بخطوة. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: ar +og_description: دروس OCR بلغة C# التي ترشدك خلال تحميل ملف صورة C# والتعرف على نص + PNG من إيصال باستخدام Aspose OCR. +og_title: دورة OCR بلغة C# – استخراج النص من إيصالات PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'دورة OCR بلغة C#: استخراج النص من إيصالات PNG باستخدام Aspose' +url: /ar/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# دليل c# OCR – استخراج النص من إيصالات PNG باستخدام Aspose + +هل احتجت إلى **دليل c# OCR** ينجز المهمة فعلاً دون الحاجة للبحث المستمر على جوجل؟ أنت في المكان الصحيح. في هذا الدليل سنقوم بـ **تحميل ملف صورة c#**، **التعرف على نص PNG**، و **قراءة نتائج OCR للإيصال**، كل ذلك مع إظهار كيفية **أداء معالجة صورة OCR** باستخدام Aspose OCR. + +سنبدأ بتثبيت حزمة NuGet المطلوبة، نتناول كل سطر من الشيفرة، وننتهي بتفريغ JSON مرتب يمكنك تمريره مباشرة إلى خط أنابيب البيانات التالي. لا إطالة، مجرد حل عملي جاهز للتنفيذ. + +## ما ستتعلمه + +- كيفية إعداد Aspose OCR في مشروع .NET 6 (أو أحدث). +- الخطوات الدقيقة لـ **تحميل ملف صورة c#** وتمريره إلى المحرك. +- كيفية **التعرف على نص PNG** من صورة إيصال والتقاط النتيجة. +- طرق **قراءة OCR للإيصال** كـ JSON منسق بشكل جميل. +- نصائح لـ **أداء معالجة صورة OCR** على أنواع ملفات مختلفة ومعالجة المشكلات الشائعة. + +**المتطلبات المسبقة** +- Visual Studio 2022 (أو أي بيئة تطوير تفضلها). +- .NET 6 SDK أو أحدث. +- صورة إيصال بصيغة PNG جاهزة (سنسميها `receipt.png`). + +إذا كان لديك هذه المتطلبات، لنبدأ. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## دليل c# OCR – إعداد محرك Aspose OCR + +أولاً، نحتاج إلى مكتبة Aspose OCR. افتح الطرفية في مجلد الحل وشغّل الأمر التالي: + +```bash +dotnet add package Aspose.OCR +``` + +هذا الأمر الواحد يجلب كل ما يلزم، بما في ذلك الثنائيات الأصلية لفك ترميز الصور. بعد التثبيت، أنشئ مشروع console جديد أو أضف الشيفرة إلى مشروع موجود. + +### لماذا Aspose؟ + +Aspose OCR يدعم أكثر من 30 لغة، يعمل دون اتصال بالإنترنت، ويعيد كائن `OcrResult` غني—مثالي لمهام **أداء معالجة صورة OCR** حيث تحتاج إلى أكثر من مجرد نص عادي. + +## تحميل ملف صورة c# وتحضير الإيصال + +الآن بعد أن أصبحت المكتبة جاهزة، لنقم بـ **تحميل ملف صورة c#**. فئة `System.Drawing.Image` تقوم بالعمل الشاق، لكن يمكنك أيضاً استخدام `SkiaSharp` إذا كنت تفضل بديلًا متعدد المنصات. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **نصيحة احترافية:** ضع الـ `Image` داخل عبارة `using` (كما هو موضح) لتحرير الموارد الأصلية بسرعة—وهذا مهم خاصةً عندما تقوم بـ **أداء معالجة صورة OCR** على العديد من الملفات داخل حلقة. + +## التعرف على نص PNG باستخدام Aspose + +مع الصورة في الذاكرة، يمكن للمحرك الآن **التعرف على نص PNG**. Aspose يعيد كائن `OcrResult` يحتوي على السلسلة الخام وبيانات مفصلة عن كل كلمة تم التعرف عليها. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +لماذا نستدعي `RecognizeWithResult` بدلاً من `Recognize` الأبسط؟ الأول يمنحك إمكانية الوصول إلى درجات الثقة، الصناديق المحيطة، وفواصل الأسطر—مفيد إذا احتجت لاحقًا إلى **قراءة OCR للإيصال** لاستخراج بنود الفاتورة. + +## قراءة نتيجة OCR للإيصال كـ JSON + +معظم الأنظمة المت downstream تفضل JSON، لذا لنقوم بتسلسل `OcrResult`. مُسلسل `System.Text.Json` يتعامل مع الكائنات المعقدة بسلاسة، وسنُفعّل المسافات البادئة للقراءة السهلة. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +الناتج JSON يبدو تقريبًا هكذا (مقتطع للاختصار): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +يمكنك الآن تمرير `jsonResult` إلى قاعدة بيانات، طابور رسائل، أو ببساطة تسجيله للتصحيح. + +## أداء معالجة صورة OCR وعرض النتيجة + +أخيرًا، نطبع الـ JSON على وحدة التحكم. في تطبيق واقعي قد تكتبها إلى ملف أو ترسلها عبر HTTP، لكن وحدة التحكم تجعل من السهل التحقق من أن كل شيء يعمل. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +شغّل البرنامج (`dotnet run`) وسترى الـ JSON المنسق يُطبع. إذا كانت صورة الإيصال واضحة، سيكون النص دقيقًا؛ إذا لم يكن كذلك، فكر في زيادة دقة الصورة أو تطبيق فلتر تمهيدي (مثل تحويل إلى تدرج رمادي، تعزيز التباين) قبل إرساله إلى المحرك. + +### التعامل مع الحالات الشائعة + +| الحالة | ما الذي يجب فعله | +|-----------|------------| +| **الصورة غير واضحة** | قم بتمهيدها باستخدام `System.Drawing` لتوضيحها أو زيادة DPI. | +| **الإيصال يحتوي على لغات متعددة** | عيّن `ocrEngine.Language = OcrLanguage.English \| OcrLanguage.Spanish;` | +| **معالجة دفعات كبيرة** | أعد استخدام كائن `OcrEngine` واحد؛ غير الـ `Image` فقط في كل دورة. | +| **ضغط الذاكرة** | حرّر كائنات `Image` فورًا وفكّر في استخدام `await Task.Run` للخطوط غير المتزامنة. | + +هذه التعديلات تحافظ على سير عمل **أداء معالجة صورة OCR** قوي حتى عندما لا تكون المدخلات مثالية. + +## الخلاصة + +تهانينا—لقد أكملت **دليل c# OCR** الذي يحمل صورة، **يتعرف على نص PNG**، و **يقرأ نتيجة OCR للإيصال** كـ JSON نظيف. الخطوات الأساسية (إعداد المحرك، تحميل الصورة، تنفيذ OCR، التسلسل، والعرض) تشكل أساسًا صلبًا يمكنك توسيعه لتشمل الفواتير، جوازات السفر، أو أي مستند ممسوح ضوئيًا آخر. + +### ما التالي؟ + +- جرّب **تحميل ملف صورة c#** باستخدام `SkiaSharp` لدعم متعدد المنصات حقيقي. +- تعمق في `OcrResult.Words` لاستخراج بنود الفاتورة، الأسعار، والتواريخ—مثالي لتطبيقات تتبع النفقات. +- اجمع هذا الدليل مع Azure Functions أو AWS Lambda لبناء API لمعالجة الإيصالات بدون خادم. + +لا تتردد في تعديل الشيفرة، إضافة المزيد من الصور، أو حتى تغيير حزمة اللغة. عالم OCR مليء بالمفاجآت، والآن لديك الأدوات لاستكشافها. + +برمجة سعيدة، ولتظل إيصالاتك دائمًا قابلة للقراءة! + +## دروس ذات صلة + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Use OCR - Recognize Image without Text Area Detection](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/arabic/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..e877e84ca --- /dev/null +++ b/ocr/arabic/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-05-25 +description: تحويل ملفات TIFF إلى نص باستخدام Aspose.OCR في C#. تعلم تحويل الصور إلى + نص على دفعات واستخراج النص من ملفات TIFF بكفاءة. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: ar +og_description: تحويل ملفات TIFF إلى نص باستخدام Aspose.OCR. يوضح هذا الدليل تحويل + الصور إلى نص على دفعات وكيفية استخراج النص من ملفات TIFF ببضع أسطر من C#. +og_title: تحويل ملفات TIFF إلى نص في C# – دليل OCR كامل للمعالجة الدفعية +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: تحويل TIFF إلى نص في C# – دليل OCR كامل للدفعات +url: /ar/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# تحويل TIFF إلى نص في C# – دليل OCR دفعي كامل + +هل احتجت يوماً إلى **تحويل TIFF إلى نص** ولكن لم تعرف من أين تبدأ؟ لست وحدك—العديد من المطورين يواجهون صعوبات مع OCR الدفعي عند التعامل مع المستندات الممسوحة. في هذا الدرس سنستعرض حلًا عمليًا **يستخرج النص من ملفات TIFF** باستخدام Aspose.OCR، وسنقوم بذلك بشكل متوازي بحيث تنتهي معالجة المجلدات الكبيرة في ثوانٍ. + +سنتطرق أيضًا إلى أفضل الممارسات لـ **تحويل دفعة من الصور إلى نص**، حتى تحصل في النهاية على مقتطف قابل لإعادة الاستخدام يحول دليلًا كاملاً من الصور الممسوحة إلى ملفات *.txt* مرتبة—مثالي للفهرسة، البحث، أو إدخاله في تحليلات لاحقة. + +## ما ستحتاجه + +- **.NET 6.0** أو أحدث (الكود يُجمّع أيضًا على .NET Framework) +- حزمة NuGet **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- مجلد يحتوي على ملف أو أكثر بصيغة *.tif* (صيغة المسح الكلاسيكية TIFF) +- بيئة التطوير المفضلة لديك (Visual Studio، VS Code، Rider—أيًا كان) + +هذا كل شيء. لا خدمات خارجية، لا مفاتيح API، فقط C# صافية وAspose. + +![لقطة شاشة لملف TIFF يتم معالجته والملف النصي الناتج](/images/ocr-result.png "نتيجة OCR تُظهر تحويل TIFF إلى نص") + +*(نص بديل: لقطة شاشة تُظهر تحويل TIFF إلى نص على الشاشة)* + +## الخطوة 1: إعداد محرك OCR – تحويل TIFF إلى نص + +أولاً، نحتاج إلى إنشاء كائن `OcrEngine` يعرف أنه يجب قراءة الأحرف الإنجليزية. المحرك هو قلب عملية التحويل؛ ضبطه بشكل صحيح يضمن نتائج موثوقة. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*لماذا هذا مهم:* +يدعم Aspose.OCR عشرات اللغات. إذا كنت تتعامل مع مسحات متعددة اللغات، ما عليك سوى تغيير `OcrLanguage.English` إلى القيمة المناسبة من الـ enum. ترك اللغة غير محددة يجعل المحرك يعمل في وضع الكشف التلقائي، مما قد يكون أبطأ وأقل دقة. + +## الخطوة 2: جمع جميع ملفات TIFF – استخراج النص من TIFF بكفاءة + +الآن نجلب كل ملف *.tif* من المجلد الذي تحدده. استخدام `Directory.GetFiles` يمنحنا مصفوفة نظيفة يمكن تمريرها إلى معالج الدفعة. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*نصيحة احترافية:* يمكن استخدام العلم `SearchOption.AllDirectories` إذا كانت مسحاتك متداخلة في مجلدات فرعية. فقط تذكر أن التعمق قد يزيد من استهلاك الذاكرة أثناء خطوة الدفعة. + +## الخطوة 3: تنفيذ OCR المتوازي – تحويل دفعة من الصور إلى نص + +الجزء الممتع الآن. يأتي Aspose.OCR بمساعد ثابت `BatchOcr.RecognizeAll` يقبل مصفوفة من مسارات الملفات، محركًا، وتلميح `parallelism`. سننشئ أربعة خيوط، وهو ما يمنح جهاز لابتوب رباعي النواة تسارعًا شبه خطي. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*لماذا التوازي؟* +معالجة دفعة من ملفات TIFF عالية الدقة يمكن أن تكون مكثفة على المعالج. بتوزيع العمل على عدة خيوط نبقي جميع الأنوية مشغولة، مما يقلل زمن التنفيذ بشكل كبير. إذا نفذت هذا على خادم بعدد أكبر من الأنوية، زد قيمة `parallelism` وفقًا لذلك. + +## الخطوة 4: كتابة المخرجات – تحويل الصور الممسوحة إلى ملفات TXT + +أخيرًا نمر على القاموس ونكتب كل نص في ملف *.txt* يحمل نفس الاسم الأساسي الأصلي. هذه هي اللحظة التي يصبح فيها **convert scanned images txt** حقيقة واقعة. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### ما يفعله الكود، بلغة بسيطة + +1. **إنشاء** محرك OCR مخصص للإنجليزية. +2. **جمع** كل ملفات TIFF من المجلد المستهدف. +3. **تشغيل** `BatchOcr.RecognizeAll` بأربعة خيوط، محولًا كل صورة إلى سلسلة نصية. +4. **التكرار** على النتائج، استبدال امتداد `.tif` بـ `.txt` وكتابة السلسلة إلى القرص. + +بهذا تكون قد أكملت سير عمل **convert TIFF to text** في أقل من 50 سطرًا من الكود. + +## التعامل مع الحالات الخاصة – عندما لا تسير الأمور بسلاسة + +- **ملفات TIFF مفقودة أو تالفة** – سيُطلق `BatchOcr` استثناءً من نوع `OcrException`. احيط الاستدعاء بـ `try / catch` إذا أردت معالجة الأخطاء برفق. +- **مستندات غير إنجليزية** – غيّر `OcrLanguage.English` إلى `OcrLanguage.Spanish` أو `OcrLanguage.French`، إلخ، أو استخدم `OcrLanguage.AutoDetect`. +- **صور كبيرة جدًا** – فكر في خفض DPI قبل OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) لتقليل استهلاك الذاكرة، مع احتمال فقدان بعض الدقة. +- **ترميز الإخراج** – إذا كنت بحاجة إلى صفحة ترميز محددة (مثل Windows‑1252)، مرّرها إلى `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## نصائح احترافية لتحويلات دفعية قوية + +- **سجّل الأخطاء**: أنشئ `List failedFiles` وأضف أي ملف يسبب استثناء؛ اكتب القائمة إلى سجل بعد الحلقة. +- **أعد استخدام المحرك**: يمكن إعادة استعمال نفس كائن `OcrEngine` عبر ملفات متعددة؛ لا تنشئه داخل الحلقة. +- **تحقق من النتيجة**: فحص سريع `if (string.IsNullOrWhiteSpace(extractedText))` يمكنه اكتشاف المسحات الفارغة أو غير القابلة للقراءة. +- **دمج مع PDF**: إذا كان المصدر PDF متعدد الصفحات، حوّل كل صفحة إلى TIFF أولاً (Aspose.PDF يقوم بذلك) ثم نفّذ هذه الدفعة. + +## الخطوات التالية – تجاوز التحويل البسيط + +الآن بعد أن أصبحت قادرًا على **استخراج النص من ملفات TIFF** دفعيًا، قد ترغب في: + +- إدخال ملفات *.txt* في فهرس بحث (Elasticsearch، Azure Cognitive Search). +- تشغيل كشف اللغة على كل نتيجة لتوجيه المستندات إلى خطوط معالجة مخصصة حسب اللغة. +- إنشاء ملفات PDF قابلة للبحث عبر دمج نص OCR مرة أخرى فوق الصور الأصلية (Aspose.PDF مرة أخرى). + +جميع هذه السيناريوهات تبني على الفكرة الأساسية: **batch image to text conversion** هو حجر الأساس لأنظمة معالجة المستندات الأكبر. + +--- + +### الخلاصة + +لقد تعلمت الآن كيفية **تحويل TIFF إلى نص** باستخدام Aspose.OCR، معالجة مجلد كامل بشكل متوازي، وحفظ كل نتيجة كملف *.txt* نظيف. الحل خفيف، قابل للتكوين بالكامل، وجاهز للإنتاج—سواء كنت تقوم برقمنة فواتير قديمة، أرشفة عقود ممسوحة، أو تشغيل محرك بحث نصي. + +جرّبه، عدّل قيمة التوازي، وابدأ في تغذية تلك الملفات النصية الجديدة في أي سير عمل تحتاجه. نتمنى لك OCR موفق! + +--- + +## دروس ذات صلة + +- [استخراج النص من الصور باستخدام عملية OCR على المجلدات](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [استخراج النص من الصورة – تحسين 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/arabic/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..164be318d --- /dev/null +++ b/ocr/arabic/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: تعلم كيفية استخراج النص من الصورة باستخدام واجهة برمجة تطبيقات ASP.NET Core + بسيطة. حمّل الصورة عبر طلب POST، واقرأ بيانات النموذج المتعدد الأجزاء، ثم نفّذ تقنية + OCR على الصورة. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: ar +og_description: استخراج النص من الصورة باستخدام واجهة برمجة تطبيقات ASP.NET Core Minimal. + يوضح هذا الدليل كيفية تحميل الصورة عبر POST، وقراءة بيانات النموذج المتعدد الأجزاء، + وإجراء OCR على الصورة. +og_title: استخراج النص من الصورة في ASP.NET Core – خطوة بخطوة +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: استخراج النص من الصورة في ASP.NET Core Minimal API – دليل كامل +url: /ar/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استخراج النص من الصورة في ASP.NET Core Minimal API – دليل كامل + +هل تساءلت يومًا كيف **استخراج النص من الصورة** دون التعامل مع أطر عمل ضخمة؟ أنت لست وحدك. يحتاج العديد من المطورين إلى طريقة سريعة لتمكين المستخدمين من إلقاء صورة والحصول على الأحرف الخام، سواء كان ذلك لمسح الفواتير، أو تحويل الملاحظات المكتوبة يدويًا إلى نص، أو تعزيز فهرس بحث. + +في هذا الدرس سننشئ API Minimal صغير باستخدام ASP.NET Core يقوم **برفع الصورة عبر POST**، ويحلل حمولة *multipart/form‑data*، ثم **يُجري OCR على الصورة** باستخدام كائن `OcrEngine` أحادي. في النهاية ستحصل على تطبيق جاهز للتشغيل يمكنك إدراجه في أي مشروع .NET 8 والبدء في استخراج النص من الصورة فورًا. + +## ما ستبنيه + +- تطبيق ويب بسيط يستمع على `/ocr`. +- نقطة نهاية تقبل ملف صورة يُرسل عبر طلب POST من نوع `multipart/form-data`. +- منطق يقرأ الملف المرفوع، يمرره إلى محرك OCR، ويعيد النتائج كنص عادي. +- مقتطف تسريع GPU اختياري (مُعَلَّق) لأولئك الذين لديهم بطاقة متوافقة. + +**المتطلبات المسبقة** +- .NET 8 SDK (أو أحدث). +- إلمام أساسي بـ C# وسطر الأوامر. +- مكتبة OCR تُوفر فئة `OcrEngine` (العينة تفترض حزمة NuGet افتراضية). + +إذا كان لديك ذلك، لنبدأ. + +## الخطوة 1: إعداد المشروع وإضافة حزمة OCR + +First, create a new web project and pull in the OCR library. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **نصيحة احترافية:** حافظ على تحديث تبعياتك. غالبًا ما تجلب الإصدارات الأحدث تحسينات في الأداء، خاصةً في الاستدلال المدعوم بـ GPU. + +## الخطوة 2: تسجيل محرك OCR أحادي (الخدمة الأساسية) + +We want a single `OcrEngine` instance for the whole app—no need to spin up a new engine per request. Register it in the builder’s service container. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**لماذا أحادي؟** +إنشاء محرك OCR قد يكون مكلفًا—فكر في تحميل أوزان الشبكة العصبية إلى الذاكرة. بإعادة استخدام نفس المثيل نوفر دورات CPU والذاكرة، مما يترجم إلى أوقات استجابة أسرع لكل طلب `/ocr`. + +## الخطوة 3: بناء التطبيق + +Now we materialize the `WebApplication` object. + +```csharp +var app = builder.Build(); +``` + +That line looks almost magical, but under the hood it wires up routing, middleware, and the DI container we just configured. + +## الخطوة 4: تعريف نقطة النهاية POST – “رفع صورة عبر POST” + +Here’s the heart of the tutorial: an endpoint that **upload image via POST**, reads the multipart payload, and hands the data to the OCR engine. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### تفصيل المنطق + +| الخطوة | ما يحدث | لماذا يهم | +|------|--------------|----------------| +| **ReadFormAsync** | يقوم بتحليل طلب *multipart/form-data* الوارد. | بدون ذلك، لا يمكنك الوصول إلى الملفات المرفوعة. | +| **form.Files["image"]** | يسترجع الملف الذي اسم حقل النموذج الخاص به هو `image`. | يضمن عقدًا متوقعًا للمتصلين. | +| **Content‑type check** | يتحقق من أن الملف صورة (مثال: `image/png`). | يمنع محرك OCR من الفشل عند بيانات غير صورة. | +| **Image.FromStream** | يحول الدفق الخام إلى كائن `System.Drawing.Image`. | مكتبة OCR تتوقع كائن `Image`، وليس مصفوفة بايتات خام. | +| **ocr.Recognize(img)** | يستدعي محرك OCR **لتعرف النص من الصورة**. | هذه هي خطوة **إجراء OCR على الصورة** الأساسية. | +| **Results.Text** | يرسل استجابة النص العادي. | تنسيق بسيط وقابل للاستهلاك للخدمات اللاحقة. | + +## الخطوة 5: تشغيل الـ API + +Finally, start the web server. + +```csharp +app.Run(); +``` + +When you execute `dotnet run`, the API will listen on `http://localhost:5000` (or a port of your choosing). You can test it with `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**الناتج المتوقع:** سيطبع الكونسول الأحرف التي تم التعرف عليها، مثال: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +If the image is blurry or the language isn’t supported, the OCR engine will return an empty string or an error message—handle those cases in production code. + +## الحالات الحدية وأفضل الممارسات + +### 1. ملفات كبيرة + +The default request body limit is 30 MB. For larger scans you might need to adjust: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR غير متزامن + +Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the lambda as `async`. + +### 3. اعتبارات الأمان + +- **تحقق من حجم الملف** قبل تحميله إلى الذاكرة. +- **نقّح اسم الملف** إذا قررت حفظه على القرص. +- **حدّ من معدل الطلبات** لتجنب هجمات حجب الخدمة. + +### 4. تسريع GPU + +If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially on high‑resolution images. + +## مثال كامل يعمل + +Below is the complete `Program.cs` you can copy‑paste into a fresh Minimal API project. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Save, run `dotnet run`, and you’re ready to **extract text from image** on demand. + +## الخلاصة + +We’ve walked through a **complete, end‑to‑end solution** for extracting text from image using ASP.NET Core Minimal API. Starting from project scaffolding, we **registered a singleton OCR engine**, built an endpoint that **uploads image via POST**, **read multipart form data**, and finally **perform OCR on image** to return clean plain‑text. + +From here you can: + +- إضافة أغلفة JSON لاستجابات أغنى. +- ربط قاعدة بيانات لتخزين النص المستخرج. +- توسيع الدعم لعدة لغات (`OcrLanguage.Spanish`, إلخ). + +النمط يتوسع بسهولة—فقط أضف نفس نقطة النهاية إلى خدمة مصغرة أكبر أو عرّضها عبر بوابة API. + +هل لديك أسئلة حول معالجة ملفات PDF، أو المعالجة الدفعية، أو ضبط GPU؟ اترك تعليقًا، وبرمجة سعيدة! + +## دروس ذات صلة + +- [استخراج النص من الصورة باستخدام 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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/arabic/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..68262641a --- /dev/null +++ b/ocr/arabic/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: استخراج النص من الصورة باستخدام C# و Aspose OCR. تعلم كيفية تحويل JPG + إلى نص، تحميل الصورة للتعرف الضوئي على الأحرف، والحصول على نتائج موثوقة بسرعة. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: ar +og_description: استخراج النص من الصورة باستخدام C#. يوضح هذا الدليل كيفية تحويل JPG + إلى نص، تحميل الصورة للتعرف الضوئي على الأحرف، ومعالجة المحتوى متعدد اللغات. +og_title: استخراج النص من الصورة في C# – دليل Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: استخراج النص من الصورة في C# – دليل Aspose OCR الكامل +url: /ar/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# استخراج النص من الصورة في C# – دليل Aspose OCR الكامل + +هل تساءلت يومًا كيف **extract text from image** باستخدام كود C# بسيط؟ لست وحدك. سواءً كنت تقوم برقمنة الإيصالات، أو مسح اللوحات الإعلانية، أو مجرد فضول حول OCR، فإن القدرة على استخراج الأحرف من صورة هي مهارة مفيدة. في هذا الدرس سنستعرض مثالًا كاملاً قابلاً للتنفيذ يوضح بالضبط كيف **extract text from image** باستخدام Aspose.OCR، وسنغطي أيضًا كيفية **convert jpg to text**، **load image for OCR**، والإجابة على سؤال “**how to ocr image**” الشهير مرة واحدة وإلى الأبد. + +بنهاية هذا الدليل ستحصل على تطبيق console مستقل يقرأ ملف JPEG، ويتعرف على اللغة الأوكرانية (أو أي لغة مدعومة أخرى)، ويطبع النتيجة على وحدة التحكم. لا مراجع غامضة، لا أجزاء مفقودة—فقط حل كامل يمكنك نسخه ولصقه وتشغيله. + +--- + +## ما ستتعلمه + +* كيفية تثبيت حزمة Aspose.OCR عبر NuGet. +* الكود الدقيق اللازم **load image for OCR** في C#. +* كيفية تعيين اللغة واستخراج النص فعليًا **extract text from image**. +* حيل لتحويل **convert jpg to text** بكفاءة. +* المشكلات الشائعة وكيفية تجنبها. + +إذا كان لديك بيئة تطوير .NET مُعدّة بالفعل، فأنت جاهز للغوص. وإلا، سيوفر لك قسم المتطلبات المسبقة أدناه كل ما تحتاجه. + +--- + +## المتطلبات + +| المتطلبات | لماذا يهم | +|-------------|----------------| +| .NET 6.0 SDK (أو أحدث) | يوفر بيئة التشغيل لتطبيق console. | +| Visual Studio 2022 أو VS Code | يجعل التحرير وتصحيح الأخطاء أسهل. | +| اتصال بالإنترنت (في التشغيل الأول) | يحتاج NuGet إلى تنزيل Aspose.OCR. | +| صورة JPEG تريد معالجتها (مثال: `ukrainian_sign.jpg`) | ملف المصدر لمحرك OCR. | + +> **نصيحة احترافية:** إذا كنت على Linux أو macOS، فإن نفس الكود يعمل مع .NET CLI (`dotnet new console`)، لذا لا تتردد في تخطي بيئة التطوير الثقيلة. + +--- + +## Step 1 – Install Aspose.OCR via NuGet + +افتح الطرفية (أو Package Manager Console) وشغّل: + +```bash +dotnet add package Aspose.OCR +``` + +هذا السطر الواحد يجلب أحدث ملفات Aspose.OCR الثنائية وجميع التبعيات المتسلسلة. لا حاجة للتلاعب اليدوي بـ DLL. + +--- + +## Step 2 – Create the OCR Engine (The Heart of Extraction) + +الآن بعد أن تم إضافة المكتبة، يمكننا إنشاء نسخة من `OcrEngine`. هذا الكائن مسؤول عن **extracting text from image**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **لماذا هذا مهم:** المحرك يضم خوارزميات OCR، نماذج اللغات، وخيارات التكوين. إنشاء نسخة واحدة وإعادة استخدامها عبر صور متعددة يكون فعالًا من حيث الذاكرة وسريعًا. + +--- + +## Step 3 – Load Image for OCR (And Set the Language) + +الخطوة التالية هي إخبار المحرك أي صورة يجب قراءتها. هنا يأتي دور عبارة **load image for OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **حالة حافة:** إذا لم يكن الملف موجودًا، فإن `Image.FromFile` يطرح استثناء `FileNotFoundException`. اح.wrap النداء داخل كتلة try‑catch للشفرة الإنتاجية. + +--- + +## Step 4 – Perform OCR and Extract Text + +مع تحميل الصورة، يمكن للمحرك الآن **extract text from image**. طريقة `Recognize` تقوم بالعمل الشاق. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +إذا سارت الأمور على ما يرام، سيحتوي `recognizedText` على تمثيل النص العادي لكل ما استطاع محرك OCR قراءته. + +--- + +## Step 5 – Convert JPG to Text (Putting It All Together) + +الكود الذي بنيناه حتى الآن بالفعل **convert jpg to text**، لكن دعنا نغلفه في طريقة مرتبة يمكنك استدعاؤها بشكل متكرر. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +الآن يمكنك ببساطة القيام بـ: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**الناتج المتوقع** (مقتطع للختصر): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +إذا كانت الصورة تحتوي على نص إنجليزي، غيّر `OcrLanguage.English` وسترى الناتج المقابل. + +--- + +## Step 6 – Handling Common “How to OCR Image” Questions + +### 6.1 هل يمكنني OCR لملف PNG أو BMP؟ + +بالطبع. طريقة `Image.FromFile` تدعم جميع الصيغ التي يتعرف عليها System.Drawing، لذا ما عليك سوى توجيه المسار إلى ملف `.png` أو `.bmp` وستبقى بقية الشفرة كما هي. + +### 6.2 ماذا لو كانت الصورة منخفضة الدقة؟ + +دقة OCR تنخفض بشكل كبير تحت 300 dpi. حل سريع هو تكبير الصورة باستخدام `Graphics` قبل تمريرها إلى المحرك: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 هل أحتاج إلى ترخيص لـ Aspose.OCR؟ + +تقدم Aspose تجربة مجانية مع علامة مائية. للاستخدام الإنتاجي، اشترِ ترخيصًا وأضف: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Full Working Example + +فيما يلي تطبيق console كامل وجاهز للتنفيذ يوضح **how to OCR image**، **load image for OCR**، و **convert jpg to text** في حزمة واحدة منظمة. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**كيفية تشغيله** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +يجب أن ترى النص المستخرج يُطبع على وحدة التحكم، مما يؤكد أنك نجحت في **extract text from image** باستخدام C#. + +--- + +## Common Pitfalls & Pro Tips + +| المشكلة | لماذا يحدث | الحل | +|-------|----------------|-----| +| مخرجات فارغة | الصورة مظلمة جدًا أو ذات تباين منخفض. | معالجة مسبقة باستخدام `Bitmap` لزيادة السطوع. | +| لغة خاطئة | خاصية `Language` تركت على الإنجليزية الافتراضية. | عيّن صراحةً `ocrEngine.Language = OcrLanguage.Ukrainian;` (أو لغتك المستهدفة). | +| خطأ نفاد الذاكرة | تحميل صور كبيرة جدًا دون تحريرها. | ضع `Image.FromFile` داخل كتلة `using` (كما هو موضح). | +| علامة مائية للترخيص | تشغيل نسخة تجريبية بدون ترخيص. | تطبيق الترخيص المشتراة مبكرًا في `Main`. | + +--- + +## Conclusion + +لقد غطينا الآن كل ما تحتاجه **extract text from image** في C#—من تثبيت Aspose.OCR، **loading image for OCR**، إلى **convert jpg to text** ومعالجة السيناريوهات متعددة اللغات. البرنامج الكامل يربط جميع الأجزاء معًا، مما يمنحك أساسًا موثوقًا لأي مشروع يتعلق بـ OCR. + +Next, you might explore: + +* **How to OCR image** تدفقات بدلاً من ملفات (استخدم `MemoryStream`). +* إضافة **c# image to text** ما بعد المعالجة مثل التدقيق الإملائي. +* دمج خطوة OCR في خط أنابيب أكبر (مثال: تخزين النتائج في قاعدة بيانات). + +لا تتردد في تجربة لغات مختلفة، صيغ صور، وحيل ما قبل المعالجة. OCR هو فن وعلم، وكلما لعبت أكثر ستحصل على نتائج أفضل. + +برمجة سعيدة، ولتكون صورك دائمًا قابلة للقراءة! + +## دروس ذات صلة + +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [استخراج النص من الصورة – تحسين OCR باستخدام Aspose.OCR لـ .NET](/ocr/english/net/ocr-optimization/) +- [كيفية استخراج النص من الصورة عن طريق إعداد المستطيلات في OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/arabic/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..99ce848df --- /dev/null +++ b/ocr/arabic/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-05-25 +description: كيفية استخدام OCR في C# لاستخراج النص من ملفات الصور. تعلم التعرف على + الأحرف الصينية من ملف JPG باستخدام Aspose.OCR في بضع خطوات بسيطة. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: ar +og_description: كيفية استخدام OCR في C# لاستخراج النص من ملفات الصور. يوضح لك هذا + الدليل كيفية التعرف على الأحرف الصينية من ملف JPG باستخدام Aspose.OCR. +og_title: كيفية استخدام OCR في C# – التعرف على النص الصيني من JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: كيفية استخدام OCR في C# – التعرف على النص الصيني من ملف JPG +url: /ar/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# كيفية استخدام OCR في C# – التعرف على النص الصيني من JPG + +هل تساءلت يومًا **كيفية استخدام OCR** لاستخراج الكلمات من صورة التقطتها بهاتفك؟ لست وحدك. في العديد من المشاريع الواقعية—مثل ماسحات الفواتير، تطبيقات الترجمة، أو إدخال البيانات الآلي—ستحتاج إلى **استخراج النص من الصورة** بسرعة وبشكل موثوق. + +في هذا الدرس سنستعرض مثالًا كاملًا وقابلًا للتنفيذ **يتعرف على النص من ملفات JPG** ويتعامل أيضًا مع الحالة الصعبة **التعرف على الأحرف الصينية** باستخدام حزمة اللغة **OCR Chinese Simplified**. في النهاية ستحصل على تطبيق console مستقل يطبع السلسلة المكتشفة في نافذة الأوامر، دون الحاجة إلى تنزيلات يدوية إضافية. + +> **ملاحظة سريعة:** يعمل الكود مع Aspose.OCR ≥ 23.7، الذي يجلب موارد اللغة تلقائيًا عند الاستخدام الأول. إذا كنت تستخدم نسخة أقدم، سيتعين عليك إضافة اللغة يدويًا. + +## المتطلبات المسبقة + +- .NET 6.0 SDK أو أحدث (المثال يستهدف .NET 6، لكن .NET 5 يعمل أيضًا) +- نسخة حديثة من Visual Studio 2022 أو VS Code مع امتداد C# +- اتصال إنترنت لتنزيل اللغة لأول مرة +- صورة JPG تحتوي على نص صيني مبسط (سنسميها `chinese_sign.jpg`) + +هذا كل شيء—بدون محركات OCR ثقيلة، بدون التعامل مع DLLs الأصلية. فقط بضع أوامر NuGet وقليل من أسطر الكود. + +## الخطوة 1: تثبيت Aspose.OCR عبر NuGet + +أولًا: نحتاج إلى مكتبة OCR. افتح طرفية في مجلد المشروع وشغّل: + +```bash +dotnet add package Aspose.OCR +``` + +أو إذا كنت تفضّل واجهة Visual Studio، انقر بزر الماوس الأيمن على **Dependencies → Manage NuGet Packages**، ابحث عن “Aspose.OCR”، ثم اضغط **Install**. + +> **نصيحة احترافية:** حافظ على تحديث الحزم. حزم اللغات الجديدة وتحسينات الأداء تُضاف في كل إصدار فرعي. + +## الخطوة 2: إنشاء مشروع Console جديد (إذا لم تقم بذلك بعد) + +إذا كنت تبدأ من الصفر، أنشئ تطبيق console جديد: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +الآن لديك ملف `Program.cs` جاهز لكود OCR. + +## الخطوة 3: كتابة كود OCR – التعرف على الصيني المبسط من JPG + +افتح `Program.cs` واستبدل محتوياته بما يلي. كل سطر مشروح حتى ترى *لماذا* نقوم بهذه الخطوة، وليس فقط *ماذا* نفعل. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### ما الذي يحدث خلف الكواليس؟ + +- **`OcrEngine.Language`** يخبر Aspose أي قاموس يستخدم. باختيار `ChineseSimplified`، نوجه المحرك للبحث عن حزمة اللغة الصينية المبسطة. +- **التنزيل لأول مرة**: عندما يتم تشغيل `Recognize`، يتواصل SDK مع CDN الخاص بـ Aspose، ينزل ملف اللغة ≈6 MB، يخزنه محليًا، ثم يواصل عملية OCR. الاستدعاءات اللاحقة تكون فورية. +- **`Image.FromFile`** يعمل مع أي تنسيق نقطي يمكن لـ .NET فك تشفيره—JPG، PNG، BMP—وبالتالي يمكنك **استخراج النص من الصورة** لملفات بأنواع متعددة، وليس JPG فقط. + +## الخطوة 4: تشغيل التطبيق والتحقق من المخرجات + +Build and run: + +```bash +dotnet run +``` + +You should see something like: + +``` +=== Recognized Text === +欢迎光临 +``` + +إذا طبع الـ console نصًا غير مفهوم أو سلسلة فارغة، تحقق مرة أخرى من: + +1. الصورة تحتوي فعليًا على أحرف صينية واضحة وعالية التباين. +2. مسار الملف صحيح (بدون مسافات زائدة أو امتدادات مفقودة). +3. جهازك يستطيع الوصول إلى `https://download.aspose.com` للحصول على حزمة اللغة. + +## الخطوة 5: التعامل مع الحالات الحدية والمشكلات الشائعة + +### 5.1 التعامل مع الصور منخفضة الجودة + +تنخفض دقة OCR عندما تكون الصورة المصدرية غير واضحة، مشوشة، أو ذات إضاءة ضعيفة. حل سريع هو معالجة الصورة مسبقًا: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 التشغيل في بيئة بدون واجهة رسومية + +إذا كنت تنشر إلى حاوية Linux بدون واجهة رسومية، تأكد من تثبيت مكتبة `libgdiplus` (المطلوبة لـ `System.Drawing`): + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 تخزين حزمة اللغة مؤقتًا يدويًا + +يمكنك تنزيل ملف اللغة مرة واحدة وتوجيه Aspose إليه عبر واجهة برمجة التطبيقات `License`، مما يلغي الحاجة إلى الاتصال الشبكي مرة واحدة. هذا مفيد للسيناريوهات غير المتصلة. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## مثال كامل يعمل (الكل في واحد) + +فيما يلي البرنامج *الكامل* الذي يمكنك نسخه ولصقه في `Program.cs`. لا توجد أجزاء مخفية، ولا سكريبتات خارجية. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### المخرجات المتوقعة + +إذا كان JPG يحتوي على العبارة “欢迎光临”، سيطبع الـ console: + +``` +=== Recognized Text === +欢迎光临 +``` + +لا تتردد في استبدال الصورة بأي علامة صينية مبسطة أخرى، اسم شارع، أو ملصق منتج—المحرك سيبذل قصارى جهده. + +## الخلاصة + +لقد غطينا للتو **كيفية استخدام OCR** في C# **لاستخراج النص من الصورة**، مع التركيز على تحدي **التعرف على الأحرف الصينية** في **JPG**. من خلال الاستفادة من تنزيل اللغة الفوري في Aspose.OCR، يمكنك الحفاظ على خفة نشر تطبيقك مع دعم **OCR Chinese Simplified** مباشرةً. + +ما التالي؟ جرّب هذه الأفكار: + +- **Batch processing**: تكرار عبر مجلد من الصور وكتابة كل نتيجة إلى ملف CSV. +- **Combine with translation APIs**: تمرير السلسلة المعترف بها إلى Azure Translator لتطبيقات متعددة اللغات في الوقت الفعلي. +- **Explore other languages**: استبدال `OcrLanguage.ChineseSimplified` بـ `Japanese` أو `Arabic` وملاحظة كيف يتكيف الكود نفسه. + +هل لديك أسئلة حول تحسين الأداء، الترخيص، أو دمج OCR في خدمة ويب؟ اترك تعليقًا أدناه—برمجة سعيدة! + +--- + +![لقطة شاشة لمخرجات الـ console تُظهر كيفية استخدام OCR في C# للتعرف على النص الصيني من صورة JPG](ocr-chinese-demo.png "كيفية عرض مخرجات OCR في الـ console") + +## دروس ذات صلة + +- [استخراج نص الصورة 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](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/arabic/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/arabic/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..e4a835e0d --- /dev/null +++ b/ocr/arabic/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,306 @@ +--- +category: general +date: 2026-05-25 +description: تعلم كيفية التعرف الضوئي على النص الروسي في C# واستخراج النص من الصورة + باستخدام Aspose OCR. كود خطوة بخطوة لتحويل الصورة إلى نص في C# بسرعة. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: ar +og_description: التعرف الضوئي على النص الروسي في C# سهل. تعلم كيفية استخراج النص من + الصورة، تحويل الصورة إلى نص باستخدام C#، وتحميل الصورة للتعرف الضوئي على الأحرف + باستخدام Aspose OCR. +og_title: التعرف الضوئي على الأحرف للنص الروسي في C# – دليل Aspose OCR الكامل +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: التعرف الضوئي على النص الروسي في C# – دليل كامل باستخدام Aspose OCR +url: /ar/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# التعرف الضوئي على النص الروسي في C# – دليل كامل باستخدام Aspose OCR + +هل احتجت يومًا إلى التعرف الضوئي على النص الروسي في C# لكنك لم تكن متأكدًا أي مكتبة تثق بها؟ لست وحدك. الحصول على أحرف نظيفة وقابلة للقراءة من صورة سيريليّة قد يشعر كأنك تحل شفرة رسائل سرية—خاصة إذا لم تقم بتعيين نموذج اللغة الصحيح. + +في هذا الدرس سنستعرض مثالًا عمليًا يوضح لك كيفية **استخراج النص من الصورة**، وتحويل *الصورة إلى نص في C#*، ومعالجة تفاصيل التعرف على اللغة الروسية باستخدام Aspose OCR. في النهاية ستحصل على تطبيق كونسول جاهز للتشغيل يقوم بتحميل صورة للتعرف الضوئي، ويطبع السلسلة المُعترف بها، ويمنحك أساسًا قويًا للسيناريوهات المتقدمة. + +## ما ستتعلمه + +- كيفية تثبيت وتكوين **Aspose OCR C#** لدعم اللغة الروسية. +- الخطوات الدقيقة لـ **تحميل الصورة للتعرف الضوئي** واستدعاء المحرك. +- نصائح للتعامل مع المشكلات الشائعة مثل نقص موارد اللغة أو الصور الضبابية. +- طرق لتوسيع الحل، مثل المعالجة الدفعية لعدة ملفات أو تعديل عتبات الثقة. + +لا تحتاج إلى خبرة سابقة مع Aspose؛ فقط إلمام أساسي بـ C# و .NET سيؤهلك للبدء. + +## المتطلبات المسبقة + +قبل أن نبدأ، تأكد من أن لديك ما يلي: + +1. **.NET 6.0** (أو أحدث) SDK مثبت – الكود يعمل على .NET Core و .NET Framework على حد سواء. +2. **Visual Studio 2022** (أو أي بيئة تطوير تفضلها). +3. حزمة **Aspose.OCR for .NET** عبر NuGet – يمكنك الحصول على مفتاح تجريبي مجاني من موقع Aspose. +4. ملف **نموذج اللغة الروسية** (`rus.traineddata`) – حمّله من صفحة موارد Aspose وضعه في مجلد ستشير إليه لاحقًا. +5. صورة نموذجية (`russian_doc.png`) تحتوي على نص سيريلي واضح. + +هل لديك كل ذلك؟ رائع—لنبدأ. + +## الخطوة 1: إعداد المشروع وتثبيت Aspose OCR + +أولاً، أنشئ مشروع كونسول جديد: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +الآن أضف حزمة Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **نصيحة احترافية:** إذا كنت تستخدم ترخيصًا تجريبيًا، احتفظ بملف `Aspose.Total.lic` في متناول يدك؛ ستقوم بتحميله في الكود لتجنب العلامات المائية. + +بعد تثبيت الحزمة، افتح `Program.cs`. سترى طريقة `Main` الافتراضية—استبدل محتواها بالهيكلية التي سنبنيها. + +## الخطوة 2: تكوين محرك OCR للغة الروسية + +جوهر العملية هو كائن `OcrEngine`. نحتاج إلى إبلاغه بأمرين: أي لغة يجب التعرف عليها وأين توجد ملفات نماذج اللغة. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **لماذا هذا مهم:** إذا تخطيت تعيين `Language = OcrLanguage.Russian`، سيستخدم المحرك اللغة الإنجليزية افتراضيًا، وستظهر أي أحرف سيريليّة كرموز مشوشة. `ResourceFolder` يشير إلى الدليل الذي يحتوي على ملف `rus.traineddata`؛ بدون ذلك، يطرح Aspose استثناء *المورد غير موجود*. + +## الخطوة 3: تحميل الصورة للتعرف الضوئي + +الآن نحتاج إلى **تحميل الصورة للتعرف الضوئي**. يعمل Aspose OCR مع `System.Drawing.Image`، لذا يمكنك تمرير أي تنسيق مدعوم (PNG، JPEG، BMP، إلخ). تأكد من صحة مسار الملف؛ المسارات النسبية مناسبة إذا وضعت الصورة بجوار الملف التنفيذي. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **حالة حافة:** إذا كانت الصورة كبيرة (أكثر من 5 ميغابايت) قد ترغب في تصغيرها أولاً. دقة OCR تنخفض عندما يكون DPI منخفضًا جدًا، لكن الملفات الضخمة قد تسبب ضغطًا على الذاكرة. يمكن إجراء تعديل سريع للحجم باستخدام `Graphics` إذا لزم الأمر. + +## الخطوة 4: التعرف على النص – من الصورة إلى النص بأسلوب C# + +مع تكوين المحرك وتحميل الصورة، يكون التعرف الفعلي نداءً واحدًا: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +عند تشغيل البرنامج (`dotnet run`)، يجب أن ترى شيئًا مثل: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +إذا كان الإخراج يبدو غير مفهوم، تحقق مرة أخرى من أن: + +- ملف `rus.traineddata` موجود في `ResourceFolder`. +- الصورة ليست ضبابية جدًا؛ فكر في تطبيق مرشح تمثيل ثنائي بسيط قبل OCR. +- إعداد اللغة فعليًا هو `OcrLanguage.Russian`. + +## الخطوة 5: الضبط الدقيق والمشكلات الشائعة + +### ضبط عتبة الثقة + +يعيد Aspose OCR قيمة ثقة لكل حرف داخليًا. رغم أن الـ API لا تعرضها مباشرة، يمكنك تمكين **الإخراج المفصل** لرؤية الكلمات ذات الثقة المنخفضة: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +إذا لاحظت أخطاءً متكررة في التعرف، جرّب: + +- **المعالجة المسبقة**: تحويل الصورة إلى تدرج الرمادي، زيادة التباين، أو تطبيق مرشح متوسط. +- **إعدادات DPI**: تأكد من أن الصورة على الأقل 300 DPI للخطوط السيريليّة. + +### المعالجة الدفعية لعدة صور + +إذا كنت بحاجة إلى **استخراج النص من الصورة** لملفات متعددة دفعة واحدة، ضع منطق التعرف داخل حلقة: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +الآن كل ملف PNG يحصل على ملف `.txt` المقابل—مفيد لأرشفة المستندات. + +### التعامل مع إخراج Unicode + +الأحرف السيريليّة هي Unicode، لذا تأكد من أن ترميز الكونسول يمكنه عرضها: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +ضع هذا السطر مباشرة بعد بدء طريقة `Main`. بدون ذلك، قد ترى علامات استفهام (`?`) بدلاً من الأحرف الروسية. + +## مثال كامل يعمل + +فيما يلي الكود الكامل الجاهز للتشغيل. انسخه إلى `Program.cs`، عدّل المسارات، وستكون جاهزًا. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**الإخراج المتوقع** (بافتراض أن الصورة النموذجية تقول “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +إذا رأيت أي شيء آخر، راجع نصائح استكشاف الأخطاء في الخطوة 5. + +## الخلاصة + +أصبح لديك الآن مثال شامل من البداية إلى النهاية حول كيفية **التعرف الضوئي على النص الروسي** في C# باستخدام Aspose OCR. من تثبيت المكتبة، تكوين نموذج اللغة الروسية، إلى تحميل صورة وتحويلها إلى نص Unicode نظيف، كل خطوة مغطاة. + +تذكر أن مفتاح OCR الموثوق هو مادة المصدر الجيدة: خطوط واضحة، DPI كافية، والموارد اللغوية الصحيحة. بمجرد إتقان الأساسيات، يمكنك التوسع إلى المعالجة الدفعية، دمجها مع التخزين السحابي، أو حتى الجمع مع معالجة AI بعدية لتدقيق الإملاء. + +### ما التالي؟ + +- استكشف خيارات **aspose ocr c#** المتقدمة مثل تحليل التخطيط أو إخراج PDF. +- دمج هذا مع سير عمل **استخراج النص من الصورة** في Azure Functions للمعالجة بدون خادم. +- جرّب لغات مختلفة—فقط غيّر `OcrLanguage.Russian` إلى `OcrLanguage.English` أو أي رمز مدعوم آخر. + +هل لديك أسئلة أو صورة صعبة لا تتعاون؟ اترك تعليقًا أدناه، وبرمجة سعيدة! + +![مثال نص OCR روسي](ocr-russian-example.png){alt="مثال نص OCR روسي"} + +## دروس ذات صلة + +- [استخراج نص الصورة C# مع اختيار اللغة باستخدام Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [التعرف على نص الصورة باستخدام Aspose OCR لعدة لغات](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [استخراج النص من الصورة باستخدام Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/arabic/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..5bf33dbad --- /dev/null +++ b/ocr/arabic/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: التعرف على النص من الصورة باستخدام Aspose OCR في C#. تعلّم كيفية تحميل + الصورة للتعرف الضوئي على الأحرف، ضبط لغة OCR، إنشاء محرك OCR واستخراج النص من ملف + TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: ar +og_description: التعرف على النص من الصورة باستخدام Aspose OCR في C#. يوضح هذا الدرس + كيفية إنشاء محرك OCR، تحميل الصورة للـ OCR، تعيين لغة الـ OCR، واستخراج النص من + ملف TIFF. +og_title: التعرف على النص من الصورة باستخدام Aspose OCR – دليل C# الكامل +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: التعرف على النص من الصورة باستخدام Aspose OCR – دليل C# الكامل +url: /ar/net/text-recognition/recognize-text-from-image-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 – دليل C# كامل + +هل احتجت يوماً إلى **التعرف على النص من الصورة** لكنك لم تكن متأكدًا أي مكتبة ستوفر لك السرعة والدقة معًا؟ لست وحدك. في العديد من مشاريع معالجة الفواتير أو الأرشفة، تكون النقطة الأكثر إزعاجًا هي استخراج نص نظيف وقابل للبحث من ملفات TIFF دون كتابة محلل مخصص. + +الأمر بسيط: Aspose OCR لـ .NET يجعل هذه السلسلة بأكملها سهلة للغاية. في هذا الدليل سنستعرض كل ما تحتاجه — تثبيت الحزمة، **إنشاء محرك OCR**، تحميل ملف TIFF، ضبط لغة OCR، وأخيرًا **استخراج النص من TIFF**. في النهاية ستحصل على تطبيق كونسول جاهز للتنفيذ يمكنه **التعرف على النص من ملفات الصورة** بسرعة البرق. + +## المتطلبات المسبقة + +- .NET 6.0 أو أحدث (الكود يعمل مع .NET Core و .NET Framework أيضًا) +- Visual Studio 2022 (أو أي بيئة تطوير تفضلها) +- حزمة Aspose.OCR عبر NuGet (دعم GPU يتطلب الإضافة `Aspose.OCR.Gpu`) +- وحدة معالجة رسومية (GPU) تدعم CUDA إذا أردت السرعة الإضافية (اختياري لكن يُنصح به) + +> **نصيحة محترف:** إذا لم يكن لديك GPU، ما عليك سوى حذف سطر `GpuDevice` وسيتحول المحرك تلقائيًا إلى المعالج المركزي (CPU). + +## الخطوة 1: تثبيت Aspose OCR وإنشاء محرك OCR + +أولاً، أضف الحزم الضرورية عبر NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +الآن يمكننا **إنشاء محرك OCR**. هذا الكائن هو قلب العملية؛ فهو يحمل الإعدادات مثل الجهاز الذي يعمل عليه وحدود الذاكرة. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**لماذا هذا مهم:** بربط المحرك بوحدة GPU، تقلل بشكل كبير الوقت المستغرق لـ **التعرف على النص من الصورة**، خاصةً عند معالجة دفعات كبيرة من ملفات TIFF عالية الدقة. + +## الخطوة 2: تحميل الصورة لـ OCR + +بعد ذلك، نحتاج إلى **تحميل الصورة لـ OCR**. Aspose.OCR يعمل مع `System.Drawing.Image`، لذا أي تنسيق يدعمه GDI+ (بما في ذلك TIFF متعدد الصفحات) سيكون مناسبًا. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +إذا كنت تتعامل مع TIFF متعدد الصفحات يمكنك التنقل بين الصفحات باستخدام `image.SelectActiveFrame`، لكن في معظم الحالات نداء واحد يكفي. + +## الخطوة 3: ضبط لغة OCR + +المحرك لا يعرف سحرًا أي لغة تقوم بمسحها. **ضبط لغة OCR** قبل تشغيل المعرّف؛ وإلا ستحصل على مخرجات مشوشة. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **هل تعلم؟** تبديل اللغات أثناء التشغيل تكلفة منخفضة — يمكنك حتى معالجة مستند مختلط اللغات بتغيير هذه الخاصية بين الصفحات. + +## الخطوة 4: تنفيذ التعرف – التعرف على النص من الصورة + +الآن الجزء الممتع: **التعرف على النص من الصورة** فعليًا. طريقة `Recognize` تُعيد سلسلة نصية عادية تحتوي جميع الأحرف المكتشفة. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +إذا كنت تحتاج إلى درجات الثقة أو إطارات الحدود يمكنك استخدام النسخة التي تُعيد كائن `OcrResult`، لكن لمعظم مهام الاستخراج السلسلة النصية العادية كافية. + +## الخطوة 5: استخراج النص من TIFF (وتعامل مع الملفات متعددة الصفحات) + +عندما يكون المصدر TIFF يحتوي على عدة صفحات، ستحتاج إلى تكرار الخطوات 2‑4 لكل إطار. إليك حلقة سريعة **تستخرج النص من TIFF** صفحة بصفحة: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +الكود أعلاه يطبع النص المستخرج لكل صفحة، مما يجعل من السهل توجيه النتائج إلى قاعدة بيانات أو فهرس بحث. + +## الخطوة 6: عرض أو حفظ النص المستخرج + +أخيرًا، لن **نعرض النص المستخرج** وربما نكتبه إلى ملف للمعالجة لاحقًا. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +تشغيل البرنامج يجب أن يُظهر الأحرف التي تم التعرف عليها ويُنشئ ملف `extracted_text.txt` بجانب ملف TIFF المصدر. + +--- + +## أسئلة شائعة وحالات خاصة + +- **ماذا لو لم يتم اكتشاف الـ GPU؟** + احذف سطر `GpuDevice`؛ سيتحول المحرك تلقائيًا إلى وضع CPU. الأداء سيكون أبطأ لكن النتائج ستظل دقيقة. + +- **هل يمكنني معالجة ملفات PNG أو JPEG؟** + بالتأكيد — `Image.FromFile` يعمل مع أي تنسيق يدعمه System.Drawing، لذا يمكنك **تحميل الصورة لـ OCR** بغض النظر عن الامتداد. + +- **كيف أتعامل مع المسحات منخفضة الدقة؟** + زد قيمة `ocrEngine.PreprocessOptions.Dpi` قبل استدعاء `Recognize`. DPI أعلى يمنح المحرك المزيد من البكسلات للعمل معها، مما يحسن الدقة. + +- **هل هناك حد لحجم ملف TIFF؟** + خاصية `GpuMemoryLimit` تحد من استهلاك الذاكرة على الـ GPU. إذا وصلت إلى الحد، سيتحول المحرك إلى CPU للصفحات المتبقية. + +--- + +## الخلاصة + +أصبح لديك الآن مقطع شفرة كامل وجاهز للإنتاج يمكنه **التعرف على النص من ملفات الصورة** باستخدام Aspose OCR في C#. غطى الدليل كيفية **إنشاء محرك OCR**، **تحميل الصورة لـ OCR**، **ضبط لغة OCR**، و**استخراج النص من TIFF** — كل ذلك مع الاستفادة من تسريع الـ GPU للسرعة. + +من هنا يمكنك: + +- تجربة لغات مختلفة (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, إلخ). +- دمج المخرجات في فهرس ElasticSearch قابل للبحث. +- إضافة معالجة ما بعد الاستخراج (تدقيق إملائي، تنظيف regex) لتحسين جودة البيانات. + +جرّبه على دفعة الفواتير الخاصة بك، عدّل حدود الذاكرة، وشاهد أداء OCR يرتفع. Happy coding! + +## دروس ذات صلة + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..c66db9735 100644 --- a/ocr/chinese/net/ocr-configuration/_index.md +++ b/ocr/chinese/net/ocr-configuration/_index.md @@ -59,7 +59,9 @@ 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# 中创建 OCR 引擎 – 完整指南](./create-ocr-engine-in-c-complete-guide/) +一步步教您在 C# 中构建并配置 Aspose.OCR 引擎,实现高效文本识别。 ### 常见使用场景 - **从扫描发票中提取文本**,实现自动化会计。 @@ -100,4 +102,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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/chinese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a4d11ed89 --- /dev/null +++ b/ocr/chinese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-25 +description: 在 C# 中创建 OCR 引擎,并学习如何在几行代码中检查其评估模式和授权状态。 +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: zh +og_description: 在 C# 中创建 OCR 引擎,并即时查看如何检测评估模式以及显示授权状态。 +og_title: 在 C# 中创建 OCR 引擎 – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: 在 C# 中创建 OCR 引擎 – 完整指南 +url: /zh/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中创建 OCR 引擎 – 完整指南 + +是否曾经想过 **创建 OCR 引擎** 对象却在海量文档中找不到答案?你并不孤单。许多开发者在需要启动 OCR 引擎、检查是否处于试用模式以及向用户展示授权状态时会卡住。 + +在本教程中,我们将通过一个简洁的端到端示例,**创建 OCR 引擎**、检查其 **OCR 引擎评估模式**,并打印友好的授权状态信息。完成后,你将拥有一个可直接运行的控制台应用,并对在项目中处理 OCR 授权有清晰的认知模型。 + +## 你将学到 + +- 如何实例化 `OcrEngine`(任何 OCR 工作流的核心)。 +- 为什么检测 **评估模式** 对合规性和用户体验至关重要。 +- 检查 **OCR 授权** 状态的最佳实践以及对异常状态的响应方式。 +- 常见陷阱——空引用、异常处理和版本不匹配。 + +不需要除已安装的 OCR SDK 之外的任何外部工具。如果你熟悉基本的 C# 语法,就可以开始了。 + +## 前置条件 + +- .NET 6.0 或更高(代码兼容 .NET Core 和 .NET Framework)。 +- 一个提供 `OcrEngine` 类且包含 `IsEvaluation` 属性的 OCR SDK(例如假设的 `MyOcrSdk`)。 +- 文本编辑器或 IDE(Visual Studio、VS Code、Rider——任选其一)。 + +就这些。让我们开始吧。 + +## 步骤 1:创建新控制台项目 + +首先,新建一个干净的控制台应用,以便在隔离环境中运行代码。 + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +打开生成的 `Program.cs`。我们将用一个完整示例替换其内容,该示例 **创建 OCR 引擎** 实例并处理授权。 + +## 步骤 2:导入 OCR SDK 命名空间 + +假设 SDK 已通过 NuGet 引用(`MyOcrSdk` 为占位符),在文件顶部添加 using 指令。 + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +如果尚未添加该包,运行: + +```bash +dotnet add package MyOcrSdk +``` + +> **小贴士:** 保持 SDK 版本最新;新版本通常会改进评估模式检测。 + +## 步骤 3:创建 OCR 引擎实例 + +现在我们终于 **创建 OCR 引擎** 对象。这是任何 OCR 工作流的核心——相当于后续读取图像的大脑。 + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +为什么这一步至关重要?`OcrEngine` 包含所有配置、语言包和授权数据。没有它,你既无法处理图像,也无法查询评估标志。 + +> **旁注:** 某些 SDK 允许在构造函数中传入配置对象(例如语言、DPI)。如果需要自定义设置,请相应修改此行代码。 + +## 步骤 4:确定 OCR 引擎评估模式 + +大多数 OCR 供应商会提供试用版,在提供有效授权密钥之前会以 **评估模式** 运行。了解自己是否处于试用模式可以让你显示合适的 UI 提示或限制某些功能。 + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation` 属性在引擎未授权或使用限时试用时返回 `true`。这是防护高级功能的快速可靠方式。 + +### 如果属性不存在怎么办? + +旧版 SDK 可能提供 `GetLicenseInfo()` 方法。此时,你需要检查返回对象中的 `IsTrial` 标志。升级时请务必查阅 SDK 更新日志。 + +## 步骤 5:显示当前授权状态 + +最后,让用户知道引擎是已授权还是仍在试用。使用简单的 `Console.WriteLine` 即可,但你也可以将其改写为 GUI 应用的提示。 + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +三元运算符让代码保持简洁,信息对终端用户或阅读日志的开发者都足够清晰。 + +## 完整可运行示例 + +将所有代码组合在一起,下面的程序可以直接复制粘贴到 `Program.cs` 并使用 `dotnet run` 运行。 + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### 预期输出 + +- **试用版构建:** + `Running in evaluation mode – limited functionality.` + +- **授权版构建:** + `Licensed – full OCR capabilities enabled.` + +如果 SDK 抛出异常(例如缺少本机 DLL),catch 块会打印友好的错误信息,而不是让整个应用崩溃。 + +## 处理边缘情况和常见陷阱 + +### 1. 空引擎实例 + +虽然构造函数通常返回有效对象,但某些 SDK 在缺少本机依赖时可能返回 `null`。请做好防护: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. 运行时授权过期 + +试用授权可能在会话期间过期。如果你的应用长时间运行,请定期重新查询 `IsEvaluation`。 + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. 不同版本的属性名称 + +旧版本可能使用 `engine.EvaluationMode` 或 `engine.License.IsTrial`。升级时请在 SDK 发布说明中搜索破坏性更改。 + +### 4. 多线程场景 + +如果启动多个 OCR 工作线程,除非 SDK 明确支持线程安全共享,否则 **每个线程实例化一个 OCR 引擎**。共享单个引擎可能导致竞争条件和错误的授权读取。 + +## 生产环境使用的专业建议 + +- **在首次检查后缓存授权状态**,以避免不必要的属性调用。 +- **在启动时记录授权密钥(掩码处理)**,便于审计——帮助支持团队诊断授权问题。 +- **提供 UI 开关**,告知用户当前处于试用模式,并提供 “购买授权” 按钮。 +- **使用 SDK 的激活 API**(如果可用)实现授权自动续期,保持用户体验流畅。 + +## 结论 + +我们仅用几行代码 **创建了 OCR 引擎** 对象,检查了 **OCR 引擎评估模式**,并打印了清晰的 **OCR 授权状态** 信息。完整示例即开即用,具备错误处理,并解释了每一步背后的原因——你可以轻松将其迁移到桌面、Web 或服务端场景。 + +接下来,你可以进一步探索: + +- 将图像传入 `engine.Recognize` 并处理多语言支持。 +- 使用 **check OCR license** API 编程式激活已购买的密钥。 +- 与 UI 框架(WinForms、WPF、MAUI)集成,显示授权徽章。 + +试一试这些内容,你就拥有了面向任何应用的坚实 OCR 基础。祝编码愉快! + +## 相关教程 + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/net/ocr-optimization/_index.md b/ocr/chinese/net/ocr-optimization/_index.md index 48aeacf55..5ac4170e4 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 结果保存为文档。 +### [预处理图像用于 OCR – 完整 Aspose C# 指南](./preprocess-image-for-ocr-complete-aspose-c-guide/) +全面指南,教您使用 Aspose.C# 对图像进行预处理,以提升 OCR 识别准确率。 + ## 常见问题 **Q: 我可以从包含多种语言的图像文件中提取文本吗?** diff --git a/ocr/chinese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/chinese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..3d19100a2 --- /dev/null +++ b/ocr/chinese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-25 +description: 使用 Aspose 对图像进行 OCR 预处理,以提升 OCR 准确率并对 JPEG 文件执行 OCR。学习如何在清晰的分步教程中使用 Aspose + 提取文本。 +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: zh +og_description: 使用 Aspose 对图像进行预处理,以提升 OCR 准确率。按照本指南,在 JPEG 上运行 OCR 并使用 C# 的 Aspose + 提取文本。 +og_title: OCR 图像预处理 – Aspose C# 教程 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: OCR图像预处理 – 完整的Aspose C#指南 +url: /zh/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 预处理图像用于 OCR – 完整 Aspose C# 指南 + +有没有想过如何 **预处理图像以进行 OCR**,让文字每次都能干净地识别?你并不是唯一面临这个问题的人——开发者们经常要与噪声扫描、低对比度 JPEG 和不稳定的光照作斗争。好消息是,只需几项聪明的调整,就能显著 **提升 OCR 准确率**,而 Aspose 让这一过程变得轻而易举。 + +在本教程中,我们将通过一个真实案例,演示如何 **在 JPEG 上运行 OCR**,应用自定义图像处理流水线,最终 **使用 Aspose 提取文本**。完成后,你将拥有一段可直接粘贴到任何 .NET 项目中的 C# 代码片段。 + +## 你将学到 + +- 为什么预处理至关重要,以及哪些滤镜能带来最大收益。 +- 如何配置 Aspose.OCR 的 `ImageProcessingOptions`,实现去倾斜、去噪、二值化和对比度提升。 +- 完整的代码示例,帮助 **在 JPEG 上运行 OCR** 并获取干净的文本。 +- 在生产环境中保持 OCR 流水线稳健的技巧与坑点。 + +不需要任何 Aspose 经验,只要具备基本的 C# 背景和 Visual Studio(或你喜欢的 IDE)即可。让我们开始吧。 + +![预处理图像用于 OCR 示例](preprocess-ocr.png "预处理图像用于 OCR") + +## 步骤 1:设置 Aspose.OCR 引擎 – 预处理图像用于 OCR + +首先,需要创建一个 `OcrEngine` 实例,并告知它期望识别的语言。大多数情况下默认是英文,你可以通过修改 `OcrLanguage` 枚举切换为法文、德文等其他语言。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**为什么这很重要:** 引擎是整个操作的核心;没有它,就无法应用任何实际 **预处理图像以进行 OCR** 的图像滤镜。可以把它想象成厨房,所有原料都在这里混合。 + +## 步骤 2:构建自定义图像处理流水线 – 提升 OCR 准确率 + +接下来是关键部分。Aspose 允许你将多个滤镜串联使用。下面我们启用了四个最有效的滤镜: + +1. **Deskew** – 将倾斜的文档校正(默认最大 5°)。 +2. **Denoise** – 平滑颗粒状背景噪声。 +3. **Binarize** – 使用阈值将图像转换为黑白二值图。 +4. **ContrastBoost** – 提升微弱字符的可见度。 + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**专业提示:** 如果源图像已经非常清晰,可以降低 `Strength` 参数或直接关闭某个滤镜。过度处理有时会抹去细小字符,建议使用真实样本进行实验。 + +## 步骤 3:加载 JPEG(或任意图像)并运行 OCR – 在 JPEG 上运行 OCR + +Aspose 支持 .NET 能读取的所有图像格式——JPEG、PNG、BMP 等。下面演示如何将 JPEG 文件加载到引擎并启动识别过程。 + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**为什么选择 JPEG?** JPEG 压缩常会产生干扰 OCR 的伪影。我们的预处理流水线,尤其是去噪和二值化步骤,能够缓解这些问题,让你 **在 JPEG 上运行 OCR** 时更加自信。 + +## 步骤 4:输出识别文本 – 使用 Aspose 提取文本 + +最后,只需将文本写入控制台、文件或任何下游服务。演示目的下,控制台输出即可。 + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +运行程序后,你应该会看到类似如下的输出: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +如果输出出现乱码,请返回 **步骤 2** 调整滤镜设置。细微的修改往往能在 **提升 OCR 准确率** 上带来显著提升。 + +## 常见边缘情况及处理办法 + +| 场景 | 建议的调整 | +|-----------|----------------------| +| **图像过暗** | 将 `ContrastBoost.Level` 提高到 1.5 或更高。 | +| **倾斜角度 > 5°** | 增大 `DeskewOptions.MaxAngle`(例如设为 10.0),或手动预先旋转图像。 | +| **彩色文字在彩色背景上** | 使用自定义阈值的 `BinarizeOptions`,或切换到 `AdaptiveBinarizeOptions`。 | +| **大文件(> 5 MB)** | 先将图像加载到 `MemoryStream`,以避免文件锁定问题。 | + +这些微调让你的流水线保持灵活且具备前瞻性,尤其在需要 **使用 Aspose 提取文本** 的多源场景下尤为重要。 + +## 完整可运行示例 – 一站式代码 + +下面是完整的、可直接复制粘贴的程序。它在 .NET 6+ 环境下编译,通过 `Aspose.OCR` NuGet 包即可运行。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +将其保存为 `Program.cs`,添加 Aspose.OCR 包(`dotnet add package Aspose.OCR`),然后执行 `dotnet run`。你将在控制台看到已清理的文本输出。 + +## 小结 – 为什么此方案有效 + +- **预处理图像用于 OCR**:流水线消除了最常见的错误来源(倾斜、噪声、低对比度)。 +- **提升 OCR 准确率**:每个滤镜都针对提升引擎感知的信噪比进行调优。 +- **在 JPEG 上运行 OCR**:即使是压缩图像,经过去倾斜和二值化后也能清晰可读。 +- **使用 Aspose 提取文本**:`Recognize` 方法返回纯字符串,随时可用于后续逻辑。 + +将这些步骤组合起来,你只需几行代码即可获得可靠的生产级 OCR 解决方案。 + +## 后续步骤与相关主题 + +- **批量处理** – 循环遍历文件夹中的图像,并将每个结果写入 `.txt` 文件。 +- **语言包** – 将 `OcrLanguage.English` 替换为 `OcrLanguage.Spanish`,或添加自定义词典。 +- **PDF 提取** – 将 Aspose.OCR 与 Aspose.PDF 结合,直接从扫描的 PDF 中抽取文本。 +- **性能调优** – 使用 `Parallel.ForEach` 并行运行引擎,以应对大规模工作负载。 + +欢迎尝试不同的滤镜参数、图像格式,或链式添加其他 Aspose 滤镜(如 `SharpnessOptions`)。掌握基础后,想实现的功能几乎没有限制。 + +--- + +*祝编码愉快!如果遇到任何问题,欢迎在下方留言,我们一起排查。* + +## 相关教程 + +- [使用 Aspose.OCR 滤镜对 .NET 进行图像预处理](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [使用 Aspose.OCR 进行图像文本提取 – 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/text-recognition/_index.md b/ocr/chinese/net/text-recognition/_index.md index 9a3154c26..6fa99f835 100644 --- a/ocr/chinese/net/text-recognition/_index.md +++ b/ocr/chinese/net/text-recognition/_index.md @@ -55,9 +55,17 @@ url: /zh/net/text-recognition/ 使用 Aspose.OCR 释放 .NET 中 OCR 的潜力。轻松从 PDF 中提取文本。立即下载以获得无缝集成体验。 ### [OCR图像识别中的识别表](./recognize-table/) 通过我们关于 OCR 图像识别中表格识别的综合指南,释放 Aspose.OCR for .NET 的潜力。 +### [使用 Aspose OCR 从图像识别文本 – 完整 C# 指南](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +### [如何在 C# 中使用 OCR – 从 JPG 识别中文文本](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +### [使用 Aspose OCR 进行俄文文本 OCR – 完整 C# 指南](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +### [使用 C# 从图像提取文本 – 完整 Aspose OCR 指南](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +### [使用 ASP.NET Core Minimal API 从图像提取文本 – 完整指南](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +### [C# OCR 教程:使用 Aspose 从 PNG 收据中提取文本](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +### [在 C# 中将 TIFF 转换为文本 – 完整批量 OCR 指南](./convert-tiff-to-text-in-c-complete-batch-ocr-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/chinese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/chinese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..7a5c29f8d --- /dev/null +++ b/ocr/chinese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-25 +description: C# OCR 教程,展示如何在 C# 中加载图像文件并使用 Aspose OCR 识别收据中的 PNG 文本——一步一步的指南。 +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: zh +og_description: C# OCR 教程,手把手教你在 C# 中加载图像文件,并使用 Aspose OCR 识别收据中的 PNG 文本。 +og_title: C# OCR 教程 – 从 PNG 收据中提取文本 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: C# OCR 教程:使用 Aspose 从 PNG 收据中提取文本 +url: /zh/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR 教程 – 使用 Aspose 从 PNG 收据中提取文本 + +是否曾经需要一个 **c# OCR 教程**,能够真正完成任务而无需无休止的搜索?你来对地方了。在本指南中,我们将 **load image file c#**、**recognize png text**,以及 **read receipt OCR** 结果,同时向你展示如何使用 Aspose OCR 进行 **perform OCR image** 处理。 + +我们将从安装所需的 NuGet 包开始,逐行讲解代码,并以整洁的 JSON 输出结束,你可以直接将其导入下一个数据管道。没有废话,只有实用、可直接运行的解决方案。 + +## 你将学到 + +- 如何在 .NET 6(或更高)项目中设置 Aspose OCR。 +- **load an image file c#** 的确切步骤并将其交给引擎。 +- 如何从收据图像 **recognize png text** 并获取结果。 +- 将 **read receipt OCR** 输出以整齐的 JSON 格式呈现的方法。 +- 关于在不同文件类型上进行 **perform OCR image** 操作以及处理常见陷阱的技巧。 + +**先决条件** +- Visual Studio 2022(或任何你喜欢的 IDE)。 +- .NET 6 SDK 或更高版本。 +- 一张 PNG 收据图像(我们称之为 `receipt.png`)。 + +如果你已经准备好,让我们开始吧。 + +![c# OCR 教程截图](ocr-demo.png "c# OCR 教程结果显示 JSON 输出") + +## c# OCR 教程 – 设置 Aspose OCR 引擎 + +首先,我们需要 Aspose OCR 库。在解决方案文件夹的终端中运行: + +```bash +dotnet add package Aspose.OCR +``` + +该单行命令会拉取所有必需的内容,包括用于图像解码的本机二进制文件。安装完成后,创建一个新的控制台项目或将代码添加到现有项目中。 + +### 为什么选择 Aspose? + +Aspose OCR 支持超过 30 种语言,离线工作,并返回丰富的 `OcrResult` 对象——非常适合需要超出纯文本的 **perform OCR image** 任务。 + +## 加载图像文件 c# 并准备收据 + +库已准备就绪,现在让我们 **load image file c#**。`System.Drawing.Image` 类负责大部分工作,但如果你更喜欢跨平台替代方案,也可以使用 `SkiaSharp`。 + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **专业提示:** 将 `Image` 包裹在 `using` 语句中(如示例所示),以及时释放本机资源——在循环中对大量文件 **perform OCR image** 时尤为重要。 + +## 使用 Aspose 识别 PNG 文本 + +图像已加载到内存后,引擎即可 **recognize png text**。Aspose 返回一个 `OcrResult`,其中包含原始字符串以及每个识别单词的详细数据。 + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +为什么调用 `RecognizeWithResult` 而不是更简单的 `Recognize`?前者让你能够获取置信度分数、边界框和换行信息——如果以后需要 **read receipt OCR** 进行项目行提取,这非常方便。 + +## 将收据 OCR 结果读取为 JSON + +大多数下游系统喜欢 JSON,所以我们将序列化 `OcrResult`。`System.Text.Json` 序列化器能够优雅地处理复杂对象,我们还会启用缩进以提升可读性。 + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +生成的 JSON 大致如下(为简洁起见已截断): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +现在你可以将 `jsonResult` 导入数据库、消息队列,或仅仅记录日志进行调试。 + +## 执行 OCR 图像处理并显示输出 + +最后,将 JSON 输出到控制台。在实际应用中,你可能会将其写入文件或通过 HTTP 发送,但使用控制台可以轻松验证一切是否正常。 + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +运行程序(`dotnet run`),你应该会看到整齐的 JSON 输出。如果收据图像清晰,文本将非常准确;如果不清晰,考虑提升图像分辨率或在送入引擎前应用预处理滤镜(例如灰度、对比度提升)。 + +### 处理常见边缘情况 + +| 情况 | 处理方法 | +|-----------|------------| +| **图像模糊** | 使用 `System.Drawing` 进行预处理以锐化或提升 DPI。 | +| **收据包含多种语言** | 设置 `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **大批量处理** | 重用单个 `OcrEngine` 实例;每次迭代仅更换 `Image`。 | +| **内存压力** | 及时释放 `Image` 对象,并考虑使用 `await Task.Run` 进行异步管道。 | + +这些调整即使在输入不完美的情况下,也能保持你的 **perform OCR image** 工作流的稳健性。 + +## 总结 + +恭喜你——你刚刚完成了一个 **c# OCR 教程**,实现了加载图像、**recognizes png text**,以及 **reads receipt OCR** 输出为整洁的 JSON。核心步骤(引擎设置、图像加载、OCR 执行、序列化和显示)构成了一个坚实的基础,您可以将其扩展到发票、护照或任何其他扫描文档。 + +### 接下来做什么? + +- 使用 `SkiaSharp` 试验 **load image file c#**,实现真正的跨平台支持。 +- 深入研究 `OcrResult.Words`,提取项目行、价格和日期——非常适合费用跟踪应用。 +- 将本教程与 Azure Functions 或 AWS Lambda 结合,构建无服务器收据处理 API。 + +随意修改代码,添加更多图像,甚至切换到其他语言包。OCR 的世界充满惊喜,而你现在拥有探索它们的工具。 + +祝编码愉快,愿你的收据永远可读! + +## 相关教程 + +- [使用 Aspose.OCR 进行语言选择的 C# 图像文本提取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [从图像提取文本 – 使用 Aspose.OCR for .NET 的 OCR 优化](/ocr/english/net/ocr-optimization/) +- [如何使用 OCR - 在不进行文本区域检测的情况下识别图像](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/chinese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..5d1803125 --- /dev/null +++ b/ocr/chinese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-05-25 +description: 使用 Aspose.OCR 在 C# 中将 TIFF 转换为文本。了解批量图像转文本的转换方法,并高效提取 TIFF 文件中的文本。 +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: zh +og_description: 使用 Aspose.OCR 将 TIFF 转换为文本。本指南展示批量图像转文本的转换方法,以及如何在几行 C# 代码中从 TIFF + 文件中提取文本。 +og_title: 在 C# 中将 TIFF 转换为文本 – 完整批量 OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: 在 C# 中将 TIFF 转换为文本 – 完整批量 OCR 指南 +url: /zh/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 将 TIFF 转换为文本(C#)– 完整批量 OCR 指南 + +是否曾需要 **将 TIFF 转换为文本**,却不知从何入手?你并不孤单——许多开发者在处理扫描文档时都会卡在批量 OCR 上。本文将手把手演示一个 **从 TIFF 文件提取文本** 的解决方案,使用 Aspose.OCR,并通过并行处理让大型文件夹在几秒钟内完成。 + +我们还会涉及 **批量图像转文本** 的最佳实践,最终你将拥有一个可复用的代码片段,能够将整个目录的扫描图像转换为整洁的 *.txt* 文件——非常适合索引、搜索或后续分析。 + +## 所需环境 + +- **.NET 6.0** 或更高(代码同样可以在 .NET Framework 上编译) +- **Aspose.OCR for .NET** NuGet 包(`Install-Package Aspose.OCR`) +- 包含一个或多个 *.tif* 文件的文件夹(经典的 TIFF 扫描格式) +- 你喜欢的 IDE(Visual Studio、VS Code、Rider——随你挑) + +就这些。无需外部服务、无需 API 密钥,纯 C# 加 Aspose 即可。 + +![Screenshot of a TIFF file being processed and the resulting text file](/images/ocr-result.png "OCR result showing converted TIFF to text output") + +*(Alt text: Screenshot showing converted TIFF to text output on screen)* + +## 第一步:设置 OCR 引擎 – 将 TIFF 转换为文本 + +首先,需要创建一个 `OcrEngine` 实例,并指定读取英文字符。引擎是转换的核心;正确配置可确保结果可靠。 + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*为什么重要:* +Aspose.OCR 支持数十种语言。如果你的扫描件是多语言的,只需将 `OcrLanguage.English` 改为相应的枚举值。若不指定语言,引擎会进入自动检测模式,速度更慢且准确度可能下降。 + +## 第二步:收集所有 TIFF 文件 – 高效提取 TIFF 文本 + +接下来,从你指定的文件夹中获取每个 *.tif* 文件。使用 `Directory.GetFiles` 可以得到一个干净的数组,供批处理使用。 + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*小技巧:* 若扫描文件分布在子文件夹中,可使用 `SearchOption.AllDirectories` 标志。只需注意更深的递归可能会在批处理阶段增加内存占用。 + +## 第三步:并行执行 OCR – 批量图像转文本 + +现在进入有趣的部分。Aspose.OCR 提供了静态助手 `BatchOcr.RecognizeAll`,接受文件路径数组、引擎以及 `parallelism` 提示。我们将启动四个线程,在现代四核笔记本上几乎实现线性加速。 + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*为何使用并行?* +批量处理高分辨率 TIFF 会消耗大量 CPU。将工作分配到多个线程可以让所有核心忙碌,从而显著缩短总运行时间。如果在拥有更多核心的服务器上运行,只需相应提升 `parallelism` 值。 + +## 第四步:写入输出 – 将扫描图像保存为 TXT 文件 + +最后遍历字典,将每段文本写入与原文件同名的 *.txt* 文件。这就是 **将扫描图像转换为 txt** 的实现时刻。 + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### 代码做了什么(简明中文说明) + +1. **创建** 一个设置为英文的 OCR 引擎。 +2. **收集** 目标文件夹下的所有 TIFF 文件。 +3. **调用** `BatchOcr.RecognizeAll`,使用四个线程将每张图像转换为字符串。 +4. **遍历** 结果,将 `.tif` 扩展名替换为 `.txt` 并写入磁盘。 + +这就是不到 50 行代码的完整 **将 TIFF 转换为文本** 工作流。 + +## 处理边缘情况 – 当出现问题时 + +- **缺失或损坏的 TIFF** – `BatchOcr` 会抛出 `OcrException`。如需优雅降级,请将调用包装在 `try / catch` 中。 +- **非英文文档** – 将 `OcrLanguage.English` 改为 `OcrLanguage.Spanish`、`OcrLanguage.French` 等,或使用 `OcrLanguage.AutoDetect`。 +- **超大图像** – 考虑在 OCR 前降低 DPI(`ocrEngine.ImagePreprocessing.Dpi = 200`),以节省内存,虽可能牺牲部分准确度。 +- **输出编码** – 如需特定代码页(例如 Windows‑1252),可使用 `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`。 + +## 稳健批量转换的专业技巧 + +- **记录失败**:创建 `List failedFiles`,将抛异常的文件加入列表,循环结束后写入日志。 +- **复用引擎**:同一个 `OcrEngine` 实例可在多文件间复用,切勿在循环内部实例化。 +- **验证结果**:使用 `if (string.IsNullOrWhiteSpace(extractedText))` 快速标记空白或不可读的扫描件。 +- **与 PDF 结合**:若源文件是多页 PDF,可先使用 Aspose.PDF 将每页转换为 TIFF,再执行本批处理。 + +## 后续步骤 – 超越简单转换 + +现在你已经能够 **批量提取 TIFF 文本**,接下来可以: + +- 将 *.txt* 文件导入搜索索引(Elasticsearch、Azure Cognitive Search)。 +- 对每个结果进行语言检测,以将文档路由到对应的本地化流水线。 +- 通过在原始图像上叠加 OCR 文本生成可搜索的 PDF(再次使用 Aspose.PDF)。 + +所有这些场景都基于同一个核心概念:**批量图像转文本** 是更大文档处理系统的基石。 + +--- + +### 结论 + +你已经学会了如何使用 Aspose.OCR **将 TIFF 转换为文本**,并行处理整个文件夹,将每个结果保存为整洁的 *.txt* 文件。该方案轻量、可完全配置,且已准备好投入生产——无论是数字化遗留发票、归档扫描合同,还是为文本搜索引擎提供数据。 + +动手试一试,调节并行度,让这些新生成的文本文件流入你的任意工作流。祝你 OCR 愉快! + +--- + + +## 相关教程 + +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/chinese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/chinese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..3687ee76e --- /dev/null +++ b/ocr/chinese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: 学习如何使用简约的 ASP.NET Core API 从图像中提取文本。通过 POST 上传图像,读取 multipart 表单数据并对图像执行 + OCR。 +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: zh +og_description: 使用最小化的 ASP.NET Core API 从图像中提取文本。本指南展示了如何通过 POST 上传图像、读取 multipart + 表单数据,并对图像执行 OCR。 +og_title: 在 ASP.NET Core 中从图像提取文本 – 步骤指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: 在 ASP.NET Core Minimal API 中从图像提取文本 – 完整指南 +url: /zh/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 ASP.NET Core Minimal API 中提取图像文本 – 完整指南 + +是否曾想过在不使用重量级框架的情况下**从图像中提取文本**?你并不孤单。许多开发者需要一种快速方式,让用户上传图片并返回原始字符,无论是扫描收据、数字化手写笔记,还是为搜索索引提供支持。 + +在本教程中,我们将创建一个小型的 ASP.NET Core Minimal API,能够**通过 POST 上传图像**,解析 *multipart/form‑data* 负载,然后使用单例 `OcrEngine` **对图像执行 OCR**。完成后,你将拥有一个可直接运行的应用程序,能够放入任何 .NET 8 项目中,立即开始从图像中提取文本。 + +## 你将构建的内容 + +- 一个监听 `/ocr` 的最小化 Web 应用。 +- 一个接受使用 `multipart/form-data` POST 请求发送的图像文件的端点。 +- 读取上传文件、将其传递给 OCR 引擎并返回纯文本结果的逻辑。 +- 可选的 GPU 加速代码片段(已注释),适用于拥有兼容显卡的用户。 + +**先决条件** +- .NET 8 SDK(或更高版本)。 +- 对 C# 和命令行有基本了解。 +- 一个提供 `OcrEngine` 类的 OCR 库(示例假设存在一个假想的 NuGet 包)。 + +如果你已经具备上述条件,让我们开始吧。 + +## 步骤 1:设置项目并添加 OCR 包 + +首先,创建一个新的 Web 项目并引入 OCR 库。 + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **专业提示:** 保持依赖项为最新。更新的版本通常带来性能提升,尤其是 GPU 加速推理时。 + +## 步骤 2:注册单例 OCR 引擎(主要服务) + +我们希望整个应用只使用一个 `OcrEngine` 实例——无需为每个请求创建新的引擎。将在构建器的服务容器中注册它。 + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**为什么使用单例?** +创建 OCR 引擎可能代价高昂——比如需要将神经网络权重加载到内存中。复用同一个实例可以节省 CPU 周期和内存,从而提升每次 `/ocr` 调用的响应速度。 + +## 步骤 3:构建应用程序 + +现在我们实例化 `WebApplication` 对象。 + +```csharp +var app = builder.Build(); +``` + +这行代码看起来几乎是魔法,但实际上它在内部完成了路由、middleware 和我们刚配置的 DI 容器的连接。 + +## 步骤 4:定义 POST 端点 – “通过 POST 上传图像” + +下面是本教程的核心:一个 **通过 POST 上传图像** 的端点,读取 multipart 负载并将数据交给 OCR 引擎。 + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### 逻辑拆解 + +| 步骤 | 发生了什么 | 为什么重要 | +|------|------------|------------| +| **ReadFormAsync** | 解析传入的 *multipart/form-data* 请求。 | 若不进行此操作,无法访问上传的文件。 | +| **form.Files["image"]** | 获取表单字段名为 `image` 的文件。 | 为调用方提供可预测的契约。 | +| **Content‑type check** | 验证文件是图像(例如 `image/png`)。 | 防止 OCR 引擎在非图像数据上出错。 | +| **Image.FromStream** | 将原始流转换为 `System.Drawing.Image`。 | OCR 库期望的是 `Image` 对象,而不是原始字节数组。 | +| **ocr.Recognize(img)** | 调用 OCR 引擎 **从图像识别文本**。 | 这就是核心的 **对图像执行 OCR** 步骤。 | +| **Results.Text** | 返回纯文本响应。 | 为下游服务提供简洁、可消费的格式。 | + +## 步骤 5:运行 API + +最后,启动 Web 服务器。 + +```csharp +app.Run(); +``` + +当你执行 `dotnet run` 时,API 将监听 `http://localhost:5000`(或你指定的端口)。你可以使用 `curl` 进行测试: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**预期输出:** 控制台将打印识别出的字符,例如: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +如果图像模糊或语言不受支持,OCR 引擎将返回空字符串或错误信息——在生产代码中需要处理这些情况。 + +## 边缘情况与最佳实践 + +### 1. 大文件 + +默认的请求体大小限制为 30 MB。对于更大的扫描文件,你可能需要调整: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. 异步 OCR + +某些 OCR 库提供异步方法(`RecognizeAsync`)。如果你的库支持,请将 `ocr.Recognize(img)` 替换为 `await ocr.RecognizeAsync(img)` 并将 lambda 标记为 `async`。 + +### 3. 安全考虑 + +- **在加载到内存之前验证文件大小**。 +- **如果将文件写入磁盘,需对文件名进行清理**。 +- **对端点进行速率限制**,以防止拒绝服务攻击。 + +### 4. GPU 加速 + +如果取消注释 `engine.GpuDevice = new GpuDevice(0);` 并且你的硬件支持 CUDA 或 DirectML,你将在高分辨率图像上看到显著的速度提升。 + +## 完整工作示例 + +下面是完整的 `Program.cs`,你可以直接复制粘贴到全新的 Minimal API 项目中。 + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +保存后,运行 `dotnet run`,即可随时 **从图像中提取文本**。 + +## 结论 + +我们已经完整演示了使用 ASP.NET Core Minimal API **从图像中提取文本的端到端解决方案**。从项目脚手架开始,我们 **注册了单例 OCR 引擎**,构建了一个 **通过 POST 上传图像** 的端点,**读取 multipart 表单数据**,最终 **对图像执行 OCR** 并返回干净的纯文本。 + +从这里你可以: + +- 为更丰富的响应添加 JSON 包装。 +- 接入数据库以存储提取的文本。 +- 扩展对多语言的支持(如 `OcrLanguage.Spanish` 等)。 + +该模式易于扩展——只需将相同的端点放入更大的微服务中,或在 API 网关后面公开即可。 + +如果对处理 PDF、批量处理或 GPU 调优有疑问,请留言,祝编码愉快! + +## 相关教程 + +- [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/chinese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/chinese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..bfa62c9b6 --- /dev/null +++ b/ocr/chinese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,310 @@ +--- +category: general +date: 2026-05-25 +description: 使用 C# 和 Aspose OCR 从图像中提取文本。了解如何将 JPG 转换为文本、加载图像进行 OCR,并快速获得可靠的结果。 +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: zh +og_description: 使用 C# 从图像中提取文本。本指南展示如何将 JPG 转换为文本,加载图像进行 OCR,以及处理多语言内容。 +og_title: 在 C# 中从图像提取文本 – Aspose OCR 教程 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: 在 C# 中从图像提取文本 – 完整的 Aspose OCR 指南 +url: /zh/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 使用 C# 从图像中提取文本 – 完整 Aspose OCR 指南 + +是否曾想过仅用纯 C# 代码**从图像中提取文本**?你并不孤单。无论是数字化收据、扫描路标,还是单纯对 OCR 感兴趣,从图片中提取字符都是一项实用技能。在本教程中,我们将演示一个完整、可运行的示例,展示如何使用 Aspose.OCR **从图像中提取文本**,并涵盖**将 jpg 转换为文本**、**加载图像进行 OCR**以及彻底解答“**如何 OCR 图像**”这一经典问题。 + +阅读完本指南后,你将拥有一个独立的控制台应用程序,能够读取 JPEG 文件,识别乌克兰语(或任何受支持的语言),并将结果打印到控制台。没有模糊的引用,没有缺失的代码——只有可以直接复制粘贴并运行的完整解决方案。 + +--- + +## 你将学到 + +* 如何安装 Aspose.OCR NuGet 包。 +* 在 C# 中**加载图像进行 OCR**的完整代码。 +* 如何设置语言并真正**从图像中提取文本**。 +* 高效**将 jpg 转换为文本**的技巧。 +* 常见陷阱及规避方法。 + +如果你已经搭建好 .NET 开发环境,直接进入下一步即可。否则,请先阅读下面的前置条件。 + +--- + +## 前置条件 + +| 要求 | 为什么重要 | +|------|------------| +| .NET 6.0 SDK(或更高) | 为控制台应用提供运行时。 | +| Visual Studio 2022 或 VS Code | 便于编辑和调试。 | +| 首次运行时需要网络连接 | NuGet 需要下载 Aspose.OCR。 | +| 一张你想处理的 JPEG 图像(例如 `ukrainian_sign.jpg`) | OCR 引擎的源文件。 | + +> **专业提示:** 如果你使用 Linux 或 macOS,使用 .NET CLI(`dotnet new console`)同样可以运行本代码,无需沉重的 IDE。 + +--- + +## 第一步 – 通过 NuGet 安装 Aspose.OCR + +打开终端(或包管理器控制台),运行: + +```bash +dotnet add package Aspose.OCR +``` + +这行命令会拉取最新的 Aspose.OCR 二进制文件及其所有传递依赖,无需手动处理 DLL。 + +--- + +## 第二步 – 创建 OCR 引擎(提取核心) + +库准备好后,我们可以实例化 `OcrEngine`。该对象负责**从图像中提取文本**。 + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **为什么重要:** 引擎封装了 OCR 算法、语言模型和配置选项。一次实例化后在多张图片间复用,既省内存又高效。 + +--- + +## 第三步 – 加载图像进行 OCR(并设置语言) + +接下来告诉引擎要读取哪张图片,这正是**加载图像进行 OCR**的用法。 + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **边缘情况:** 如果文件不存在,`Image.FromFile` 会抛出 `FileNotFoundException`。在生产代码中请使用 try‑catch 包裹。 + +--- + +## 第四步 – 执行 OCR 并提取文本 + +图片加载完毕后,引擎即可**从图像中提取文本**。`Recognize` 方法负责核心工作。 + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +如果一切顺利,`recognizedText` 将包含 OCR 引擎读取到的纯文本。 + +--- + +## 第五步 – 将 JPG 转换为文本(完整封装) + +到目前为止的代码已经**将 jpg 转换为文本**,下面把它封装成一个可重复调用的方法。 + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +现在你只需这样调用: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**预期输出**(为简洁起见已截断): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +如果图像中是英文文本,只需将 `OcrLanguage.English` 替换为对应语言,即可看到相应输出。 + +--- + +## 第六步 – 处理常见的“如何 OCR 图像”问题 + +### 6.1 我可以 OCR PNG 或 BMP 吗? + +完全可以。`Image.FromFile` 支持 System.Drawing 能识别的所有格式,只需把路径指向 `.png` 或 `.bmp` 文件,其余代码保持不变。 + +### 6.2 如果图像分辨率太低怎么办? + +低于 300 dpi 时 OCR 准确率会急剧下降。可以在送入引擎前使用 `Graphics` 将图像放大: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Aspose.OCR 需要许可证吗? + +Aspose 提供带水印的免费试用版。正式使用时请购买许可证并添加: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## 完整可运行示例 + +下面是一个完整的、可直接运行的控制台应用程序,演示了**如何 OCR 图像**、**加载图像进行 OCR**以及**将 jpg 转换为文本**的完整流程。 + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**运行方式** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +运行后,你应当在控制台看到提取的文本,证明已成功使用 C# **从图像中提取文本**。 + +--- + +## 常见陷阱与专业技巧 + +| 问题 | 成因 | 解决方案 | +|------|------|----------| +| 输出为空 | 图像过暗或对比度低。 | 使用 `Bitmap` 预处理,提高亮度。 | +| 语言错误 | `Language` 属性默认英文。 | 明确设置 `ocrEngine.Language = OcrLanguage.Ukrainian;`(或目标语言)。 | +| 内存溢出 | 大图未及时释放。 | 将 `Image.FromFile` 包在 `using` 块中(如示例所示)。 | +| 试用水印 | 未使用许可证。 | 在 `Main` 开头尽早加载购买的许可证。 | + +--- + +## 结论 + +我们已经完整覆盖了在 C# 中**从图像中提取文本**的全部步骤——从安装 Aspose.OCR、**加载图像进行 OCR**到**将 jpg 转换为文本**以及多语言处理。完整示例将所有环节串联,为任何 OCR 项目提供可靠的基础。 + +接下来,你可以进一步探索: + +* 使用 **如何 OCR 图像** 的流式方式(`MemoryStream`)而非文件。 +* 添加 **c# image to text** 的后处理,如拼写检查。 +* 将 OCR 步骤集成到更大的流水线(例如将结果存入数据库)。 + +尽情尝试不同语言、图像格式和预处理技巧吧。OCR 既是艺术也是科学,玩得越多,效果越好。 + +祝编码愉快,愿你的图像永远可读! + +## 相关教程 + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/chinese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..cb604e4cd --- /dev/null +++ b/ocr/chinese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,296 @@ +--- +category: general +date: 2026-05-25 +description: 如何在 C# 中使用 OCR 从图像文件中提取文本。学习使用 Aspose.OCR 通过几个简单步骤识别 JPG 中的中文字符。 +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: zh +og_description: 如何在 C# 中使用 OCR 从图像文件中提取文本。本指南展示了如何使用 Aspose.OCR 从 JPG 中识别中文字符。 +og_title: 如何在 C# 中使用 OCR – 从 JPG 识别中文文本 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: 如何在 C# 中使用 OCR – 从 JPG 识别中文文本 +url: /zh/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中使用 OCR – 从 JPG 识别中文文本 + +有没有想过 **如何使用 OCR** 从手机拍摄的图片中提取文字?你并不孤单。在许多实际项目中——比如收据扫描器、翻译应用或自动数据录入——你需要快速且可靠地 **从图像中提取文本**。 + +在本教程中,我们将演示一个完整且可运行的示例,能够 **从 JPG 文件中识别文本**,甚至能够处理使用 **OCR Chinese Simplified** 语言包的 **识别中文字符** 的棘手情况。完成后,你将拥有一个独立的控制台应用程序,它会将检测到的字符串打印到控制台,无需额外手动下载。 + +> **快速提示:** 该代码适用于 Aspose.OCR ≥ 23.7,它会在首次使用时自动获取语言资源。如果你使用的是较旧的版本,则需要手动添加语言。 + +## 前置条件 + +- .NET 6.0 SDK 或更高版本(示例针对 .NET 6,但 .NET 5 也可使用) +- 最近版本的 Visual Studio 2022 或带有 C# 扩展的 VS Code +- 首次语言下载所需的互联网连接 +- 包含简体中文文本的 JPG 图像(我们将其命名为 `chinese_sign.jpg`) + +就是这样——无需笨重的 OCR 引擎,也不需要处理本机 DLL。只需几条 NuGet 命令和几行代码。 + +## 步骤 1:通过 NuGet 安装 Aspose.OCR + +首先:我们需要 OCR 库。在项目文件夹中打开终端并运行: + +```bash +dotnet add package Aspose.OCR +``` + +或者,如果你更喜欢 Visual Studio UI,右键点击 **Dependencies → Manage NuGet Packages**,搜索 “Aspose.OCR”,然后点击 **Install**。 + +**专业提示:** 保持你的包为最新版本。每个小版本都会加入新的语言包和性能改进。 + +## 步骤 2:创建新的控制台项目(如果尚未创建) + +如果你从头开始,创建一个全新的控制台应用程序: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +现在你已经拥有一个准备好放置 OCR 代码的 `Program.cs` 文件。 + +## 步骤 3:编写 OCR 代码 – 从 JPG 识别简体中文 + +打开 `Program.cs` 并将其内容替换为以下代码。每行都带有注释,帮助你了解我们 *为什么* 要这么做,而不仅仅是 *做了什么*。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 背后发生了什么? + +- **`OcrEngine.Language`** 告诉 Aspose 使用哪个词典。通过选择 `ChineseSimplified`,我们指示引擎使用简体中文语言包。 +- **首次下载**:当调用 `Recognize` 时,SDK 会访问 Aspose 的 CDN,下载约 6 MB 的语言文件并在本地缓存,然后继续进行 OCR。后续调用则是瞬时完成。 +- **`Image.FromFile`** 支持 .NET 能解码的任何栅格格式——JPG、PNG、BMP——因此你可以 **从图像中提取文本**,不仅限于 JPG。 + +## 步骤 4:运行应用并验证输出 + +构建并运行: + +```bash +dotnet run +``` + +你应该会看到类似如下的输出: + +``` +=== Recognized Text === +欢迎光临 +``` + +如果控制台打印出乱码或空字符串,请仔细检查以下事项: + +1. 图像确实包含清晰、高对比度的中文字符。 +2. 文件路径正确(没有多余的空格或缺少扩展名)。 +3. 你的机器能够访问 `https://download.aspose.com` 以获取语言包。 + +## 步骤 5:处理边缘情况和常见陷阱 + +### 5.1 处理低质量图像 + +当源图像模糊、噪声大或光照不足时,OCR 的准确率会下降。一个快速的解决方案是对图像进行预处理: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 在无头环境中运行 + +如果你将应用部署到没有 GUI 的 Linux 容器,请确保已安装 `libgdiplus` 库(`System.Drawing` 所需): + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 手动缓存语言包 + +你可以一次性下载语言文件,并通过 `License` API 将其指向 Aspose,这样就消除了首次网络请求。对于离线场景非常实用。 + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## 完整工作示例(全功能) + +下面是可以直接复制粘贴到 `Program.cs` 的 *完整* 程序。没有隐藏代码,也没有外部脚本。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 预期输出 + +如果 JPG 包含短语 “欢迎光临”,控制台将输出: + +``` +=== Recognized Text === +欢迎光临 +``` + +随意将图像替换为其他简体中文标志、街道名称或产品标签——引擎会尽力识别。 + +## 结论 + +我们刚刚介绍了在 C# 中 **如何使用 OCR** 来 **从图像中提取文本**,特别是解决在 **JPG** 中 **识别中文字符** 的挑战。通过利用 Aspose.OCR 的即时语言下载,你可以保持部署轻量化,同时开箱即支持 **OCR Chinese Simplified**。 + +接下来可以尝试以下想法: + +- **批量处理**:遍历文件夹中的图像并将每个结果写入 CSV。 +- **结合翻译 API**:将识别的字符串输入 Azure Translator,实现实时多语言应用。 +- **探索其他语言**:将 `OcrLanguage.ChineseSimplified` 替换为 `Japanese` 或 `Arabic`,观察相同代码的适配情况。 + +对性能调优、授权或将 OCR 集成到 Web 服务有疑问?在下方留言——祝编码愉快! + +--- + +![显示如何在 C# 中使用 OCR 从 JPG 图像识别中文文本的控制台输出截图](ocr-chinese-demo.png "如何使用 OCR 控制台输出") + +## 相关教程 + +- [使用 Aspose.OCR 进行语言选择的 C# 图像文本提取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [使用 Aspose OCR 识别多语言图像文本](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [通过准备矩形在 OCR 中提取图像文本的方法](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/chinese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/chinese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..d683d8141 --- /dev/null +++ b/ocr/chinese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: 学习如何在 C# 中使用 Aspose OCR 对俄文文本进行 OCR,并从图像中提取文字。提供一步步的代码,快速将图像转换为 C# 文本。 +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: zh +og_description: 在 C# 中轻松实现俄文 OCR。学习如何从图像中提取文本、将图像转换为文本(C#),以及使用 Aspose OCR 加载图像进行 + OCR。 +og_title: 在 C# 中 OCR 俄文文本 – 完整的 Aspose OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: 在 C# 中 OCR 俄文文本 – 使用 Aspose OCR 的完整指南 +url: /zh/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Russian Text in C# – Complete Guide Using Aspose OCR + +是否曾需要在 C# 中对俄文文本进行 OCR,却不确定该使用哪个库?你并不孤单。要从西里尔字母图像中获取干净、可读的字符,往往像在解码密码——尤其是当你没有设置正确的语言模型时。 + +在本教程中,我们将通过一个动手示例,展示如何 **从图像中提取文本**,实现 *image to text C#* 的转换,并处理俄语识别的细节,使用 Aspose OCR。完成后,你将拥有一个可直接运行的控制台应用程序,能够加载图像进行 OCR,打印识别出的字符串,并为更高级的场景奠定坚实基础。 + +## What You’ll Learn + +- 如何安装并配置 **Aspose OCR C#** 以支持俄语。 +- **加载图像进行 OCR** 并调用引擎的完整步骤。 +- 处理常见问题的技巧,如缺少语言资源或图像模糊。 +- 扩展方案,例如批量处理多个文件或调整置信度阈值。 + +无需事先了解 Aspose;只要对 C# 和 .NET 有基本了解即可上手。 + +## Prerequisites + +在开始之前,请确保你具备以下条件: + +1. 已安装 **.NET 6.0**(或更高)SDK —— 代码可在 .NET Core 与 .NET Framework 上运行。 +2. **Visual Studio 2022**(或任意你喜欢的 IDE)。 +3. **Aspose.OCR for .NET** NuGet 包 —— 可从 Aspose 官网获取免费试用密钥。 +4. 一个 **俄语语言模型** 文件(`rus.traineddata`)——从 Aspose 资源页面下载,并放置在后续会引用的文件夹中。 +5. 一张包含清晰西里尔字母的示例图像(`russian_doc.png`)。 + +准备好了吗?那我们开始吧。 + +## Step 1: Set Up the Project and Install Aspose OCR + +首先,创建一个新的控制台项目: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +现在添加 Aspose OCR 包: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** 如果使用试用许可证,请将 `Aspose.Total.lic` 文件放在手边;在代码中加载它可以避免水印。 + +安装完包后,打开 `Program.cs`。你会看到默认的 `Main` 方法——将其内容替换为我们即将构建的骨架代码。 + +## Step 2: Configure the OCR Engine for Russian Language + +核心对象是 `OcrEngine`。我们需要告诉它两件事:识别哪种语言以及语言模型文件所在位置。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Why this matters:** 如果不设置 `Language = OcrLanguage.Russian`,引擎默认使用英语,所有西里尔字符都会变成乱码。`ResourceFolder` 指向包含 `rus.traineddata` 的目录;若缺失,Aspose 会抛出 *resource not found* 异常。 + +## Step 3: Load the Image for OCR + +接下来需要 **加载图像进行 OCR**。Aspose OCR 使用 `System.Drawing.Image`,因此任何受支持的格式(PNG、JPEG、BMP 等)都可以。确保文件路径正确;相对路径在将图像放在可执行文件旁时同样适用。 + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** 若图像体积较大(超过 5 MB),建议先缩小。DPI 过低会导致识别率下降,而巨大的文件会增加内存压力。必要时可使用 `Graphics` 进行快速缩放。 + +## Step 4: Recognize the Text – From Image to Text C# Style + +引擎配置好、图像加载完后,实际识别只需一次调用: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +运行程序(`dotnet run`)后,你应看到类似下面的输出: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +如果输出是乱码,请再次确认: + +- `rus.traineddata` 文件已放在 `ResourceFolder` 中。 +- 图像没有过于模糊;考虑在 OCR 前先做二值化处理。 +- 语言设置确实为 `OcrLanguage.Russian`。 + +## Step 5: Fine‑Tuning and Common Pitfalls + +### Adjusting Confidence Threshold + +Aspose OCR 在内部为每个字符返回置信度值。虽然 API 未直接暴露,但可以开启 **详细输出** 来查看低置信度的词: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +如果发现误识别频繁,可尝试: + +- **预处理**:将图像转为灰度、提升对比度或使用中值滤波。 +- **DPI 设置**:确保图像至少为 300 DPI,以适配西里尔文字。 + +### Batch Processing Multiple Images + +若需要 **批量提取图像文本**,可将识别逻辑放入循环: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +这样每个 PNG 都会生成对应的 `.txt` 文件,方便文档归档。 + +### Handling Unicode Output + +西里尔字符属于 Unicode,请确保控制台编码能够显示它们: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +将此行放在 `Main` 方法开始后。若不设置,可能会看到问号(`?`)而非俄文字母。 + +## Full Working Example + +下面是完整的、可直接运行的代码。复制粘贴到 `Program.cs`,根据实际路径进行调整,即可使用。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**预期输出**(假设示例图像中的文字为 “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +若出现其他结果,请回到第 5 步的故障排除章节检查设置。 + +## Conclusion + +现在,你已经拥有一个完整的 **在 C# 中使用 Aspose OCR 进行俄文 OCR** 的端到端示例。从库的安装、俄语语言模型的配置,到加载图像并转换为干净的 Unicode 文本,全部步骤已覆盖。 + +记住,可靠的 OCR 依赖于良好的源材料:清晰的字体、足够的 DPI 以及正确的语言资源。掌握基础后,你可以进一步实现批量处理、与云存储集成,甚至结合 AI 进行拼写检查等后处理。 + +### What’s Next? + +- 探索 **aspose ocr c#** 的高级选项,如布局分析或 PDF 输出。 +- 将其与 **extract text from image** 工作流结合,在 Azure Functions 中实现无服务器处理。 +- 尝试其他语言——只需将 `OcrLanguage.Russian` 替换为 `OcrLanguage.English` 或其他支持的代码。 + +有问题或遇到难以识别的图像?欢迎在下方留言,祝编码愉快! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + +## Related Tutorials + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/chinese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..a15d0bb1a --- /dev/null +++ b/ocr/chinese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-25 +description: 使用 Aspose OCR 在 C# 中识别图像中的文本。了解如何加载用于 OCR 的图像、设置 OCR 语言、创建 OCR 引擎以及从 + TIFF 中提取文本。 +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: zh +og_description: 使用 Aspose OCR 在 C# 中识别图像文本。本教程展示了如何创建 OCR 引擎、加载 OCR 图像、设置 OCR 语言以及从 + TIFF 中提取文本。 +og_title: 使用 Aspose OCR 从图像识别文本 – 完整 C# 指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: 使用 Aspose OCR 从图像识别文本 – 完整 C# 指南 +url: /zh/net/text-recognition/recognize-text-from-image-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 从图像识别文本 – 完整 C# 指南 + +是否曾经需要**从图像识别文本**,但不确定哪个库既能提供速度又能保证准确性?你并不孤单。在许多发票处理或归档项目中,最大的问题是如何在不编写自定义解析器的情况下,从 TIFF 文件中获取干净、可搜索的文本。 + +事实是:Aspose OCR for .NET 让整个流程变得轻而易举。在本指南中,我们将逐步演示你需要的所有内容——安装包、**创建 OCR 引擎**、加载 TIFF、设置 OCR 语言,最后**从 TIFF 中提取文本**。完成后,你将拥有一个可直接运行的控制台应用程序,能够快速**从图像识别文本**。 + +## Prerequisites + +- .NET 6.0 或更高(代码同样适用于 .NET Core 和 .NET Framework) +- Visual Studio 2022(或任何你喜欢的 IDE) +- Aspose.OCR NuGet 包(GPU 支持需要 `Aspose.OCR.Gpu` 插件) +- 如果想要更快的速度,需要具备 CUDA 支持的 GPU(可选,但推荐) + +> **技巧提示:** 如果没有 GPU,只需省略 `GpuDevice` 行,引擎会自动回退到 CPU。 + +## Step 1: Install Aspose OCR and Create OCR Engine + +首先,通过 NuGet 添加必要的包: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +现在我们可以**创建 OCR 引擎**。该对象是整个过程的核心;它保存了运行设备和内存限制等配置。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**为什么这很重要:** 将引擎绑定到 GPU 后,你可以显著缩短**从图像识别文本**所需的时间,尤其是处理大量高分辨率 TIFF 时。 + +## Step 2: Load Image for OCR + +接下来,我们需要**加载图像进行 OCR**。Aspose.OCR 使用 `System.Drawing.Image`,因此任何 GDI+ 支持的格式(包括多页 TIFF)都可以。 + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +如果处理多页 TIFF,可以使用 `image.SelectActiveFrame` 循环遍历页面,但在大多数情况下一次调用即可满足需求。 + +## Step 3: Set OCR Language + +引擎不会自动识别你要扫描的语言。请在运行识别器之前**设置 OCR 语言**;否则会得到大量乱码。 + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **你知道吗?** 在运行时切换语言开销很小——甚至可以在页面之间更改此属性,以处理混合语言的文档。 + +## Step 4: Perform the Recognition – Recognize Text from Image + +现在进入有趣的部分:实际**从图像识别文本**。`Recognize` 方法返回包含所有检测到字符的普通字符串。 + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +如果需要置信度分数或边界框,可以使用返回 `OcrResult` 对象的重载,但对于大多数提取任务,普通字符串已足够。 + +## Step 5: Extract Text from TIFF (and handle multi‑page files) + +当源文件是包含多页的 TIFF 时,需要对每一帧重复步骤 2‑4。下面是一个快速循环,**逐页从 TIFF 中提取文本**: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +上述代码会打印每页提取的文本,使得将结果导入数据库或搜索索引变得非常简单。 + +## Step 6: Display or Persist the Extracted Text + +最后,让我们**显示提取的文本**,并可选择将其写入文件以便后续处理。 + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +运行程序后应输出识别的字符,并在源 TIFF 旁边创建 `extracted_text.txt` 文件。 + +--- + +## Common Questions & Edge Cases + +- **如果我的 GPU 未被检测到怎么办?** + 删除 `GpuDevice` 行;引擎会自动切换到 CPU 模式。性能会变慢,但结果仍然准确。 + +- **我可以处理 PNG 或 JPEG 文件吗?** + 当然可以——`Image.FromFile` 支持 System.Drawing 支持的任何格式,因此无论扩展名如何,都可以**加载图像进行 OCR**。 + +- **如何处理低分辨率扫描?** + 在调用 `Recognize` 之前提升 `ocrEngine.PreprocessOptions.Dpi`。更高的 DPI 为引擎提供更多像素,从而提升准确性。 + +- **TIFF 的大小有没有限制?** + `GpuMemoryLimit` 属性限制 GPU 使用量。如果达到上限,引擎会对剩余页面回退到 CPU。 + +## Conclusion + +现在,你已经拥有一个完整的、可投入生产的代码片段,使用 Aspose OCR 在 C# 中**从图像识别文本**。本教程涵盖了如何**创建 OCR 引擎**、**加载图像进行 OCR**、**设置 OCR 语言**以及**从 TIFF 中提取文本**——并利用 GPU 加速提升速度。 + +从这里你可能: + +- 尝试不同的语言(`OcrLanguage.Spanish`、`OcrLanguage.ChineseSimplified` 等)。 +- 将输出集成到可搜索的 ElasticSearch 索引中。 +- 添加后处理(拼写检查、正则清理)以提升数据质量。 + +在自己的发票批次上试一试,调整内存限制,观察 OCR 性能飞速提升。祝编码愉快! + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..4c636937d 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. +### [Vytvořte OCR engine v C# – kompletní průvodce](./create-ocr-engine-in-c-complete-guide/) +Kompletní průvodce vytvořením OCR enginu v C# pomocí Aspose.OCR pro přesné rozpoznávání textu. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/czech/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..725d180e6 --- /dev/null +++ b/ocr/czech/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Vytvořte OCR engine v C# a naučte se, jak v několika řádcích kódu zkontrolovat + jeho evaluační režim a licenční stav. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: cs +og_description: Vytvořte OCR engine v C# a okamžitě zjistěte, jak detekovat evaluační + režim a zobrazit stav licence. +og_title: Vytvořte OCR engine v C# – průvodce krok za krokem +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Vytvořte OCR engine v C# – Kompletní průvodce +url: /cs/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Vytvoření OCR enginu v C# – Kompletní průvodce + +Už jste se někdy zamýšleli, jak **vytvořit OCR engine** objekty v C# bez prohledávání nekonečných dokumentací? Nejste v tom sami. Mnoho vývojářů narazí na problém, když potřebují spustit OCR engine, ověřit, zda běží v režimu zkušební verze, a zobrazit stav licencování uživatelům. + +V tomto tutoriálu vás provedeme stručným, end‑to‑end příkladem, který **vytvoří OCR engine**, zkontroluje jeho **režim hodnocení OCR enginu** a vytiskne přátelskou zprávu o stavu licencování. Na konci budete mít připravenou spustitelnou konzolovou aplikaci a jasný mentální model pro práci s licencováním OCR ve vašich projektech. + +## Co se naučíte + +- Jak vytvořit instanci `OcrEngine` (jádro každého OCR workflow). +- Proč je detekce **evaluation mode** důležitá pro soulad a uživatelskou zkušenost. +- Nejlepší způsob, jak **check OCR license** stav a reagovat na neočekávané stavy. +- Běžné úskalí — null reference, výjimky a nesoulad verzí. + +Nejsou potřeba žádné externí nástroje kromě OCR SDK, které již máte nainstalované. Pokud jste obeznámeni se základní syntaxí C#, můžete začít. + +## Požadavky + +- .NET 6.0 nebo novější (kód se kompiluje s .NET Core i .NET Framework). +- OCR SDK, který poskytuje třídu `OcrEngine` s vlastností `IsEvaluation` (například hypotetický `MyOcrSdk`). +- Textový editor nebo IDE (Visual Studio, VS Code, Rider — vyberte si svůj oblíbený). + +To je vše. Ponořme se. + +## Krok 1: Vytvořte nový konzolový projekt + +Nejprve vytvořte novou čistou konzolovou aplikaci, abyste mohli kód spustit izolovaně. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Otevřete vygenerovaný soubor `Program.cs`. Nahraďte jeho obsah kompletním příkladem, který **creates OCR engine** instance a zpracovává licencování. + +## Krok 2: Naimportujte jmenný prostor OCR SDK + +Předpokládejme, že SDK je přidáno přes NuGet (`MyOcrSdk` je zástupný název), přidejte using direktivu na začátek souboru. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Pokud jste ještě balíček nepřidali, spusťte: + +```bash +dotnet add package MyOcrSdk +``` + +> **Tip:** Udržujte verzi SDK aktuální; novější vydání často zlepšují detekci evaluation‑mode. + +## Krok 3: Vytvořte instanci OCR Engine + +Nyní konečně **create OCR engine** objekty. Toto je jádro každého OCR workflow — představte si to jako mozek, který později bude číst obrázky. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Proč je tento krok zásadní? `OcrEngine` zapouzdřuje veškerou konfiguraci, jazykové balíčky a licenční data. Bez něj nemůžete zpracovávat obrázky ani dotazovat se na flag hodnocení. + +> **Poznámka:** Některé SDK umožňují předat objekt konfigurace do konstruktoru (např. jazyk, DPI). Pokud potřebujete vlastní nastavení, upravte řádek podle toho. + +## Krok 4: Zjistěte režim hodnocení OCR Engine + +Většina OCR dodavatelů poskytuje zkušební verzi, která běží v **evaluation mode**, dokud není zadán platný licenční klíč. Vědět, zda jste v režimu zkušební verze, vám umožní zobrazit vhodné UI prvky nebo omezit určité funkce. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Vlastnost `IsEvaluation` vrací `true`, když je engine nelicencovaný nebo používá časově omezenou zkušební verzi. Je to rychlý, spolehlivý způsob, jak chránit prémiové funkce. + +### Co když vlastnost chybí? + +Starší verze SDK mohou místo toho poskytovat metodu `GetLicenseInfo()`. V takovém případě byste prozkoumali vrácený objekt na flag `IsTrial`. Vždy konzultujte changelog SDK při aktualizaci. + +## Krok 5: Zobrazte aktuální stav licencování + +Nakonec zobrazíme uživateli, zda je engine licencovaný nebo stále v zkušební verzi. Jednoduchý console write‑line stačí, ale můžete jej přizpůsobit pro GUI aplikace. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Ternární operátor udržuje kód přehledný a zprávy jsou dostatečně jasné pro koncové uživatele nebo vývojáře čtoucí logy. + +## Kompletní funkční příklad + +Spojením všeho dohromady získáte samostatný program, který můžete zkopírovat do `Program.cs` a spustit pomocí `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Očekávaný výstup + +- **Zkušební verze:** + `Running in evaluation mode – limited functionality.` + +- **Licencovaná verze:** + `Licensed – full OCR capabilities enabled.` + +Pokud SDK vyhodí výjimku (např. chybějící nativní DLL), catch blok vytiskne užitečnou chybovou zprávu místo zhroucení celé aplikace. + +## Zpracování okrajových případů a běžných úskalí + +### 1. Null instance enginu + +Ačkoliv konstruktor obvykle vrací platný objekt, některé SDK mohou vrátit `null`, pokud chybí požadované nativní závislosti. Chraňte se před tím: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Vypršení licence během běhu + +Zkušební licence může během relace vypršet. Pravidelně znovu dotazujte `IsEvaluation`, pokud vaše aplikace běží dlouho. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Různé názvy vlastností mezi verzemi + +Starší vydání mohou poskytovat `engine.EvaluationMode` nebo `engine.License.IsTrial`. Při aktualizaci prohledejte poznámky k vydání SDK pro breaking changes. + +### 4. Vícevláknové scénáře + +Pokud spouštíte několik OCR workerů, vytvořte **jeden OCR engine na vlákno**, pokud SDK výslovně nepodporuje sdílení mezi vlákny. Sdílení jediného enginu může vést k závodním podmínkám a nesprávnému čtení licencí. + +## Tipy pro produkční nasazení + +- **Uložte do cache stav licencování** po prvním ověření, aby se předešlo zbytečným voláním vlastností. +- **Zaznamenejte licenční klíč** (maskovaný) při startu pro auditní záznamy — pomáhá podpoře diagnostikovat problémy s licencí. +- **Poskytněte UI přepínač**, který informuje uživatele, že jsou v režimu zkušební verze, a nabízí tlačítko „Koupit licenci“. +- **Automatizujte obnovu licence** pomocí aktivačního API SDK, pokud je k dispozici, aby byl uživatelský zážitek plynulý. + +## Závěr + +Právě jsme **created OCR engine** objekty během několika řádků, zkontrolovali **OCR engine evaluation mode** a vytiskli jasnou zprávu o **OCR licensing status**. Kompletní příklad funguje ihned, elegantně ošetřuje chyby a zdůrazňuje „proč“ za každým krokem — takže jej můžete přizpůsobit pro desktop, web nebo serverové scénáře. + +Dále můžete zkusit: + +- Vkládání obrázků do `engine.Recognize` a zpracování podpory více jazyků. +- Použití **check OCR license** API k programatické aktivaci zakoupeného klíče. +- Integrace s UI frameworky (WinForms, WPF, MAUI) pro zobrazení licenčních odznaků. + +Vyzkoušejte je a získáte robustní OCR základ připravený pro jakoukoliv aplikaci. Šťastné programování! + +## Související tutoriály + +- [Jak extrahovat OCR – OCR konfigurace](/ocr/english/net/ocr-configuration/) +- [Jak získat OCR výsledky s Aspose.OCR pro .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Jak OCR PDF v .NET s Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/ocr-optimization/_index.md b/ocr/czech/net/ocr-optimization/_index.md index 73afa8ddc..99482a771 100644 --- a/ocr/czech/net/ocr-optimization/_index.md +++ b/ocr/czech/net/ocr-optimization/_index.md @@ -70,6 +70,8 @@ Prozkoumejte bezproblémovou integraci OCR s Aspose.OCR pro .NET. Rozpoznávejte Odemkněte potenciál Aspose.OCR pro .NET s naším komplexním průvodcem. Naučte se krok za krokem, jak připravit obdélníky pro rozpoznávání obrázků. Pozvedněte své .NET aplikace s bezproblémovou integrací OCR. ### [Předzpracovatelské filtry pro obrázek v OCR rozpoznávání obrázků](./preprocessing-filters-for-image/) Prozkoumejte Aspose.OCR pro .NET. Zvyšte přesnost OCR pomocí předzpracovatelských filtrů. Stáhněte si nyní pro bezproblémovou integraci. +### [Předzpracování obrázku pro OCR – Kompletní průvodce Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Kompletní průvodce předzpracováním obrázku pro OCR v Aspose C#. ### [Korekce výsledků s kontrolou pravopisu v OCR rozpoznávání obrázků](./result-correction-with-spell-checking/) 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/) diff --git a/ocr/czech/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/czech/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..db65280a1 --- /dev/null +++ b/ocr/czech/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Předzpracujte obrázek pro OCR pomocí Aspose, abyste zlepšili přesnost + OCR, a spusťte OCR na souborech JPEG. Naučte se, jak pomocí Aspose extrahovat text + v přehledném tutoriálu krok za krokem. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: cs +og_description: Předzpracujte obrázek pro OCR pomocí Aspose, abyste zvýšili přesnost + OCR. Postupujte podle tohoto návodu k provedení OCR na JPEG a extrahování textu + pomocí Aspose v C#. +og_title: Předzpracování obrázku pro OCR – Aspose C# návod +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Předzpracování obrázku pro OCR – Kompletní průvodce Aspose C# +url: /cs/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Předzpracování obrázku pro OCR – Kompletní průvodce Aspose C# Guide + +Už jste se někdy zamýšleli, jak **předzpracovat obrázek pro OCR**, aby text byl pokaždé čistý? Nejste jediní – vývojáři neustále bojují s šumivými skeny, JPEGy s nízkým kontrastem a nepředvídatelným osvětlením. Dobrá zpráva? S několika chytrými úpravami můžete **zlepšit přesnost OCR** dramaticky a Aspose to usnadňuje. + +V tomto tutoriálu projdeme reálným příkladem, který vám ukáže, jak **spustit OCR na JPEG** obrázcích, použít vlastní pipeline pro zpracování obrázků a nakonec **extrahovat text pomocí Aspose**. Na konci budete mít připravený úryvek C#, který můžete vložit do libovolného .NET projektu. + +## Co se naučíte + +- Proč je předzpracování důležité a které filtry přinášejí největší zisk. +- Jak nakonfigurovat `ImageProcessingOptions` v Aspose.OCR pro vyrovnání, odšumění, binarizaci a zvýšení kontrastu. +- Přesný kód potřebný k **spuštění OCR na JPEG** souborech a získání čistého textu. +- Tipy a úskalí, která udržují vaši OCR pipeline robustní v produkci. + +Předchozí zkušenost s Aspose není nutná; stačí základní znalost C# a Visual Studio (nebo vaše oblíbené IDE). Pojďme na to. + +![Příklad předzpracování obrázku pro OCR](preprocess-ocr.png "Předzpracování obrázku pro OCR") + +## Krok 1: Nastavení Aspose.OCR enginu – Předzpracování obrázku pro OCR + +Nejprve potřebujeme instanci `OcrEngine` a musíme jí říct, jaký jazyk očekáváme. Ve většině případů je výchozí angličtina, ale můžete ji změnit na francouzštinu, němčinu atd. změnou enumu `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Proč je to důležité:** Engine je srdcem operace; bez něj nemůžete použít žádné z obrazových filtrů, které skutečně **předzpracovávají obrázek pro OCR**. Představte si ho jako kuchyni, kde se míchají všechny ingredience. + +## Krok 2: Vytvoření vlastní pipeline pro zpracování obrázků – Zlepšení přesnosti OCR + +Nyní přichází ta zajímavá část. Aspose vám umožňuje řetězit několik filtrů dohromady. Níže povolíme čtyři z nejúčinnějších: + +1. **Deskew** – narovná nakloněné dokumenty (výchozí max 5°). +2. **Denoise** – vyhladí zrnitá pozadí. +3. **Binarize** – převádí obrázek na černobílý pomocí prahu. +4. **ContrastBoost** – zvýrazní slabé znaky. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Tip:** Pokud jsou vaše zdrojové obrázky již ostré, můžete snížit `Strength` nebo filtr úplně vypnout. Přílišné zpracování může někdy vymazat slabé znaky, takže experimentujte se skutečnými vzorky. + +## Krok 3: Načtení JPEG (nebo libovolného obrázku) a spuštění OCR – Spuštění OCR na JPEG + +Aspose pracuje s libovolným formátem obrázku, který .NET dokáže číst – JPEG, PNG, BMP, jakýkoli. Zde je návod, jak načíst JPEG soubor do enginu a spustit proces rozpoznávání. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Proč JPEG?** JPEG komprese často zavádí artefakty, které OCR zmátají. Naše pipeline pro předzpracování, zejména kroky denoise a binarize, tyto problémy zmírňují, takže můžete **spustit OCR na JPEG** s jistotou. + +## Krok 4: Výstup rozpoznaného textu – Extrahování textu pomocí Aspose + +Nakonec jednoduše zapíšeme text do konzole, souboru nebo jakékoli následné služby. Pro demonstrační účely stačí konzole. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Když spustíte program, měli byste vidět něco jako: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Pokud výstup vypadá poškozeně, vraťte se k **kroku 2** a upravte nastavení filtrů. Malé úpravy často přinášejí velké zlepšení v **zlepšení přesnosti OCR**. + +## Běžné okrajové případy a jak je řešit + +| Situace | Navrhovaná úprava | +|-----------|----------------------| +| **Velmi tmavé obrázky** | Zvyšte `ContrastBoost.Level` na 1,5 nebo vyšší. | +| **Zkosení > 5°** | Zvyšte `DeskewOptions.MaxAngle` (např. 10.0) nebo předem otočte obrázek ručně. | +| **Barevný text na barevném pozadí** | Použijte `BinarizeOptions` s vlastním prahem nebo přepněte na `AdaptiveBinarizeOptions`. | +| **Velké soubory ( > 5 MB )** | Nejprve načtěte obrázek do `MemoryStream`, aby se předešlo problémům se zamčením souboru. | + +Tyto úpravy udržují vaši pipeline flexibilní a připravenou na budoucnost, zejména když potřebujete **extrahovat text pomocí Aspose** z různých zdrojů. + +## Kompletní funkční příklad – Všechny kroky na jednom místě + +Níže je kompletní program připravený ke kopírování a vložení. Kompiluje se s .NET 6+ a vyžaduje pouze balíček NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Uložte to jako `Program.cs`, přidejte balíček Aspose.OCR (`dotnet add package Aspose.OCR`) a spusťte `dotnet run`. Uvidíte vyčištěný text vytištěný v konzoli. + +## Shrnutí – Proč tento přístup funguje + +- **Preprocess image for OCR**: Pipeline odstraňuje nejčastější zdroje chyb (zkosení, šum, nízký kontrast). +- **Improve OCR accuracy**: Každý filtr je nastaven tak, aby zvýšil poměr signálu k šumu, který engine vidí. +- **Run OCR on JPEG**: I komprimované obrázky jsou čitelné po narovnání a binarizaci. +- **Extract text using Aspose**: Metoda `Recognize` vrací prostý řetězec, připravený pro jakoukoli následnou logiku. + +Společně tyto kroky poskytují spolehlivé OCR řešení pro produkci během několika řádků. + +## Další kroky a související témata + +- **Dávkové zpracování** – Procházet složku s obrázky a zapisovat každý výsledek do souboru `.txt`. +- **Jazykové balíčky** – Vyměnit `OcrLanguage.English` za `OcrLanguage.Spanish` nebo přidat vlastní slovníky. +- **Extrahování PDF** – Kombinovat Aspose.OCR s Aspose.PDF pro získání textu přímo ze skenovaných PDF. +- **Ladění výkonu** – Spustit engine paralelně pomocí `Parallel.ForEach` pro velké objemy. + +Neváhejte experimentovat s hodnotami filtrů, zkoušet různé formáty obrázků nebo řetězit další Aspose filtry jako `SharpnessOptions`. Možnosti jsou neomezené, jakmile ovládnete základy. + +--- + +*Šťastné kódování! Pokud narazíte na problémy, zanechte komentář níže a společně je vyřešíme.* + +## Související tutoriály + +- [Předzpracování OCR obrázku s filtry Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Extrahování textu z obrázku – optimalizace OCR s Aspose.OCR pro .NET](/ocr/english/net/ocr-optimization/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..605d37605 100644 --- a/ocr/czech/net/text-recognition/_index.md +++ b/ocr/czech/net/text-recognition/_index.md @@ -19,11 +19,11 @@ Jste připraveni posunout své .NET aplikace na další úroveň? Ponořte se do ## Získejte možnosti pro rozpoznávání znaků v rozpoznávání obrazu OCR -V tomto tutoriálu vás provedeme využitím výkonu Aspose.OCR pro .NET ke zlepšení vašich schopností rozpoznávání obrázků. Naučte se krok za krokem, jak načíst volby pro rozpoznané znaky, a zajistit tak přesnost a efektivitu ve vašich aplikacích. Vylepšete svůj zážitek z OCR pomocí špičkových funkcí Aspose.OCR. +V tomto tutoriálu vás provedeme využitím výkonu Aspose.OCR pro .NET ke zlepšení vašich schopností rozpoznávání obrázků. Naučte se krok za krokem, jak načíst volby pro rozpoznané znaky, a zajistit tak přesnost a efektivitu ve svých aplikacích. Vylepšete svůj zážitek z OCR pomocí špičkových funkcí Aspose.OCR. ## Získejte výsledek rozpoznávání v rozpoznávání obrazu OCR -Prozkoumejte možnosti Aspose.OCR pro .NET a změňte způsob, jakým zacházíte s rozpoznáváním textu v obrázcích. Odhalte složitosti získávání výsledků rozpoznávání pomocí našeho komplexního průvodce. Ať už jste zkušený vývojář nebo teprve začínáte, tento výukový program vám umožní bezproblémovou integraci OCR do vašich projektů. +Prozkoumejte možnosti Aspose.OCR pro .NET a změňte způsob, jakým zacházíte s rozpoznáváním textu v obrázcích. Odhalte složitosti získávání výsledků rozpoznávání pomocí našeho komplexního průvodce. Ať už jste zkušený vývojář nebo teprve začínáte, tento výukový program vám umožní bezproblémovou integraci OCR do svých projektů. ## Získejte výsledek jako JSON v rozpoznávání obrazu OCR @@ -55,9 +55,24 @@ 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. +### [Rozpoznání textu z obrázku pomocí Aspose OCR – Kompletní průvodce v C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Kompletní průvodce v C# pro rozpoznání textu z obrázku pomocí Aspose OCR. Naučte se krok za krokem implementovat OCR ve svých aplikacích. +### [Jak použít OCR v C# – Rozpoznání čínského textu z JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Naučte se, jak pomocí Aspose.OCR v C# rozpoznat čínské znaky z JPG obrázku a integrovat výsledek do vaší aplikace. +### [OCR ruského textu v C# – Kompletní průvodce s použitím Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Kompletní průvodce v C# pro rozpoznání ruského textu pomocí Aspose OCR. Naučte se krok po kroku implementovat OCR ve svých aplikacích. +### [Extrahování textu z obrázku v C# – Kompletní průvodce Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Kompletní návod v C# pro extrahování textu z obrázku pomocí Aspose OCR. Naučte se krok po kroku implementovat OCR ve svých projektech. +### [Extrahování textu z obrázku v ASP.NET Core Minimal API – kompletní průvodce](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Kompletní návod, jak pomocí ASP.NET Core Minimal API extrahovat text z obrázku pomocí Aspose.OCR. +### [c# OCR tutoriál: Extrahování textu z PNG účtenek pomocí Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Naučte se pomocí Aspose.OCR v C# extrahovat text z PNG účtenek a integrovat jej do vašich aplikací. +### [Převod TIFF na text v C# – Kompletní průvodce dávkovým OCR](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Naučte se, jak pomocí Aspose.OCR v C# hromadně převádět TIFF soubory na text s podrobným návodem. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/czech/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..9413e6c1c --- /dev/null +++ b/ocr/czech/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR tutoriál, který ukazuje, jak načíst soubor obrázku v C# a rozpoznat + text v PNG z účtenky pomocí Aspose OCR – krok za krokem průvodce. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: cs +og_description: c# OCR tutoriál, který vás provede načtením souboru obrázku v c# a + rozpoznáním textu v png z účtenky pomocí Aspose OCR. +og_title: c# OCR tutoriál – Extrahování textu z PNG účtenek +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR tutoriál: Extrahujte text z PNG účtenek pomocí Aspose' +url: /cs/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Extrahování textu z PNG účtenek pomocí Aspose + +Už jste někdy potřebovali **c# OCR tutorial**, který opravdu funguje, aniž byste museli nekonečně googlovat? Jste na správném místě. V tomto průvodci **načteme soubor obrázku c#**, **rozpoznáme text v png**, a **přečteme výstup OCR z účtenky**, a to vše s ukázkou, jak **provádět OCR image** zpracování pomocí Aspose OCR. + +Začneme instalací potřebného NuGet balíčku, projdeme každý řádek kódu a skončíme úhledným výpisem JSON, který můžete přímo přesměrovat do dalšího datového potrubí. Žádné zbytečnosti, jen praktické, připravené řešení. + +## Co se naučíte + +- Jak nastavit Aspose OCR v projektu .NET 6 (nebo novějším). +- Přesné kroky k **načtení souboru obrázku c#** a předání ho enginu. +- Jak **rozpoznat text v png** z obrázku účtenky a zachytit výsledek. +- Způsoby, jak **přečíst OCR z účtenky** jako hezky formátovaný JSON. +- Tipy pro **provádění OCR image** operací na různých typech souborů a řešení běžných úskalí. + +**Předpoklady** +- Visual Studio 2022 (nebo jakékoli IDE dle vašeho výběru). +- .NET 6 SDK nebo novější. +- PNG obrázek účtenky po ruce (předpokládejme, že se jmenuje `receipt.png`). + +Pokud máte vše připravené, pojďme na to. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR Tutorial – Nastavení Aspose OCR Engine + +Nejprve potřebujeme knihovnu Aspose OCR. Otevřete terminál ve složce řešení a spusťte: + +```bash +dotnet add package Aspose.OCR +``` + +Tento jediný příkaz stáhne vše potřebné, včetně nativních binárek pro dekódování obrázků. Po instalaci vytvořte nový konzolový projekt nebo přidejte kód do existujícího. + +### Proč Aspose? + +Aspose OCR podporuje více než 30 jazyků, funguje offline a vrací bohatý objekt `OcrResult` — ideální pro **perform OCR image** úkoly, kde potřebujete víc než jen prostý text. + +## Načtení souboru obrázku c# a příprava účtenky + +Když je knihovna připravena, **načteme soubor obrázku c#**. Třída `System.Drawing.Image` udělá těžkou práci, ale můžete také použít `SkiaSharp`, pokud dáváte přednost multiplatformní alternativě. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Tip:** Zabalte `Image` do `using` bloku (jak je ukázáno), aby se nativní prostředky uvolnily okamžitě — což je obzvláště důležité, když **perform OCR image** na mnoho souborů ve smyčce. + +## Rozpoznání textu PNG pomocí Aspose + +S obrázkem v paměti může engine nyní **rozpoznat text v png**. Aspose vrací `OcrResult`, který obsahuje jak surový řetězec, tak podrobné údaje o každém rozpoznaném slově. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Proč volat `RecognizeWithResult` místo jednoduššího `Recognize`? První vám poskytne skóre důvěry, ohraničující rámečky a zalomení řádků — užitečné, pokud později potřebujete **read receipt OCR** pro extrakci položek. + +## Čtení výsledku OCR z účtenky jako JSON + +Většina downstream systémů miluje JSON, takže si `OcrResult` serializujeme. Serializér `System.Text.Json` se s komplexními objekty vypořádá elegantně a povolíme odsazení pro čitelnost. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Výsledný JSON vypadá zhruba takto (zkrácený pro přehlednost): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Nyní můžete `jsonResult` poslat do databáze, fronty zpráv nebo jej jednoduše zalogovat pro ladění. + +## Provádění OCR Image Processing a zobrazení výstupu + +Nakonec vypíšeme JSON do konzole. Ve skutečné aplikaci byste ho pravděpodobně zapisovali do souboru nebo odesílali přes HTTP, ale konzole usnadňuje ověření, že vše funguje. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Spusťte program (`dotnet run`) a měli byste vidět hezky formátovaný JSON. Pokud je obrázek účtenky čistý, text bude přesný; pokud ne, zvažte zvýšení rozlišení obrázku nebo aplikaci předzpracování (např. převod na odstíny šedi, zvýšení kontrastu) před předáním enginu. + +### Řešení běžných okrajových případů + +| Situace | Co dělat | +|-----------|------------| +| **Obrázek je rozmazaný** | Předzpracujte pomocí `System.Drawing` – zaostřete nebo zvýšte DPI. | +| **Účtenka obsahuje více jazyků** | Nastavte `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Zpracování velkých batchů** | Znovu použijte jedinou instanci `OcrEngine`; měňte jen `Image` v každé iteraci. | +| **Tlak na paměť** | Promptně uvolňujte objekty `Image` a zvažte `await Task.Run` pro asynchronní pipeline. | + +Tyto úpravy udrží váš **perform OCR image** workflow robustní i při nedokonalém vstupu. + +## Závěr + +Gratulujeme — právě jste dokončili **c# OCR tutorial**, který načte obrázek, **rozpozná text v png** a **přečte výstup OCR z účtenky** jako čistý JSON. Základní kroky (nastavení enginu, načtení obrázku, spuštění OCR, serializace a výpis) tvoří pevný základ, který můžete rozšířit na faktury, pasy nebo jakýkoli jiný naskenovaný dokument. + +### Co dál? + +- Vyzkoušejte **load image file c#** pomocí `SkiaSharp` pro pravou multiplatformní podporu. +- Prozkoumejte podrobně `OcrResult.Words` a extrahujte položky, ceny a data — ideální pro aplikace sledování výdajů. +- Kombinujte tento tutoriál s Azure Functions nebo AWS Lambda a vytvořte serverless API pro zpracování účtenek. + +Klidně upravujte kód, přidávejte další obrázky nebo přepněte na jiný jazykový balíček. Svět OCR je plný překvapení a nyní máte nástroje, jak je objevovat. + +Šťastné programování a ať jsou vaše účtenky vždy čitelné! + + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Use OCR - Recognize Image without Text Area Detection](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/czech/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..80f11bd71 --- /dev/null +++ b/ocr/czech/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Převod TIFF na text pomocí Aspose.OCR v C#. Naučte se hromadný převod + obrázků na text a efektivně extrahujte text z TIFF souborů. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: cs +og_description: Převod TIFF na text pomocí Aspose.OCR. Tento průvodce ukazuje hromadný + převod obrázků na text a jak extrahovat text z TIFF souborů pomocí několika řádků + kódu v C#. +og_title: Převod TIFF na text v C# – Kompletní průvodce dávkovým OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Převod TIFF na text v C# – Kompletní průvodce hromadným OCR +url: /cs/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Převod TIFF na text v C# – Kompletní průvodce hromadným OCR + +Už jste někdy potřebovali **převést TIFF na text**, ale nebyli jste si jisti, kde začít? Nejste v tom sami — mnoho vývojářů narazí na hromadné OCR při práci s naskenovanými dokumenty. V tomto tutoriálu vás provedeme praktickým řešením, které **extrahuje text z TIFF** souborů pomocí Aspose.OCR, a uděláme to paralelně, takže velké složky skončí během několika sekund. + +Také se dotkneme nejlepších postupů pro **hromadný převod obrázku na text**, takže na konci budete mít znovupoužitelný úryvek, který převádí celý adresář naskenovaných obrázků na úhledné soubory *.txt* — ideální pro indexaci, vyhledávání nebo předávání do následných analytických procesů. + +## Co budete potřebovat + +- **.NET 6.0** nebo novější (kód se také kompiluje na .NET Framework) +- NuGet balíček **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Složka obsahující jeden nebo více souborů *.tif* (klasický formát skenování TIFF) +- Vaše oblíbené IDE (Visual Studio, VS Code, Rider — cokoli preferujete) + +A to je vše. Žádné externí služby, žádné API klíče, jen čistý C# a Aspose. + +![Snímek obrazovky TIFF souboru, který se zpracovává, a výsledného textového souboru](/images/ocr-result.png "Výsledek OCR zobrazující převod TIFF na text") + +*(Alt text: Snímek obrazovky ukazující převod TIFF na text na obrazovce)* + +## Krok 1: Nastavení OCR enginu — Převod TIFF na text + +Nejprve potřebujeme instanci `OcrEngine`, která ví, že má číst anglické znaky. Engine je srdcem převodu; jeho správné nastavení zajišťuje spolehlivé výsledky. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Proč je to důležité:* +Aspose.OCR podporuje desítky jazyků. Pokud pracujete s vícejazyčnými skeny, stačí změnit `OcrLanguage.English` na odpovídající hodnotu výčtu. Pokud jazyk nedefinujete, engine přejde do režimu automatické detekce, což může být pomalejší a méně přesné. + +## Krok 2: Shromáždění všech TIFF souborů — Efektivní extrakce textu z TIFF + +Dále načteme každý soubor *.tif* ze zadané složky. Použití `Directory.GetFiles` nám poskytne čisté pole, které můžeme předat hromadnému procesoru. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Tip:* Příznak `SearchOption.AllDirectories` lze použít, pokud jsou vaše skeny vnořeny ve podsložkách. Jen si uvědomte, že hlubší rekurze může během hromadného kroku zvýšit spotřebu paměti. + +## Krok 3: Paralelní OCR — Hromadný převod obrázku na text + +Nyní zábavná část. Aspose.OCR obsahuje statického pomocníka `BatchOcr.RecognizeAll`, který přijímá pole cest k souborům, engine a parametr `parallelism`. Spustíme čtyři vlákna, což na moderním čtyřjádrovém notebooku poskytuje téměř lineární zrychlení. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Proč paralelismus?* +Skenování hromady vysokého rozlišení TIFF může být náročné na CPU. Rozdělením práce mezi více vláken udržíme všechna jádra vytížená, což dramaticky zkrátí celkový čas běhu. Pokud to spustíte na serveru s více jádry, zvyšte hodnotu `parallelism` odpovídajícím způsobem. + +## Krok 4: Zápis výstupu — Převod naskenovaných obrázků na TXT soubory + +Nakonec projdeme slovník a zapíšeme každý kus textu do souboru *.txt*, který má stejný základní název jako původní soubor. To je okamžik, kdy **convert scanned images txt** se stává realitou. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Co kód dělá, v prostém jazyce + +1. **Vytvořte** OCR engine nastavený na angličtinu. +2. **Shromážděte** každý TIFF soubor z cílové složky. +3. **Spusťte** `BatchOcr.RecognizeAll` se čtyřmi vlákny, které každému obrázku převádějí na řetězec. +4. **Projděte** výsledky, zaměňte příponu `.tif` za `.txt` a zapište řetězec na disk. + +To je celý workflow **convert TIFF to text** v méně než 50 řádcích kódu. + +## Řešení okrajových případů — Když věci neprobíhají hladce + +- **Chybějící nebo poškozené TIFF** — `BatchOcr` vyhodí `OcrException`. Zabalte volání do `try / catch`, pokud potřebujete elegantní degradaci. +- **Dokumenty v jiném jazyce než angličtině** — změňte `OcrLanguage.English` na `OcrLanguage.Spanish`, `OcrLanguage.French` atd., nebo použijte `OcrLanguage.AutoDetect`. +- **Velmi velké obrázky** — zvažte snížení DPI před OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) pro úsporu paměti, i když můžete ztratit část přesnosti. +- **Kódování výstupu** — pokud potřebujete konkrétní kódovou stránku (např. Windows‑1252), předávejte ji do `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Profesionální tipy pro robustní hromadné převody + +- **Logujte selhání**: vytvořte `List failedFiles` a přidejte do něj každý soubor, který vyhodí výjimku; po smyčce zapište seznam do logu. +- **Znovu použijte engine**: stejná instance `OcrEngine` může být použita napříč mnoha soubory; nevytvářejte ji uvnitř smyčky. +- **Validujte výsledek**: rychlá kontrola `if (string.IsNullOrWhiteSpace(extractedText))` může označit skeny, které jsou prázdné nebo nečitelné. +- **Kombinujte s PDF**: pokud je vaším zdrojem vícestránkový PDF, nejprve převěďte každou stránku na TIFF (Aspose.PDF to umí) a pak spusťte tento batch. + +## Další kroky — Přesahování jednoduchého převodu + +Nyní, když můžete **extrahovat text z TIFF** souborů hromadně, můžete chtít: + +- Zavést soubory *.txt* do vyhledávacího indexu (Elasticsearch, Azure Cognitive Search). +- Spustit detekci jazyka na každém výsledku pro směrování dokumentů do lokálně specifických pipeline. +- Vytvořit prohledávatelné PDF překrytím OCR textu zpět na původní obrázky (znovu Aspose.PDF). + +Všechny tyto scénáře staví na stejném základním principu: **batch image to text conversion** je stavební kámen pro větší systémy zpracování dokumentů. + +--- + +### Závěr + +Právě jste se naučili, jak **převést TIFF na text** pomocí Aspose.OCR, zpracovat celou složku paralelně a uložit každý výsledek jako čistý soubor *.txt*. Řešení je lehké, plně konfigurovatelné a připravené do produkce — ať už digitalizujete staré faktury, archivujete naskenované smlouvy nebo napájíte vyhledávač textu. + +Vyzkoušejte to, upravte paralelismus a začněte zavádět nově vytvořené textové soubory do libovolného pracovního postupu, který potřebujete. Šťastné OCRování! + +--- + +## Související tutoriály + +- [Extrahovat text z obrázků pomocí OCR operace ve složkách](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/czech/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..20fe6e5c4 --- /dev/null +++ b/ocr/czech/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Naučte se, jak extrahovat text z obrázku pomocí minimalistického ASP.NET + Core API. Nahrajte obrázek pomocí POST, načtěte multipart data formuláře a proveďte + OCR na obrázku. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: cs +og_description: Extrahujte text z obrázku pomocí minimalistického ASP.NET Core API. + Tento průvodce ukazuje, jak nahrát obrázek pomocí POST, číst multipart data formuláře + a provést OCR na obrázku. +og_title: Extrahování textu z obrázku v ASP.NET Core – krok po kroku +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Extrahování textu z obrázku v ASP.NET Core Minimal API – kompletní průvodce +url: /cs/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahování textu z obrázku v ASP.NET Core Minimal API – Kompletní průvodce + +Už jste se někdy zamýšleli, jak **extrahovat text z obrázku** bez zbytečného boje s těžkými frameworky? Nejste sami. Mnoho vývojářů potřebuje rychlý způsob, jak uživatelům umožnit nahrát obrázek a získat zpět surové znaky, ať už jde o skenování účtenek, digitalizaci ručně psaných poznámek nebo napájení vyhledávacího indexu. + +V tomto tutoriálu vytvoříme malou ASP.NET Core Minimal API, která **nahrává obrázek pomocí POST**, zpracuje *multipart/form‑data* payload a následně **provádí OCR na obrázku** pomocí singletonu `OcrEngine`. Na konci budete mít plně funkční aplikaci, kterou můžete vložit do libovolného .NET 8 projektu a okamžitě začít extrahovat text z obrázku. + +## Co vytvoříte + +- Minimální webovou aplikaci naslouchající na `/ocr`. +- Endpoint, který přijímá soubor obrázku odeslaný pomocí `multipart/form-data` POST požadavku. +- Logiku, která načte nahraný soubor, předá jej OCR enginu a vrátí výsledek jako prostý text. +- Volitelný úryvek pro akceleraci pomocí GPU (zakomentovaný) pro ty, kteří mají kompatibilní kartu. + +**Předpoklady** +- .NET 8 SDK (nebo novější). +- Základní znalost C# a práce s příkazovým řádkem. +- OCR knihovna, která poskytuje třídu `OcrEngine` (ukázka předpokládá hypotetický NuGet balíček). + +Pokud máte vše připravené, pojďme na to. + +## Krok 1: Nastavení projektu a přidání OCR balíčku + +Nejprve vytvořte nový webový projekt a přidejte OCR knihovnu. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Tip:** Udržujte své závislosti aktuální. Novější verze často přinášejí výkonnostní zlepšení, zejména u inference akcelerované GPU. + +## Krok 2: Registrace singletonu OCR Engine (hlavní služba) + +Potřebujeme jedinou instanci `OcrEngine` pro celou aplikaci – není nutné spouštět nový engine pro každý požadavek. Zaregistrujte ji v kontejneru služeb builderu. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Proč singleton?** +Vytvoření OCR enginu může být nákladné – například načítání vah neuronové sítě do paměti. Opakovaným používáním stejné instance šetříme jak CPU cykly, tak RAM, což se projeví rychlejšími odezvami pro každý volání `/ocr`. + +## Krok 3: Sestavení aplikace + +Nyní materializujeme objekt `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Ten řádek vypadá téměř magicky, ale pod povrchem propojuje routování, middleware a DI kontejner, který jsme právě nakonfigurovali. + +## Krok 4: Definice POST endpointu – „Nahrát obrázek pomocí POST“ + +Tady je jádro tutoriálu: endpoint, který **nahrává obrázek pomocí POST**, načte multipart payload a předá data OCR enginu. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Rozbor logiky + +| Krok | Co se děje | Proč je to důležité | +|------|------------|---------------------| +| **ReadFormAsync** | Parsuje příchozí *multipart/form-data* požadavek. | Bez toho nemůžete přistupovat k nahraným souborům. | +| **form.Files["image"]** | Načte soubor, jehož název pole ve formuláři je `image`. | Zajišťuje předvídatelný kontrakt pro volající. | +| **Kontrola Content‑type** | Ověřuje, že soubor je obrázek (např. `image/png`). | Zabraňuje tomu, aby OCR engine selhal na ne‑obrázkových datech. | +| **Image.FromStream** | Převádí surový stream na `System.Drawing.Image`. | OCR knihovna očekává objekt `Image`, ne jen pole bajtů. | +| **ocr.Recognize(img)** | Volá OCR engine k **rozpoznání textu z obrázku**. | Toto je jádro kroku **perform OCR on image**. | +| **Results.Text** | Vrací výsledek jako prostý text. | Jednoduchý, snadno konzumovatelný formát pro downstream služby. | + +## Krok 5: Spuštění API + +Nakonec spusťte webový server. + +```csharp +app.Run(); +``` + +Po spuštění `dotnet run` bude API naslouchat na `http://localhost:5000` (nebo na vámi zvoleném portu). Můžete to otestovat pomocí `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Očekávaný výstup:** Konzole vypíše rozpoznané znaky, např.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Pokud je obrázek rozmazaný nebo není podporovaný jazyk, OCR engine vrátí prázdný řetězec nebo chybovou zprávu – v produkčním kódu byste tyto případy měli ošetřit. + +## Okrajové případy a osvědčené postupy + +### 1. Velké soubory + +Výchozí limit těla požadavku je 30 MB. Pro větší skeny možná budete muset upravit: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynchronní OCR + +Některé OCR knihovny nabízejí asynchronní metody (`RecognizeAsync`). Pokud je máte, nahraďte `ocr.Recognize(img)` za `await ocr.RecognizeAsync(img)` a označte lambda výraz jako `async`. + +### 3. Bezpečnostní úvahy + +- **Ověřte velikost souboru** před načtením do paměti. +- **Sanitizujte název souboru**, pokud jej někdy zapisujete na disk. +- **Omezte rychlost** (rate‑limit) endpointu, aby se předešlo útokům typu denial‑of‑service. + +### 4. Akcelerace pomocí GPU + +Pokud odkomentujete řádek `engine.GpuDevice = new GpuDevice(0);` a váš hardware podporuje CUDA nebo DirectML, zaznamenáte výrazné zrychlení, zejména u vysoce rozlišených obrázků. + +## Kompletní funkční příklad + +Níže je kompletní `Program.cs`, který můžete zkopírovat a vložit do nového Minimal API projektu. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Uložte, spusťte `dotnet run` a jste připraveni **extrahovat text z obrázku** na vyžádání. + +## Závěr + +Prošli jsme **kompletním, end‑to‑end řešením** pro extrahování textu z obrázku pomocí ASP.NET Core Minimal API. Od vytvoření projektu až po **registraci singletonu OCR engine**, vytvoření endpointu, který **nahrává obrázek pomocí POST**, **čte multipart form data** a nakonec **provádí OCR na obrázku** a vrací čistý prostý text. + +Dále můžete: + +- Přidat JSON obálky pro bohatší odpovědi. +- Připojit databázi pro ukládání extrahovaného textu. +- Rozšířit podporu o více jazyků (`OcrLanguage.Spanish` atd.). + +Tento vzor se dobře škáluje – stačí vložit stejný endpoint do většího mikroservisu nebo jej vystavit za API gateway. + +Máte otázky ohledně zpracování PDF, hromadného zpracování nebo ladění GPU? Zanechte komentář a šťastné kódování! + +## Související tutoriály + +- [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/czech/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/czech/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..4e4c3a00c --- /dev/null +++ b/ocr/czech/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: Extrahujte text z obrázku pomocí C# a Aspose OCR. Naučte se, jak převést + JPG na text, načíst obrázek pro OCR a získat spolehlivé výsledky rychle. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: cs +og_description: Extrahujte text z obrázku pomocí C#. Tento průvodce ukazuje, jak převést + JPG na text, načíst obrázek pro OCR a pracovat s vícejazyčným obsahem. +og_title: Extrahování textu z obrázku v C# – Aspose OCR tutoriál +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Extrahování textu z obrázku v C# – Kompletní průvodce Aspose OCR +url: /cs/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahování textu z obrázku v C# – Kompletní průvodce Aspose OCR + +Už jste se někdy zamýšleli, jak **extrahovat text z obrázku** pomocí čistého C# kódu? Nejste v tom sami. Ať už digitalizujete účtenky, skenujete cedule nebo jste jen zvědaví na OCR, schopnost vytáhnout znaky z fotografie je užitečná dovednost. V tomto tutoriálu projdeme kompletním, spustitelným příkladem, který ukazuje přesně, jak **extrahovat text z obrázku** pomocí Aspose.OCR, a také se podíváme na **převod jpg na text**, **načtení obrázku pro OCR** a odpovíme na klasickou otázku „**jak OCR obrázek**“ jednou provždy. + +Na konci tohoto průvodce budete mít samostatnou konzolovou aplikaci, která načte JPEG soubor, rozpozná ukrajinštinu (nebo jakýkoli jiný podporovaný jazyk) a výsledek vypíše do konzole. Žádné vágní odkazy, žádné chybějící části – jen kompletní řešení, které můžete zkopírovat, vložit a spustit. + +--- + +## Co se naučíte + +* Jak nainstalovat NuGet balíček Aspose.OCR. +* Přesný kód potřebný k **načtení obrázku pro OCR** v C#. +* Jak nastavit jazyk a skutečně **extrahovat text z obrázku**. +* Tipy pro **převod jpg na text** efektivně. +* Běžné úskalí a jak se jim vyhnout. + +Pokud už máte nastavené .NET vývojové prostředí, můžete rovnou skočit do kódu. Jinak vás sekce požadavků níže připraví na start. + +--- + +## Požadavky + +| Požadavek | Proč je důležitý | +|-----------|-------------------| +| .NET 6.0 SDK (nebo novější) | Poskytuje runtime pro konzolovou aplikaci. | +| Visual Studio 2022 nebo VS Code | Usnadňuje úpravy a ladění. | +| Internetové připojení (při prvním spuštění) | NuGet potřebuje stáhnout Aspose.OCR. | +| JPEG obrázek, který chcete zpracovat (např. `ukrainian_sign.jpg`) | Vstupní soubor pro OCR engine. | + +> **Tip:** Pokud používáte Linux nebo macOS, stejný kód funguje s .NET CLI (`dotnet new console`), takže můžete klidně vynechat těžké IDE. + +--- + +## Krok 1 – Instalace Aspose.OCR přes NuGet + +Otevřete terminál (nebo Package Manager Console) a spusťte: + +```bash +dotnet add package Aspose.OCR +``` + +Tento jediný řádek stáhne nejnovější Aspose.OCR binárky a všechny transitivní závislosti. Žádné ruční manipulace s DLL soubory nejsou potřeba. + +--- + +## Krok 2 – Vytvoření OCR enginu (srdce extrakce) + +Nyní, když je knihovna na místě, můžeme vytvořit instanci `OcrEngine`. Tento objekt je zodpovědný za **extrahování textu z obrázku**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Proč je to důležité:** Engine zapouzdřuje OCR algoritmy, jazykové modely a konfigurační možnosti. Vytvořit jej jednou a znovu jej používat pro více obrázků je jak paměťově úsporné, tak rychlé. + +--- + +## Krok 3 – Načtení obrázku pro OCR (a nastavení jazyka) + +Dalším krokem je říct enginu, který obrázek má číst. Zde vstupuje fráze **načíst obrázek pro OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Hraniční případ:** Pokud soubor neexistuje, `Image.FromFile` vyhodí `FileNotFoundException`. Pro produkční kód obalte volání do try‑catch bloku. + +--- + +## Krok 4 – Provedení OCR a extrakce textu + +S načteným obrázkem může engine nyní **extrahovat text z obrázku**. Metoda `Recognize` udělá těžkou práci. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Pokud vše proběhne v pořádku, `recognizedText` bude obsahovat prostý textový výstup všeho, co OCR engine dokázal přečíst. + +--- + +## Krok 5 – Převod JPG na text (sjednocení všeho) + +Kód, který jsme doposud vytvořili, už **převádí jpg na text**, ale zabalíme ho do přehledné metody, kterou můžete volat opakovaně. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Nyní můžete jednoduše použít: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Očekávaný výstup** (zkrácený pro stručnost): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Pokud obrázek obsahuje anglický text, změňte `OcrLanguage.English` a uvidíte odpovídající výstup. + +--- + +## Krok 6 – Řešení běžných otázek „Jak OCR obrázek“ + +### 6.1 Mohu OCRovat PNG nebo BMP? + +Ano. Metoda `Image.FromFile` podporuje všechny formáty, které rozpozná System.Drawing, takže stačí nasměrovat cestu na soubor s příponou `.png` nebo `.bmp` a zbytek kódu zůstane stejný. + +### 6.2 Co když je obrázek nízkého rozlišení? + +Přesnost OCR dramaticky klesá pod 300 dpi. Rychlý trik je upscale obrázku pomocí `Graphics` před předáním enginu: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Potřebuji licenci pro Aspose.OCR? + +Aspose nabízí bezplatnou zkušební verzi s vodoznakem. Pro produkční použití zakupte licenci a přidejte: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Kompletní funkční příklad + +Níže najdete kompletní, připravenou ke spuštění konzolovou aplikaci, která demonstruje **jak OCR obrázek**, **načíst obrázek pro OCR** a **převést jpg na text** v jednom úhledném balíčku. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Jak to spustit** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Měli byste vidět extrahovaný text vytištěný v konzoli, což potvrzuje, že jste úspěšně **extrahovali text z obrázku** pomocí C#. + +--- + +## Běžné úskalí a tipy profesionálů + +| Problém | Proč se vyskytuje | Řešení | +|---------|-------------------|--------| +| Prázdný výstup | Obrázek příliš tmavý nebo s nízkým kontrastem. | Předzpracujte pomocí `Bitmap` a zvyšte jas. | +| Špatný jazyk | Vlastnost `Language` zůstala na výchozí angličtině. | Explicitně nastavte `ocrEngine.Language = OcrLanguage.Ukrainian;` (nebo vámi požadovaný jazyk). | +| Chyba nedostatku paměti | Velmi velké obrázky načtené bez uvolnění. | Zabalte `Image.FromFile` do `using` bloku (jak je ukázáno). | +| Vodoznak licence | Běžíte na trial verzi bez licence. | Aplikujte zakoupenou licenci co nejdříve v `Main`. | + +--- + +## Závěr + +Probrali jsme vše, co potřebujete k **extrahování textu z obrázku** v C# – od instalace Aspose.OCR, **načtení obrázku pro OCR**, po **převod jpg na text** a práci s vícejazyčnými scénáři. Kompletní ukázkový program spojuje všechny části dohromady a poskytuje spolehlivý základ pro jakýkoli OCR projekt. + +Dále můžete zkusit: + +* **Jak OCR obrázek** pomocí streamů místo souborů (použijte `MemoryStream`). +* Přidat **c# image to text** post‑processing, např. kontrolu pravopisu. +* Integrovat OCR krok do většího pipeline (např. ukládání výsledků do databáze). + +Nebojte se experimentovat s různými jazyky, formáty obrázků a předzpracovatelskými triky. OCR je stejně umění jako věda a čím více si s ním pohráváte, tím lepší výsledky získáte. + +Šťastné kódování a ať jsou vaše obrázky vždy čitelné! + +## Související tutoriály + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/czech/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..2bbccac4d --- /dev/null +++ b/ocr/czech/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-05-25 +description: Jak použít OCR v C# k extrakci textu z obrazových souborů. Naučte se + rozpoznávat čínské znaky z JPG pomocí Aspose.OCR během několika jednoduchých kroků. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: cs +og_description: Jak použít OCR v C# k extrakci textu z obrazových souborů. Tento průvodce + vám ukáže, jak rozpoznat čínské znaky z JPG pomocí Aspose.OCR. +og_title: Jak použít OCR v C# – Rozpoznat čínský text z JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Jak použít OCR v C# – Rozpoznat čínský text z JPG +url: /cs/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak používat OCR v C# – Rozpoznat čínský text z JPG + +Už jste se někdy zamysleli **jak používat OCR** k vytažení slov z obrázku, který jste pořízili telefonem? Nejste v tom sami. V mnoha reálných projektech—například skenery účtenek, překladové aplikace nebo automatizovaný vstup dat—budete potřebovat **extrahovat text z obrázku** souborů rychle a spolehlivě. + +V tomto tutoriálu projdeme kompletním, spustitelným příkladem, který **rozpoznává text z JPG** souborů a dokonce řeší obtížný případ **rozpoznání čínských znaků** pomocí jazykového balíčku **OCR Chinese Simplified**. Na konci budete mít samostatnou konzolovou aplikaci, která vypíše detekovaný řetězec do konzole, bez nutnosti dalších ručních stažení. + +> **Rychlá poznámka:** Kód funguje s Aspose.OCR ≥ 23.7, který automaticky stáhne jazykové zdroje při prvním použití. Pokud používáte starší verzi, budete muset jazyk přidat ručně. + +## Požadavky + +- .NET 6.0 SDK nebo novější (příklad cílí na .NET 6, ale .NET 5 také funguje) +- Nedávná verze Visual Studio 2022 nebo VS Code s rozšířením C# +- Připojení k internetu pro první stažení jazyka +- JPG obrázek, který obsahuje zjednodušený čínský text (nazveme jej `chinese_sign.jpg`) + +To je vše—žádné těžkopádné OCR enginy, žádné manipulace s nativními DLL. Pouze pár příkazů NuGet a několik řádků kódu. + +## Krok 1: Instalace Aspose.OCR přes NuGet + +Nejprve potřebujeme OCR knihovnu. Otevřete terminál ve složce projektu a spusťte: + +```bash +dotnet add package Aspose.OCR +``` + +Nebo, pokud dáváte přednost UI ve Visual Studiu, klikněte pravým tlačítkem na **Dependencies → Manage NuGet Packages**, vyhledejte “Aspose.OCR” a klikněte na **Install**. + +> **Pro tip:** Udržujte své balíčky aktuální. Nové jazykové balíčky a vylepšení výkonu přicházejí v každém minor release. + +## Krok 2: Vytvoření nového konzolového projektu (pokud jste tak ještě neučinili) + +Pokud začínáte od nuly, vytvořte nový konzolový aplikaci: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Nyní máte soubor `Program.cs` připravený pro OCR kód. + +## Krok 3: Napsání OCR kódu – Rozpoznání zjednodušené čínštiny z JPG + +Otevřete `Program.cs` a nahraďte jeho obsah následujícím. Každý řádek je anotován, abyste viděli *proč* děláme každý krok, ne jen *co* děláme. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Co se děje pod kapotou? + +- **`OcrEngine.Language`** říká Aspose, který slovník použít. Výběrem `ChineseSimplified` instruujeme engine, aby hledal jazykový balíček pro zjednodušenou čínštinu. +- **První stažení**: Když se spustí `Recognize`, SDK se obrátí na CDN Aspose, stáhne ≈6 MB jazykový soubor, uloží jej lokálně do cache a poté pokračuje v OCR. Následující volání jsou okamžité. +- **`Image.FromFile`** funguje s libovolným rastrovým formátem, který .NET dokáže dekódovat—JPG, PNG, BMP—takže můžete **extrahovat text z obrázku** souborů mnoha typů, nejen JPG. + +## Krok 4: Spuštění aplikace a ověření výstupu + +Sestavte a spusťte: + +```bash +dotnet run +``` + +Měli byste vidět něco jako: + +``` +=== Recognized Text === +欢迎光临 +``` + +Pokud konzole vypíše nesmysly nebo prázdný řetězec, zkontrolujte: + +1. Obrázek skutečně obsahuje jasné, vysokokontrastní čínské znaky. +2. Cesta k souboru je správná (žádné nadbytečné mezery nebo chybějící přípony). +3. Váš počítač může dosáhnout na `https://download.aspose.com` pro jazykový balíček. + +## Krok 5: Řešení okrajových případů a běžných úskalí + +### 5.1 Práce s nízkokvalitními obrázky + +Přesnost OCR klesá, když je zdrojový obrázek rozmazaný, šumivý nebo má špatné osvětlení. Rychlé řešení je předzpracovat obrázek: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Spuštění v headless prostředí + +Pokud nasazujete do Linux kontejneru bez GUI, ujistěte se, že je nainstalována knihovna `libgdiplus` (vyžadovaná pro `System.Drawing`): + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Ruční cachování jazykového balíčku + +Můžete stáhnout jazykový soubor jednou a nasměrovat Aspose na něj pomocí API `License`, což eliminuje jednorázové síťové volání. To je užitečné pro offline scénáře. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Kompletní funkční příklad (vše v jednom) + +Níže je *kompletní* program, který můžete zkopírovat a vložit do `Program.cs`. Žádné skryté části, žádné externí skripty. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Očekávaný výstup + +Pokud JPG obsahuje frázi “欢迎光临”, konzole vypíše: + +``` +=== Recognized Text === +欢迎光临 +``` + +Klidně nahraďte obrázek jakýmkoli jiným zjednodušeným čínským znakem, názvem ulice nebo štítkem produktu—engine udělá, co může. + +## Závěr + +Právě jsme probrali **jak používat OCR** v C# k **extrahování textu z obrázku** souborů, konkrétně řešení výzvy **rozpoznání čínských znaků** v **JPG**. Využitím on‑the‑fly stažení jazyků od Aspose.OCR můžete udržet nasazení lehké a přitom podporovat **OCR Chinese Simplified** přímo z krabice. + +Co dál? Vyzkoušejte tyto nápady: + +- **Dávkové zpracování**: Procházet složku s obrázky a zapisovat každý výsledek do CSV. +- **Kombinace s překladovými API**: Poslat rozpoznaný řetězec do Azure Translator pro aplikace v reálném čase s více jazyky. +- **Prozkoumat další jazyky**: Vyměnit `OcrLanguage.ChineseSimplified` za `Japanese` nebo `Arabic` a sledovat, jak se stejný kód přizpůsobí. + +Máte otázky ohledně ladění výkonu, licencování nebo integrace OCR do webové služby? Zanechte komentář níže—šťastné kódování! + +--- + +![Snímek obrazovky výstupu konzole ukazující, jak použít OCR v C# k rozpoznání čínského textu z JPG obrázku](ocr-chinese-demo.png "jak použít výstup OCR v konzoli") + +## Související tutoriály + +- [Extrahovat text z obrázku v C# s výběrem jazyka pomocí Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [rozpoznat text z obrázku s Aspose OCR pro více jazyků](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Jak extrahovat text z obrázku přípravou obdélníků v OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/czech/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/czech/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..9d160813b --- /dev/null +++ b/ocr/czech/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: Naučte se, jak provést OCR ruského textu v C# a extrahovat text z obrázku + pomocí Aspose OCR. Krok za krokem kód pro rychlý převod obrázku na text v C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: cs +og_description: OCR ruského textu v C# je snadné. Naučte se extrahovat text z obrázku, + převést obrázek na text v C# a načíst obrázek pro OCR pomocí Aspose OCR. +og_title: OCR ruského textu v C# – Kompletní průvodce Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR ruského textu v C# – Kompletní průvodce s použitím Aspose OCR +url: /cs/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR ruského textu v C# – Kompletní průvodce s použitím Aspose OCR + +Už jste někdy potřebovali OCR ruského textu v C#, ale nevedeli ste, kterou knihovnu použít? Nejste sami. Získat čisté, čitelné znaky z cyrilického obrázku může připomínat dešifrování tajných zpráv — obzvláště pokud nemáte nastavený správný jazykový model. + +V tomto tutoriálu projdeme praktickým příkladem, který vám ukáže, jak **extrahovat text z obrázku**, převést *image to text C#* styl a zvládnout nuance rozpoznávání ruského jazyka pomocí Aspose OCR. Na konci budete mít připravenou konzolovou aplikaci, která načte obrázek pro OCR, vypíše rozpoznaný řetězec a poskytne vám solidní základ pro pokročilejší scénáře. + +## Co se naučíte + +- Jak nainstalovat a nakonfigurovat **Aspose OCR C#** pro podporu ruského jazyka. +- Přesné kroky k **načtení obrázku pro OCR** a volání enginu. +- Tipy, jak řešit běžné problémy, jako chybějící jazykové zdroje nebo rozmazané skeny. +- Způsoby, jak rozšířit řešení, například hromadné zpracování více souborů nebo ladění prahových hodnot spolehlivosti. + +Předchozí zkušenost s Aspose není vyžadována; stačí základní znalost C# a .NET, abyste mohli začít. + +## Předpoklady + +Než se pustíme dál, ujistěte se, že máte následující: + +1. **.NET 6.0** (nebo novější) SDK nainstalované — kód funguje jak na .NET Core, tak na .NET Framework. +2. **Visual Studio 2022** (nebo libovolné IDE, které preferujete). +3. NuGet balíček **Aspose.OCR for .NET** — zdarma zkušební klíč získáte na webu Aspose. +4. Soubor **ruského jazykového modelu** (`rus.traineddata`) — stáhněte jej ze stránky zdrojů Aspose a umístěte do složky, na kterou budete později odkazovat. +5. Ukázkový obrázek (`russian_doc.png`) obsahující čistý cyrilický text. + +Máte vše připravené? Skvěle — pojďme na to. + +## Krok 1: Vytvoření projektu a instalace Aspose OCR + +Nejprve vytvořte nový konzolový projekt: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Nyní přidejte balíček Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Tip:** Pokud používáte zkušební licenci, mějte po ruce soubor `Aspose.Total.lic`; načtete jej v kódu, aby se zabránilo vodoznakům. + +Po instalaci balíčku otevřete `Program.cs`. Uvidíte výchozí metodu `Main` — nahraďte její obsah kostrou, kterou budeme postupně budovat. + +## Krok 2: Konfigurace OCR enginu pro ruský jazyk + +Srdcem operace je objekt `OcrEngine`. Musíme mu říct dvě věci: jaký jazyk rozpoznávat a kde najde soubory jazykových modelů. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Proč je to důležité:** Pokud vynecháte nastavení `Language = OcrLanguage.Russian`, engine použije výchozí angličtinu a všechny cyrilické znaky se zobrazí jako nesrozumitelné symboly. `ResourceFolder` ukazuje na adresář, kde leží soubor `rus.traineddata`; bez něj Aspose vyhodí výjimku *resource not found*. + +## Krok 3: Načtení obrázku pro OCR + +Nyní musíme **načíst obrázek pro OCR**. Aspose OCR pracuje s `System.Drawing.Image`, takže můžete předat libovolný podporovaný formát (PNG, JPEG, BMP, atd.). Ujistěte se, že cesta k souboru je správná; relativní cesty jsou v pořádku, pokud obrázek umístíte vedle spustitelného souboru. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Hraniční případ:** Pokud je obrázek velký (více než 5 MB), může být vhodné jej nejprve zmenšit. Přesnost OCR klesá, když je DPI příliš nízké, ale obrovské soubory mohou zatížit paměť. Rychlé zmenšení lze provést pomocí `Graphics`, pokud je potřeba. + +## Krok 4: Rozpoznání textu – From Image to Text C# Style + +S nakonfigurovaným enginem a načteným obrázkem je samotné rozpoznání jedním voláním: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Po spuštění programu (`dotnet run`) byste měli vidět něco jako: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Pokud výstup vypadá jako nesmysl, zkontrolujte: + +- Soubor `rus.traineddata` je přítomen v `ResourceFolder`. +- Obrázek není příliš rozmazaný; zvažte předzpracování jednoduchým binarizačním filtrem. +- Nastavení jazyka je skutečně `OcrLanguage.Russian`. + +## Krok 5: Ladění a běžné úskalí + +### Úprava prahu spolehlivosti + +Aspose OCR interně vrací hodnotu spolehlivosti pro každý znak. API ji přímo neexponuje, ale můžete povolit **detailní výstup**, abyste viděli, která slova mají nízkou spolehlivost: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Pokud zaznamenáte časté chybné rozpoznání, zkuste: + +- **Předzpracování**: Převod obrázku na odstíny šedi, zvýšení kontrastu nebo aplikaci mediánového filtru. +- **Nastavení DPI**: Ujistěte se, že obrázek má alespoň 300 DPI pro cyrilické skripty. + +### Hromadné zpracování více obrázků + +Pokud potřebujete **extrahovat text z obrázku** ve velkém množství, zabalte logiku rozpoznání do smyčky: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Nyní každý PNG získá svůj vlastní `.txt` soubor — užitečné pro archivaci dokumentů. + +### Práce s Unicode výstupem + +Cyrilické znaky jsou Unicode, takže se ujistěte, že vaše konzole dokáže zobrazit tyto znaky: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Umístěte tento řádek hned po startu metody `Main`. Bez něj můžete vidět otazníky (`?`) místo ruských písmen. + +## Kompletní funkční příklad + +Níže je kompletní, připravený k běhu kód. Zkopírujte jej do `Program.cs`, upravte cesty a můžete spustit. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Očekávaný výstup** (za předpokladu, že ukázkový obrázek obsahuje text „Пример текста на русском языке."): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Pokud uvidíte něco jiného, vraťte se k tipům v kroku 5. + +## Závěr + +Nyní máte solidní end‑to‑end příklad, jak **ocr russian text** v C# pomocí Aspose OCR. Od instalace knihovny, přes konfiguraci ruského jazykového modelu, až po načtení obrázku a převod na čistý Unicode text, vše je pokryto. + +Pamatujte, že klíčem k spolehlivému OCR jsou kvalitní zdrojové materiály: čistá písma, dostatečné DPI a správné jazykové zdroje. Jakmile zvládnete základy, můžete rozšířit řešení na hromadné zpracování, integraci s cloudovým úložištěm nebo dokonce kombinovat s AI post‑processingem pro kontrolu pravopisu. + +### Co dál? + +- Prozkoumejte **aspose ocr c#** pokročilé možnosti jako analýzu rozvržení nebo výstup do PDF. +- Spojte to s **extract text from image** workflow v Azure Functions pro serverless zpracování. +- Vyzkoušejte jiné jazyky — stačí změnit `OcrLanguage.Russian` na `OcrLanguage.English` či jiný podporovaný kód. + +Máte otázky nebo obtížný obrázek, který nechce spolupracovat? Zanechte komentář níže a šťastné programování! + +![ocr russian text example](ocr-russian-example.png){alt="příklad ruského textu OCR"} + +## Související tutoriály + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/czech/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..469d2ab57 --- /dev/null +++ b/ocr/czech/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,208 @@ +--- +category: general +date: 2026-05-25 +description: rozpoznat text z obrázku pomocí Aspose OCR v C#. Naučte se, jak načíst + obrázek pro OCR, nastavit jazyk OCR, vytvořit OCR engine a extrahovat text z TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: cs +og_description: Rozpoznávat text z obrázku pomocí Aspose OCR v C#. Tento tutoriál + ukazuje, jak vytvořit OCR engine, načíst obrázek pro OCR, nastavit jazyk OCR a extrahovat + text z TIFFu. +og_title: rozpoznat text z obrázku pomocí Aspose OCR – kompletní průvodce C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Rozpoznat text z obrázku pomocí Aspose OCR – kompletní průvodce C# +url: /cs/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Rozpoznání textu z obrázku pomocí Aspose OCR – Kompletní průvodce v C# + +Už jste někdy potřebovali **rozpoznat text z obrázku**, ale nebyli jste si jisti, která knihovna vám poskytne jak rychlost, tak přesnost? Nejste v tom sami. V mnoha projektech zpracování faktur nebo archivace je největším problémem získat čistý, prohledávatelný text z TIFF souborů bez psaní vlastního parseru. + +Takže: Aspose OCR pro .NET udělá celý tento proces hračkou. V tomto průvodci projdeme vše, co potřebujete – instalaci balíčku, **vytvoření OCR engine**, načtení TIFF, nastavení jazyka OCR a nakonec **extrahování textu z TIFF**. Na konci budete mít připravenou konzolovou aplikaci, která dokáže **rozpoznat text z obrázku** během okamžiku. + +## Požadavky + +- .NET 6.0 nebo novější (kód funguje také s .NET Core a .NET Framework) +- Visual Studio 2022 (nebo jakékoli IDE, které preferujete) +- Aspose.OCR NuGet package (GPU podpora vyžaduje doplněk `Aspose.OCR.Gpu`) +- GPU s podporou CUDA, pokud chcete extra rychlost (volitelné, ale doporučené) + +> **Pro tip:** Pokud nemáte GPU, stačí vynechat řádek `GpuDevice` a engine se automaticky přepne na CPU. + +## Krok 1: Instalace Aspose OCR a vytvoření OCR engine + +Nejprve přidejte potřebné balíčky přes NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Nyní můžeme **vytvořit OCR engine**. Tento objekt je srdcem procesu; obsahuje konfiguraci, jako je zařízení, na kterém běží, a limity paměti. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Proč je to důležité:** Připojením engine k GPU dramaticky zkrátíte dobu potřebnou k **rozpoznání textu z obrázku**, zejména u velkých dávkách vysoce rozlišených TIFF souborů. + +## Krok 2: Načtení obrázku pro OCR + +Dále potřebujeme **načíst obrázek pro OCR**. Aspose.OCR pracuje s `System.Drawing.Image`, takže jakýkoli formát podporovaný GDI+ (včetně multi‑page TIFF) je v pořádku. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Pokud pracujete s multi‑page TIFF, můžete procházet stránky pomocí `image.SelectActiveFrame`, ale ve většině scénářů stačí jedno volání. + +## Krok 3: Nastavení jazyka OCR + +Engine si sám neví, v jakém jazyce skenujete. **Nastavte jazyk OCR** před spuštěním rozpoznávače; jinak získáte spoustu nesmyslného výstupu. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Věděli jste?** Přepínání jazyků za běhu je levné – můžete dokonce zpracovat dokument s více jazyky změnou této vlastnosti mezi stránkami. + +## Krok 4: Provedení rozpoznání – Rozpoznání textu z obrázku + +Teď ta zábavná část: skutečně **rozpoznat text z obrázku**. Metoda `Recognize` vrací prostý řetězec se všemi detekovanými znaky. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Pokud potřebujete skóre důvěry nebo ohraničující rámečky, můžete použít přetíženou verzi, která vrací objekt `OcrResult`, ale pro většinu úloh extrakce stačí prostý řetězec. + +## Krok 5: Extrahování textu z TIFF (a zpracování souborů s více stránkami) + +Když je zdroj TIFF obsahující několik stránek, budete chtít opakovat kroky 2‑4 pro každý rámec. Zde je rychlá smyčka, která **extrahuje text z TIFF** stránku po stránce: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Výše uvedený kód vypisuje extrahovaný text pro každou stránku, což usnadňuje přesměrování výsledků do databáze nebo vyhledávacího indexu. + +## Krok 6: Zobrazení nebo uložení extrahovaného textu + +Nakonec **zobrazíme extrahovaný text** a případně jej zapíšeme do souboru pro pozdější zpracování. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Spuštění programu by mělo vypsat rozpoznané znaky a vytvořit `extracted_text.txt` vedle vašeho zdrojového TIFF. + +--- + +## Časté otázky a okrajové případy + +- **Co když není moje GPU detekováno?** + Odstraňte řádek `GpuDevice`; engine se automaticky přepne do režimu CPU. Výkon bude pomalejší, ale výsledky zůstanou přesné. + +- **Mohu zpracovávat soubory PNG nebo JPEG?** + Rozhodně – `Image.FromFile` funguje s jakýmkoli formátem podporovaným System.Drawing, takže můžete **načíst obrázek pro OCR** bez ohledu na příponu. + +- **Jak zacházet s nízkým rozlišením skenů?** + Zvyšte `ocrEngine.PreprocessOptions.Dpi` před voláním `Recognize`. Vyšší DPI poskytne engine více pixelů k práci, což zlepšuje přesnost. + +- **Existuje limit velikosti TIFF?** + Vlastnost `GpuMemoryLimit` omezuje využití GPU. Pokud limit překročíte, engine přejde na CPU pro zbývající stránky. + +## Závěr + +Nyní máte kompletní, připravený k nasazení úryvek kódu, který **rozpozná text z obrázku** pomocí Aspose OCR v C#. Tutoriál pokryl, jak **vytvořit OCR engine**, **načíst obrázek pro OCR**, **nastavit jazyk OCR** a **extrahovat text z TIFF** – vše s využitím akcelerace GPU pro rychlost. + +Od sem můžete: + +- Experimentovat s různými jazyky (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` atd.). +- Integrovat výstup do prohledávatelného indexu ElasticSearch. +- Přidat post‑processing (kontrola pravopisu, čištění regulárními výrazy) pro zlepšení kvality dat. + +Vyzkoušejte to na vlastní dávce faktur, upravte limity paměti a sledujte, jak OCR výkon stoupá. Šťastné programování! + +## Související tutoriály + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..050219f5c 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. +### [Maak OCR-engine in C# – Complete gids](./create-ocr-engine-in-c-complete-guide/) +Leer stap‑voor‑stap hoe je een OCR‑engine in C# maakt en configureert met Aspose.OCR voor optimale tekstherkenning. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/dutch/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..2cecf279e --- /dev/null +++ b/ocr/dutch/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Maak een OCR‑engine in C# en leer hoe je de evaluatiemodus en licentiestatus + in een paar regels code kunt controleren. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: nl +og_description: Maak een OCR-engine in C# en zie direct hoe je de evaluatiemodus kunt + detecteren en de licentiestatus kunt weergeven. +og_title: Maak een OCR‑engine in C# – Stapsgewijze handleiding +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Maak OCR-engine in C# – Complete gids +url: /nl/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Maak OCR Engine in C# – Complete gids + +Heb je je ooit afgevraagd hoe je **OCR engine maken** objecten in C# kunt maken zonder eindeloos door documentatie te zoeken? Je bent niet de enige. Veel ontwikkelaars lopen tegen een muur aan wanneer ze een OCR-engine moeten opzetten, moeten controleren of deze in proefmodus draait, en de licentiestatus aan gebruikers moeten tonen. + +In deze tutorial lopen we een beknopt, end‑to‑end voorbeeld door dat **een OCR engine maakt**, de **OCR engine evaluatiemodus** controleert, en een vriendelijke boodschap over de licentiestatus afdrukt. Aan het einde heb je een kant‑klaar console‑applicatie en een duidelijk mentaal model voor het omgaan met OCR-licenties in je eigen projecten. + +## Wat je zult leren + +- Hoe je een `OcrEngine` instantieert (de kern van elke OCR-werkstroom). +- Waarom het detecteren van **evaluatiemodus** belangrijk is voor naleving en gebruikerservaring. +- De beste manier om de **OCR-licentie** status te **controleren** en te reageren op onverwachte toestanden. +- Veelvoorkomende valkuilen—null‑referenties, foutafhandeling en versie‑mismatches. + +Geen externe tools nodig naast de OCR SDK die je al geïnstalleerd hebt. Als je vertrouwd bent met basis C#‑syntaxis, ben je klaar om te gaan. + +## Vereisten + +- .NET 6.0 of later (de code compileert met .NET Core en .NET Framework). +- Een OCR SDK die een `OcrEngine`‑klasse exposeert met een `IsEvaluation`‑eigenschap (bijvoorbeeld de hypothetische `MyOcrSdk`). +- Een teksteditor of IDE (Visual Studio, VS Code, Rider—kies je favoriet). + +Dat is alles. Laten we duiken. + +## Stap 1: Een nieuw console‑project opzetten + +Eerst maak je een nieuw console‑app zodat je de code geïsoleerd kunt uitvoeren. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Open het gegenereerde `Program.cs`. We zullen de inhoud vervangen door een volledig voorbeeld dat **OCR engine maken**‑instanties maakt en licenties afhandelt. + +## Stap 2: De OCR SDK‑namespace importeren + +Aangenomen dat de SDK via NuGet is gerefereerd (`MyOcrSdk` is een placeholder), voeg de using‑directive toe aan de bovenkant van het bestand. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Als je het pakket nog niet hebt toegevoegd, voer dan uit: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Houd je SDK‑versie up‑to‑date; nieuwere releases verbeteren vaak de detectie van de evaluatiemodus. + +## Stap 3: De OCR Engine‑instantie maken + +Nu maken we eindelijk **OCR engine** objecten. Dit is het hart van elke OCR‑werkstroom—beschouw het als het brein dat later afbeeldingen zal lezen. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Waarom is deze stap cruciaal? De `OcrEngine` bevat alle configuratie, taalpakketten en licentiegegevens. Zonder deze kun je geen afbeeldingen verwerken of de evaluatie‑vlag opvragen. + +> **Side note:** Sommige SDK's laten je een configuratie‑object doorgeven aan de constructor (bijv. taal, DPI). Als je aangepaste instellingen nodig hebt, wijzig dan de regel overeenkomstig. + +## Stap 4: De OCR Engine‑evaluatiemodus bepalen + +De meeste OCR‑leveranciers leveren een proefversie die draait in **evaluatiemodus** totdat een geldige licentiesleutel is opgegeven. Weten of je in proefmodus bent, stelt je in staat om passende UI‑aanwijzingen te tonen of bepaalde functies te beperken. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +De `IsEvaluation`‑eigenschap retourneert `true` wanneer de engine niet gelicentieerd is of een tijd‑beperkte proefversie gebruikt. Het is een snelle, betrouwbare manier om premium‑functies te beschermen. + +### Wat als de eigenschap ontbreekt? + +Oudere SDK‑versies kunnen in plaats daarvan een methode zoals `GetLicenseInfo()` exposen. In dat geval inspecteer je het geretourneerde object op een `IsTrial`‑vlag. Raadpleeg altijd de SDK‑changelog bij een upgrade. + +## Stap 5: De huidige licentiestatus weergeven + +Tot slot laten we de gebruiker zien of de engine gelicentieerd is of nog in proefmodus. Een eenvoudige console‑write‑line doet het, maar je kunt het aanpassen voor GUI‑apps. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +De ternary‑operator houdt de code netjes, en de berichten zijn duidelijk genoeg voor eindgebruikers of ontwikkelaars die logs lezen. + +## Volledig werkend voorbeeld + +Alles bij elkaar genomen, hier is een zelfstandige programma dat je kunt copy‑pasten in `Program.cs` en uitvoeren met `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Verwachte output + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +Als de SDK een uitzondering gooit (bijv. ontbrekende native DLL), zal het catch‑blok een nuttig foutbericht afdrukken in plaats van de hele app te laten crashen. + +## Omgaan met randgevallen en veelvoorkomende valkuilen + +### 1. Null‑engine‑instanties + +Hoewel de constructor meestal een geldig object retourneert, kunnen sommige SDK's `null` teruggeven als vereiste native afhankelijkheden ontbreken. Bescherm hiertegen: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Licentie‑verval tijdens uitvoering + +Een proeflicentie kan halverwege een sessie verlopen. Vraag periodiek `IsEvaluation` opnieuw op als je app lange tijd actief blijft. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Verschillende eigenschapsnamen tussen versies + +Oudere releases kunnen `engine.EvaluationMode` of `engine.License.IsTrial` exposen. Bij een upgrade, zoek de SDK‑release‑notes voor breaking changes. + +### 4. Multi‑threaded scenario's + +Als je meerdere OCR‑workers opstart, instantiateer **één OCR engine per thread** tenzij de SDK expliciet thread‑safe delen ondersteunt. Het delen van één engine kan leiden tot race‑conditions en onjuiste licentie‑lezingen. + +## Pro‑tips voor productiegebruik + +- **Cache de licentiestatus** na de eerste controle om onnodige eigenschapsaanroepen te vermijden. +- **Log de licentiesleutel** (gemaskeerd) bij opstarten voor audit‑trails—helpt support‑teams licentie‑problemen te diagnosticeren. +- **Voorzie een UI‑schakelaar** die gebruikers vertelt dat ze in proefmodus zijn en een “Koop licentie”‑knop aanbiedt. +- **Automatiseer licentie‑vernieuwing** met de activatie‑API van de SDK, indien beschikbaar, om de gebruikerservaring naadloos te houden. + +## Conclusie + +We hebben zojuist **OCR engine** objecten gemaakt in een handvol regels, de **OCR engine evaluatiemodus** geïnspecteerd, en een duidelijke **OCR licentiestatus**‑boodschap afgedrukt. Het volledige voorbeeld werkt direct, behandelt fouten elegant, en belicht het “waarom” achter elke stap—zodat je het kunt aanpassen aan desktop-, web- of service‑scenario's. + +Vervolgens kun je verkennen: + +- Het voeden van afbeeldingen aan `engine.Recognize` en het omgaan met meertalige ondersteuning. +- Het gebruiken van **check OCR license** API's om programmatically een aangeschafte sleutel te activeren. +- Integratie met UI‑frameworks (WinForms, WPF, MAUI) om licentie‑badges weer te geven. + +Probeer die uit, en je hebt een robuuste OCR‑basis klaar voor elke applicatie. Veel plezier met coderen! + +## Gerelateerde tutorials + +- [Hoe OCR te extraheren – OCR-configuratie](/ocr/english/net/ocr-configuration/) +- [Hoe OCR-resultaten te krijgen met Aspose.OCR voor .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Hoe PDF OCR'en in .NET met Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/ocr-optimization/_index.md b/ocr/dutch/net/ocr-optimization/_index.md index b95973f36..9151538eb 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. +### [Afbeelding voorbewerken voor OCR – Complete Aspose C#‑gids](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Leer hoe je afbeeldingen optimaliseert voor OCR met een volledige C#‑handleiding, inclusief filters en best practices. ## Veelgestelde vragen diff --git a/ocr/dutch/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/dutch/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..6f4fdbadc --- /dev/null +++ b/ocr/dutch/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Preprocess afbeelding voor OCR met Aspose om de OCR‑nauwkeurigheid te + verbeteren en voer OCR uit op JPEG‑bestanden. Leer hoe je tekst kunt extraheren + met Aspose in een duidelijke, stapsgewijze tutorial. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: nl +og_description: Verwerk afbeelding voor OCR met Aspose om de OCR‑nauwkeurigheid te + verbeteren. Volg deze gids om OCR op een JPEG uit te voeren en tekst te extraheren + met Aspose in C#. +og_title: Afbeelding voor OCR voorbewerken – Aspose C#-handleiding +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Afbeelding voor OCR voorbewerken – Complete Aspose C#‑gids +url: /nl/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Preprocess Image for OCR – Complete Aspose C# Guide + +Ever wondered how to **preprocess image for OCR** so the text comes out clean every time? You’re not the only one—developers constantly battle noisy scans, low‑contrast JPEGs, and unpredictable lighting. The good news? With a few smart tweaks you can **improve OCR accuracy** dramatically, and Aspose makes it painless. + +In this tutorial we’ll walk through a real‑world example that shows you how to **run OCR on JPEG** images, apply a custom image‑processing pipeline, and finally **extract text using Aspose**. By the end you’ll have a ready‑to‑paste C# snippet that you can drop into any .NET project. + +## Wat je zult leren + +- Waarom voorverwerking belangrijk is en welke filters de grootste winst opleveren. +- Hoe je Aspose.OCR’s `ImageProcessingOptions` configureert voor kantcorrectie, ruisonderdrukking, binarisatie en contrastverhoging. +- De exacte code die nodig is om **run OCR on JPEG** bestanden uit te voeren en schone tekst op te halen. +- Tips en valkuilen die je OCR‑pipeline robuust houden in productie. + +Geen ervaring met Aspose is vereist; alleen een basiskennis van C# en Visual Studio (of je favoriete IDE). Laten we beginnen. + +![Preprocess image for OCR example](preprocess-ocr.png "Preprocess image for OCR") + +## Stap 1: Installeer de Aspose.OCR Engine – Preprocess Image for OCR + +Allereerst hebben we een `OcrEngine`‑instantie nodig en moeten we aangeven welke taal we verwachten. In de meeste gevallen is Engels de standaard, maar je kunt het vervangen door Frans, Duits, enz., door de `OcrLanguage`‑enum te wijzigen. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Why this matters:** De engine is het hart van de bewerking; zonder deze kun je geen van de beeldfilters toepassen die daadwerkelijk **preprocess image for OCR**. Beschouw het als de keuken waar alle ingrediënten worden gemengd. + +## Stap 2: Bouw een Aangepaste Beeld‑Verwerkings‑Pipeline – Improve OCR Accuracy + +Nu komt het interessante deel. Aspose laat je meerdere filters achter elkaar schakelen. Hieronder schakelen we vier van de meest effectieve in: + +1. **Deskew** – maakt scheve documenten recht (standaard max 5°). +2. **Denoise** – maakt korrelige achtergronden glad. +3. **Binarize** – zet de afbeelding om naar zwart‑wit met behulp van een drempel. +4. **ContrastBoost** – laat zwakke tekens opvallen. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** Als je bronafbeeldingen al scherp zijn, kun je de `Strength` verlagen of een filter volledig uitschakelen. Over‑verwerking kan soms zwakke tekens verwijderen, dus experimenteer met echte monsters. + +## Stap 3: Laad de JPEG (of een andere afbeelding) en voer OCR uit – Run OCR on JPEG + +Aspose werkt met elk afbeeldingsformaat dat .NET kan lezen—JPEG, PNG, BMP, je noemt het. Hier zie je hoe je een JPEG‑bestand in de engine laadt en het herkenningsproces start. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Why JPEG?** JPEG‑compressie introduceert vaak artefacten die OCR verwarren. Onze voorverwerkings‑pipeline, vooral de denoise‑ en binarize‑stappen, vermindert die problemen, waardoor je **run OCR on JPEG** met vertrouwen kunt uitvoeren. + +## Stap 4: Output de Herkende Tekst – Extract Text Using Aspose + +Tot slot schrijven we de tekst simpelweg naar de console, een bestand, of een downstream‑service. Voor demonstratiedoeleinden is de console voldoende. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Wanneer je het programma uitvoert, zou je iets moeten zien als: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Als de output er rommelig uitziet, ga dan terug naar **Step 2** en pas de filterinstellingen aan. Kleine aanpassingen leveren vaak grote verbeteringen op in **improve OCR accuracy**. + +## Veelvoorkomende Randgevallen en Hoe ze Aan te Pakken + +| Situatie | Aanbevolen Aanpassing | +|-----------|----------------------| +| **Zeer donkere afbeeldingen** | Verhoog `ContrastBoost.Level` naar 1,5 of hoger. | +| **Scheefstand > 5°** | Verhoog `DeskewOptions.MaxAngle` (bijv. 10.0) of roteer de afbeelding handmatig vooraf. | +| **Gekleurde tekst op gekleurde achtergrond** | Gebruik `BinarizeOptions` met een aangepaste drempel of schakel over naar `AdaptiveBinarizeOptions`. | +| **Grote bestanden ( > 5 MB )** | Laad de afbeelding eerst in een `MemoryStream` om bestandsvergrendelingsproblemen te voorkomen. | + +Deze aanpassingen houden je pipeline flexibel en toekomstbestendig, vooral wanneer je **extract text using Aspose** moet gebruiken vanuit diverse bronnen. + +## Volledig Werkend Voorbeeld – Alle Stappen op één Plaats + +Hieronder staat het volledige, kant‑klaar‑om‑te‑kopiëren programma. Het compileert met .NET 6+ en vereist alleen het `Aspose.OCR` NuGet‑pakket. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Sla dit op als `Program.cs`, voeg het Aspose.OCR‑pakket toe (`dotnet add package Aspose.OCR`), en voer `dotnet run` uit. Je ziet de opgeschoonde tekst in de console verschijnen. + +## Samenvatting – Waarom Deze Aanpak Werkt + +- **Preprocess image for OCR**: De pipeline verwijdert de meest voorkomende foutbronnen (scheefstand, ruis, laag contrast). +- **Improve OCR accuracy**: Elk filter is afgestemd om de signaal‑ruisverhouding die de engine ziet te verhogen. +- **Run OCR on JPEG**: Zelfs gecomprimeerde afbeeldingen worden leesbaar na kantcorrectie en binarisatie. +- **Extract text using Aspose**: De `Recognize`‑methode retourneert een eenvoudige string, klaar voor elke downstream‑logica. + +Samen geven deze stappen je een betrouwbare OCR‑oplossing van productie‑kwaliteit in slechts een handvol regels. + +## Volgende Stappen en Gerelateerde Onderwerpen + +- **Batch processing** – Loop door een map met afbeeldingen en schrijf elk resultaat naar een `.txt`‑bestand. +- **Language packs** – Vervang `OcrLanguage.English` door `OcrLanguage.Spanish` of voeg aangepaste woordenboeken toe. +- **PDF extraction** – Combineer Aspose.OCR met Aspose.PDF om tekst direct uit gescande PDF's te halen. +- **Performance tuning** – Voer de engine parallel uit met `Parallel.ForEach` voor grote workloads. + +Voel je vrij om te experimenteren met de filterwaarden, verschillende afbeeldingsformaten te proberen, of extra Aspose-filters te combineren zoals `SharpnessOptions`. De mogelijkheden zijn eindeloos zodra je de basis onder de knie hebt. + +--- + +*Happy coding! Als je tegen problemen aanloopt, laat dan een reactie achter en we lossen het samen op.* + +## Gerelateerde Tutorials + +- [Voorverwerken van afbeelding OCR met Aspose.OCR-filters voor .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Tekst extraheren uit afbeelding – OCR-optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) +- [Afbeeldingstekst extraheren C# met taalkeuze via 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/text-recognition/_index.md b/ocr/dutch/net/text-recognition/_index.md index e39716b53..1ec884109 100644 --- a/ocr/dutch/net/text-recognition/_index.md +++ b/ocr/dutch/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Verbeter uw .NET-toepassingen met Aspose.OCR voor efficiënte beeldtekstherkenni Ontgrendel het potentieel van OCR in .NET met Aspose.OCR. Extraheer moeiteloos tekst uit PDF's. Download nu voor een naadloze integratie-ervaring. ### [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. +### [Tekst herkennen van afbeelding met Aspose OCR – Complete C#-gids](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Leer hoe u met Aspose OCR en C# tekst uit afbeeldingen haalt in deze complete stap‑voor‑stap gids. +### [Hoe OCR in C# te gebruiken – Chinees tekst herkennen vanuit JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Leer hoe u met Aspose.OCR en C# Chinese tekst uit JPG-afbeeldingen nauwkeurig kunt herkennen. +### [OCR Russische tekst in C# – Complete gids met Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Leer hoe u met Aspose OCR en C# Russische tekst uit afbeeldingen haalt in deze volledige stap‑voor‑stap gids. +### [Tekst extraheren uit afbeelding in C# – Complete Aspose OCR-gids](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Ontdek hoe u met Aspose OCR en C# tekst uit afbeeldingen kunt extraheren met deze volledige stap‑voor‑stap gids. +### [Tekst extraheren uit afbeelding in ASP.NET Core Minimal API – Complete gids](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Leer hoe u met Aspose OCR tekst uit afbeeldingen haalt via een ASP.NET Core Minimal API in deze volledige stap‑voor‑stap gids. +### [c# OCR-tutorial: Tekst extraheren uit PNG-bonnetjes met Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Leer hoe u met Aspose OCR en C# tekst uit PNG‑bonnetjes haalt in deze stapsgewijze gids. +### [TIFF naar tekst converteren in C# – Complete batch-OCR-gids](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Leer hoe u met Aspose.OCR in C# TIFF-bestanden batchgewijs naar tekst converteert met deze volledige gids. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/dutch/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..8785a28ea --- /dev/null +++ b/ocr/dutch/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,222 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR‑tutorial die laat zien hoe je een afbeeldingsbestand in c# laadt + en png‑tekst van een bon herkent met Aspose OCR – stapsgewijze handleiding. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: nl +og_description: c# OCR-tutorial die je stap voor stap begeleidt bij het laden van + een afbeeldingsbestand in c# en het herkennen van png-tekst van een bon met behulp + van Aspose OCR. +og_title: c# OCR-tutorial – Tekst extraheren uit PNG-bonnetjes +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR-tutorial: Tekst extraheren uit PNG-bonnen met Aspose' +url: /nl/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Tekst extraheren uit PNG‑bonnen met Aspose + +Heb je ooit een **c# OCR tutorial** nodig gehad die echt werkt zonder eindeloos Googelen? Dan ben je hier op het juiste adres. In deze gids **laden we een afbeeldingbestand c#**, **herkennen we png‑tekst**, en **lezen we de bon‑OCR**‑resultaten, terwijl we je laten zien hoe je **perform OCR image**‑verwerking uitvoert met Aspose OCR. + +We beginnen met het installeren van het benodigde NuGet‑pakket, lopen elke regel code door, en eindigen met een nette JSON‑dump die je rechtstreeks in je volgende datapijplijn kunt pompen. Geen poespas, alleen een praktische, kant‑klaar‑oplossing. + +## Wat je zult leren + +- Hoe je Aspose OCR instelt in een .NET 6 (of later) project. +- De exacte stappen om **een afbeeldingbestand te laden c#** en aan de engine te geven. +- Hoe je **png‑tekst herkent** van een bonafbeelding en het resultaat vastlegt. +- Manieren om **bon‑OCR**‑output te lezen als mooi opgemaakte JSON. +- Tips voor **perform OCR image**‑operaties op verschillende bestandstypen en het omgaan met veelvoorkomende valkuilen. + +**Prerequisites** +- Visual Studio 2022 (of elke IDE die je wilt). +- .NET 6 SDK of nieuwer. +- Een PNG‑bonafbeelding bij de hand (we noemen deze `receipt.png`). + +Als je dat hebt, laten we beginnen. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial resultaat met JSON‑output") + +## c# OCR Tutorial – Aspose OCR‑engine instellen + +Allereerst hebben we de Aspose OCR‑bibliotheek nodig. Open je terminal in de solution‑map en voer uit: + +```bash +dotnet add package Aspose.OCR +``` + +Dat ene commando haalt alles binnen wat nodig is, inclusief native binaries voor afbeeldingsdecodering. Zodra het geïnstalleerd is, maak je een nieuw console‑project aan of voeg je de code toe aan een bestaand project. + +### Waarom Aspose? + +Aspose OCR ondersteunt meer dan 30 talen, werkt offline, en retourneert een rijk `OcrResult`‑object—perfect voor **perform OCR image**‑taken waarbij je meer nodig hebt dan alleen platte tekst. + +## Afbeeldingbestand laden c# en de bon voorbereiden + +Nu de bibliotheek klaar is, laten we **een afbeeldingbestand laden c#**. De `System.Drawing.Image`‑klasse doet het zware werk, maar je kunt ook `SkiaSharp` gebruiken als je een cross‑platform alternatief wilt. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** Plaats de `Image` in een `using`‑statement (zoals getoond) om native resources direct vrij te geven—vooral belangrijk wanneer je **perform OCR image** uitvoert op veel bestanden in een lus. + +## PNG‑tekst herkennen met Aspose + +Met de afbeelding in het geheugen kan de engine nu **png‑tekst herkennen**. Aspose retourneert een `OcrResult` dat zowel de ruwe string als gedetailleerde gegevens over elk herkend woord bevat. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Waarom `RecognizeWithResult` gebruiken in plaats van de simpelere `Recognize`? Het eerste geeft je toegang tot confidence‑scores, bounding boxes en regeleinden—handig als je later **bon‑OCR** moet **read receipt OCR** voor het extraheren van regelitems. + +## Bon‑OCR‑resultaat lezen als JSON + +De meeste downstream‑systemen houden van JSON, dus laten we het `OcrResult` serialiseren. De `System.Text.Json`‑serializer gaat elegant om met complexe objecten, en we schakelen inspringing in voor leesbaarheid. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Het resulterende JSON ziet er ongeveer zo uit (ingekort voor de duidelijkheid): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Je kunt `jsonResult` nu doorsturen naar een database, een berichtwachtrij, of simpelweg loggen voor debugging. + +## Perform OCR Image Processing en output weergeven + +Tot slot, de JSON naar de console schrijven. In een echte applicatie zou je het waarschijnlijk naar een bestand schrijven of via HTTP versturen, maar de console maakt het makkelijk om te verifiëren dat alles werkt. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Voer het programma uit (`dotnet run`) en je zou de mooi opgemaakte JSON moeten zien. Als de bonafbeelding duidelijk is, zal de tekst spot‑on zijn; zo niet, overweeg dan de beeldresolutie te verhogen of een pre‑processing filter toe te passen (bijv. grijstinten, contrastverhoging) voordat je het aan de engine geeft. + +### Veelvoorkomende randgevallen afhandelen + +| Situatie | Wat te doen | +|-----------|------------| +| **Afbeelding is onscherp** | Pre‑process met `System.Drawing` om te verscherpen of DPI te verhogen. | +| **Bon bevat meerdere talen** | Stel `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` in | +| **Grote batchverwerking** | Hergebruik één `OcrEngine`‑instantie; wijzig alleen de `Image` per iteratie. | +| **Geheugendruk** | Dispose `Image`‑objecten direct en overweeg `await Task.Run` voor async‑pijplijnen. | + +Deze aanpassingen houden je **perform OCR image**‑workflow robuust, zelfs wanneer de invoer niet perfect is. + +## Wrap‑Up + +Gefeliciteerd—je hebt zojuist een **c# OCR tutorial** voltooid die een afbeelding laadt, **png‑tekst herkent**, en **bon‑OCR**‑output leest als nette JSON. De kernstappen (engine‑setup, afbeelding laden, OCR‑uitvoering, serialisatie en weergave) vormen een solide basis die je kunt uitbreiden naar facturen, paspoorten of andere gescande documenten. + +### Wat nu? + +- Experimenteer met **load image file c#** via `SkiaSharp` voor echte cross‑platform ondersteuning. +- Duik dieper in `OcrResult.Words` om regelitems, prijzen en data te extraheren—perfect voor onkosten‑tracking apps. +- Combineer deze tutorial met Azure Functions of AWS Lambda om een serverless bon‑verwerkings‑API te bouwen. + +Voel je vrij om de code aan te passen, meer afbeeldingen toe te voegen, of zelfs over te stappen op een andere taal‑pack. De wereld van OCR zit vol verrassingen, en nu heb je de tools om ze te ontdekken. + +Happy coding, en moge je bonnen altijd leesbaar blijven! + + +## Gerelateerde tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Use OCR - Recognize Image without Text Area Detection](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/dutch/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..02c8415b7 --- /dev/null +++ b/ocr/dutch/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-05-25 +description: Converteer TIFF naar tekst met Aspose.OCR in C#. Leer batchafbeelding-naar-tekstconversie + en haal efficiënt tekst uit TIFF‑bestanden. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: nl +og_description: Converteer TIFF naar tekst met Aspose.OCR. Deze gids toont batch afbeelding‑naar‑tekstconversie + en hoe je tekst uit TIFF‑bestanden kunt extraheren in een paar regels C#. +og_title: TIFF converteren naar tekst in C# – Complete batch‑OCR‑gids +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: TIFF converteren naar tekst in C# – Complete batch‑OCR‑gids +url: /nl/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# TIFF naar Tekst Converteren in C# – Complete Batch OCR Gids + +Heb je ooit **TIFF naar tekst** moeten converteren maar wist je niet waar te beginnen? Je bent niet de enige—veel ontwikkelaars lopen tegen batch OCR aan bij het verwerken van gescande documenten. In deze tutorial lopen we een praktische oplossing door die **tekst uit TIFF**‑bestanden haalt met Aspose.OCR, en we doen het parallel zodat grote mappen in seconden klaar zijn. + +We zullen ook ingaan op best practices voor **batch image to text conversion**, zodat je aan het einde een herbruikbare code‑fragment hebt die een volledige map met gescande afbeeldingen omzet in nette *.txt*-bestanden—perfect voor indexering, zoeken of invoeren in downstream‑analyse. + +## Wat je nodig hebt + +- **.NET 6.0** of later (de code compileert ook op .NET Framework) +- **Aspose.OCR for .NET** NuGet‑pakket (`Install-Package Aspose.OCR`) +- Een map met een of meer *.tif*-bestanden (het klassieke TIFF‑scanformaat) +- Je favoriete IDE (Visual Studio, VS Code, Rider—wat je ook wilt) + +Dat is alles. Geen externe services, geen API‑sleutels, alleen pure C# en Aspose. + +![Schermafbeelding van een TIFF‑bestand dat wordt verwerkt en het resulterende tekstbestand](/images/ocr-result.png "OCR‑resultaat dat de geconverteerde TIFF‑naar‑tekst uitvoer toont") + +*(Alt‑tekst: Schermafbeelding die de geconverteerde TIFF‑naar‑tekst uitvoer op het scherm toont)* + +## Stap 1: OCR‑engine configureren – TIFF naar tekst converteren + +Allereerst hebben we een `OcrEngine`‑instantie nodig die weet dat hij Engelse tekens moet lezen. De engine is het hart van de conversie; door deze correct te configureren zorg je voor betrouwbare resultaten. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Waarom dit belangrijk is:* +Aspose.OCR ondersteunt tientallen talen. Als je te maken hebt met meertalige scans, wijzig je eenvoudig `OcrLanguage.English` naar de juiste enum‑waarde. Het niet definiëren van de taal dwingt de engine in de auto‑detectiemodus, wat langzamer en minder nauwkeurig kan zijn. + +## Stap 2: Alle TIFF‑bestanden verzamelen – Tekst efficiënt uit TIFF halen + +Vervolgens halen we elk *.tif*-bestand uit een map die je opgeeft. Met `Directory.GetFiles` krijgen we een nette array die we kunnen doorgeven aan de batch‑processor. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro‑tip:* De `SearchOption.AllDirectories`‑vlag kan worden gebruikt als je scans zich in sub‑mappen bevinden. Houd er rekening mee dat diepere recursie het geheugenverbruik tijdens de batchstap kan verhogen. + +## Stap 3: Parallel OCR uitvoeren – Batch image to text conversion + +Nu het leuke gedeelte. Aspose.OCR wordt geleverd met een statische helper `BatchOcr.RecognizeAll` die een array van bestandspaden, een engine en een `parallelism`‑hint accepteert. We starten vier threads, wat op een moderne quad‑core laptop bijna lineaire versnelling oplevert. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Waarom parallelisme?* +Het scannen van een batch hoge‑resolutie TIFF‑bestanden kan CPU‑intensief zijn. Door het werk over meerdere threads te verdelen, houden we alle cores bezig, waardoor de totale uitvoeringstijd drastisch wordt verkort. Als je dit op een server met meer cores uitvoert, verhoog dan de `parallelism`‑waarde dienovereenkomstig. + +## Stap 4: Output schrijven – Gescande afbeeldingen naar TXT‑bestanden converteren + +Tot slot lopen we door de dictionary en schrijven elk stuk tekst naar een *.txt*-bestand dat dezelfde basisnaam als het origineel heeft. Dit is het moment waarop **convert scanned images txt** werkelijkheid wordt. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Wat de code doet, in eenvoudige bewoordingen + +1. **Create** een OCR‑engine ingesteld op Engels. +2. **Collect** elk TIFF‑bestand uit de doelmap. +3. **Run** `BatchOcr.RecognizeAll` met vier threads, waarbij elke afbeelding wordt omgezet naar een string. +4. **Loop** over de resultaten, vervang de `.tif`‑extensie door `.txt` en schrijf de string naar de schijf. + +Dat is de volledige **convert TIFF to text** workflow in minder dan 50 regels code. + +## Afhandelen van randgevallen – Wanneer dingen niet soepel verlopen + +- **Missing or corrupted TIFFs** – `BatchOcr` zal een `OcrException` gooien. Plaats de aanroep in een `try / catch` als je een zachte degradatie nodig hebt. +- **Non‑English documents** – wijzig `OcrLanguage.English` naar `OcrLanguage.Spanish`, `OcrLanguage.French`, enz., of gebruik `OcrLanguage.AutoDetect`. +- **Very large images** – overweeg de DPI te verlagen vóór OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) om geheugen te besparen, hoewel je wat nauwkeurigheid kunt verliezen. +- **Output encoding** – als je een specifieke code‑pagina nodig hebt (bijv. Windows‑1252), geef deze door aan `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Pro‑tips voor robuuste batch‑conversies + +- **Log failures**: maak een `List failedFiles` aan en voeg elk bestand toe dat een uitzondering werpt; schrijf de lijst na de lus naar een log. +- **Reuse the engine**: dezelfde `OcrEngine`‑instantie kan hergebruikt worden voor veel bestanden; instantiate niet binnen de lus. +- **Validate the result**: een snelle `if (string.IsNullOrWhiteSpace(extractedText))` kan scans markeren die leeg of onleesbaar waren. +- **Combine with PDF**: als je bron een meer‑pagina PDF is, converteer dan eerst elke pagina naar TIFF (Aspose.PDF doet dat) en voer vervolgens deze batch uit. + +## Volgende stappen – Verder gaan dan eenvoudige conversie + +Nu je **tekst uit TIFF**‑bestanden in bulk kunt **extraheren**, wil je misschien: + +- De *.txt*-bestanden voeden in een zoekindex (Elasticsearch, Azure Cognitive Search). +- Taalherkenning uitvoeren op elk resultaat om documenten naar locatie‑specifieke pipelines te routeren. +- Zoekbare PDF’s genereren door de OCR‑tekst over de originele afbeeldingen te leggen (Aspose.PDF opnieuw). + +Al deze scenario’s bouwen voort op hetzelfde kernidee: **batch image to text conversion** is een bouwsteen voor grotere document‑verwerkende systemen. + +--- + +### Conclusie + +Je hebt zojuist geleerd hoe je **TIFF naar tekst** kunt **converteren** met Aspose.OCR, een volledige map parallel verwerkt, en elk resultaat opslaat als een schoon *.txt*-bestand. De oplossing is lichtgewicht, volledig configureerbaar, en klaar voor productie—of je nu legacy‑facturen digitaliseert, gescande contracten archiveert, of een tekst‑zoekmachine aandrijft. + +Probeer het, pas de paralleliteit aan, en begin die nieuw aangemaakte tekstbestanden in te voeren in de workflow die je nodig hebt. Veel plezier met OCRen! + +--- + +## Gerelateerde tutorials + +- [Tekst extraheren uit afbeeldingen met OCR‑bewerking op mappen](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Tekst extraheren uit afbeelding – OCR‑optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) +- [Afbeeldingstekst extraheren in C# met taalkeuze met 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/dutch/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..8acecad83 --- /dev/null +++ b/ocr/dutch/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Leer hoe je tekst uit een afbeelding kunt extraheren met een minimale + ASP.NET Core‑API. Upload de afbeelding via POST, lees multipart‑formuliagegevens + en voer OCR uit op de afbeelding. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: nl +og_description: Tekst extraheren uit een afbeelding met een minimale ASP.NET Core + API. Deze gids laat zien hoe je een afbeelding uploadt via POST, multipart form‑data + leest en OCR op de afbeelding uitvoert. +og_title: Tekst uit afbeelding extraheren in ASP.NET Core – Stap voor stap +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Tekst uit afbeelding extraheren in ASP.NET Core Minimal API – Complete gids +url: /nl/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tekst uit afbeelding extraheren in ASP.NET Core Minimal API – Complete gids + +Heb je je ooit afgevraagd hoe je **tekst uit afbeelding** kunt extraheren zonder te worstelen met zware frameworks? Je bent niet de enige. Veel ontwikkelaars hebben een snelle manier nodig om gebruikers een foto te laten uploaden en de ruwe tekens terug te krijgen, of het nu gaat om het scannen van bonnetjes, het digitaliseren van handgeschreven notities, of het voeden van een zoekindex. + +In deze tutorial zetten we een kleine ASP.NET Core Minimal API op die **afbeelding uploadt via POST**, de *multipart/form‑data* payload verwerkt, en vervolgens **OCR op afbeelding uitvoert** met een singleton `OcrEngine`. Aan het einde heb je een volledig werkende app die je in elk .NET 8‑project kunt plaatsen en meteen tekst uit afbeelding kunt extraheren. + +## Wat je gaat bouwen + +- Een minimale webapp die luistert op `/ocr`. +- Een endpoint dat een afbeeldingsbestand accepteert dat wordt verzonden met een `multipart/form-data` POST‑verzoek. +- Logica die het geüploade bestand leest, het aan de OCR‑engine doorgeeft en platte‑tekstresultaten retourneert. +- Optioneel GPU‑versnellingsfragment (uitgecommentarieerd) voor degenen met een compatibele kaart. + +**Prerequisites** +- .NET 8 SDK (of later). +- Basiskennis van C# en de commandoregel. +- Een OCR‑bibliotheek die een `OcrEngine`‑klasse exposeert (het voorbeeld gaat uit van een hypothetisch NuGet‑pakket). + +Als je dat hebt, laten we erin duiken. + +## Stap 1: Het project opzetten en het OCR‑pakket toevoegen + +Maak eerst een nieuw webproject aan en haal de OCR‑bibliotheek binnen. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro tip:** Houd je afhankelijkheden up‑to‑date. Nieuwere versies brengen vaak prestatieverbeteringen, vooral voor GPU‑versnelde inferentie. + +## Stap 2: Registreer een Singleton OCR‑Engine (Primaire service) + +We willen één `OcrEngine`‑instantie voor de hele app—geen noodzaak om per verzoek een nieuwe engine te starten. Registreer deze in de servicecontainer van de builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Waarom een singleton?** +Het creëren van een OCR‑engine kan duur zijn—denk aan het laden van neurale‑netwerkgewichten in het geheugen. Door dezelfde instantie te hergebruiken besparen we zowel CPU‑cycli als RAM, wat zich vertaalt naar snellere responstijden voor elke `/ocr`‑aanroep. + +## Stap 3: Bouw de applicatie + +Nu materialiseren we het `WebApplication`‑object. + +```csharp +var app = builder.Build(); +``` + +Die regel lijkt bijna magisch, maar onder de motorkap zet het routing, middleware en de DI‑container die we zojuist hebben geconfigureerd op elkaar. + +## Stap 4: Definieer de POST‑endpoint – “Afbeelding uploaden via POST” + +Hier is het hart van de tutorial: een endpoint die **afbeelding uploadt via POST**, de multipart‑payload leest, en de gegevens aan de OCR‑engine doorgeeft. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### De logica ontleden + +| Stap | Wat gebeurt er | Waarom het belangrijk is | +|------|----------------|--------------------------| +| **ReadFormAsync** | Parseert het binnenkomende *multipart/form-data* verzoek. | Zonder dit kun je geen toegang krijgen tot de geüploade bestanden. | +| **form.Files["image"]** | Haalt het bestand op waarvan de form‑field naam `image` is. | Garandeert een voorspelbaar contract voor aanroepers. | +| **Content‑type check** | Verifieert dat het bestand een afbeelding is (bijv. `image/png`). | Voorkomt dat de OCR‑engine vastloopt op niet‑afbeeldingsdata. | +| **Image.FromStream** | Converteert de ruwe stream naar een `System.Drawing.Image`. | De OCR‑bibliotheek verwacht een `Image`‑object, niet een ruwe byte‑array. | +| **ocr.Recognize(img)** | Roept de OCR‑engine aan om **tekst uit afbeelding te herkennen**. | Dit is de kernstap **OCR op afbeelding uitvoeren**. | +| **Results.Text** | Stuurt de platte‑tekst respons terug. | Een eenvoudig, bruikbaar formaat voor downstream services. | + +## Stap 5: De API draaien + +Start tenslotte de webserver. + +```csharp +app.Run(); +``` + +Wanneer je `dotnet run` uitvoert, zal de API luisteren op `http://localhost:5000` (of een poort naar keuze). Je kunt het testen met `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Verwachte output:** De console zal de herkende tekens afdrukken, bijv.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Als de afbeelding onscherp is of de taal niet wordt ondersteund, zal de OCR‑engine een lege string of een foutmelding teruggeven—handel deze gevallen af in productcode. + +## Randgevallen & Best practices + +### 1. Grote bestanden + +De standaardlimiet voor de request‑body is 30 MB. Voor grotere scans moet je mogelijk aanpassen: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynchrone OCR + +Sommige OCR‑bibliotheken bieden async‑methoden (`RecognizeAsync`). Als die van jou dat doet, vervang `ocr.Recognize(img)` door `await ocr.RecognizeAsync(img)` en markeer de lambda als `async`. + +### 3. Beveiligingsoverwegingen + +- **Valideer de bestandsgrootte** voordat je het in het geheugen laadt. +- **Sanitiseer de bestandsnaam** als je deze ooit naar schijf schrijft. +- **Rate‑limit** de endpoint om denial‑of‑service‑aanvallen te voorkomen. + +### 4. GPU‑versnelling + +Als je de regel `engine.GpuDevice = new GpuDevice(0);` uitcommentarieert en je hardware ondersteunt CUDA of DirectML, zul je een merkbare snelheidsverbetering zien, vooral bij hoge‑resolutie‑afbeeldingen. + +## Volledig werkend voorbeeld + +Hieronder staat de volledige `Program.cs` die je kunt copy‑pasten in een nieuw Minimal API‑project. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Sla op, voer `dotnet run` uit, en je bent klaar om **tekst uit afbeelding** op aanvraag te extraheren. + +## Conclusie + +We hebben een **complete, end‑to‑end oplossing** doorlopen voor het extraheren van tekst uit afbeelding met ASP.NET Core Minimal API. Beginnend met het opzetten van het project, hebben we **een singleton OCR‑engine geregistreerd**, een endpoint gebouwd dat **afbeelding uploadt via POST**, **multipart‑form‑data leest**, en uiteindelijk **OCR op afbeelding uitvoert** om schone platte‑tekst terug te geven. + +Vanaf hier kun je: + +- JSON‑wrappers toevoegen voor rijkere responsen. +- Een database aansluiten om de geëxtraheerde tekst op te slaan. +- Ondersteuning uitbreiden naar meerdere talen (`OcrLanguage.Spanish`, enz.). + +Het patroon schaalt goed—zet simpelweg dezelfde endpoint in een grotere microservice of exposeer het achter een API‑gateway. + +Heb je vragen over het verwerken van PDF’s, batchverwerking, of GPU‑afstemming? Laat een reactie achter, en happy coding! + +## Gerelateerde tutorials + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/dutch/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..92cc5bf8b --- /dev/null +++ b/ocr/dutch/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-05-25 +description: Tekst extraheren uit afbeelding met C# en Aspose OCR. Leer hoe je jpg + naar tekst converteert, afbeelding laadt voor OCR, en snel betrouwbare resultaten + krijgt. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: nl +og_description: Tekst uit een afbeelding halen met C#. Deze gids laat zien hoe je + jpg naar tekst converteert, een afbeelding laadt voor OCR en meertalige inhoud verwerkt. +og_title: Tekst uit afbeelding extraheren in C# – Aspose OCR‑tutorial +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Tekst uit afbeelding extraheren in C# – Complete Aspose OCR-gids +url: /nl/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tekst uit afbeelding extraheren in C# – Complete Aspose OCR-gids + +Heb je je ooit afgevraagd hoe je **extract text from image** kunt doen met eenvoudige C# code? Je bent niet de enige. Of je nu bonnen digitaliseert, verkeersborden scant, of gewoon nieuwsgierig bent naar OCR, de mogelijkheid om tekens uit een afbeelding te halen is een handige vaardigheid. In deze tutorial lopen we een volledig, uitvoerbaar voorbeeld door dat precies laat zien hoe je **extract text from image** met Aspose.OCR, en we behandelen ook hoe je **convert jpg to text**, **load image for OCR**, en beantwoorden we de klassieke vraag “**how to ocr image**” een en al. + +Aan het einde van deze gids heb je een zelfstandige console‑app die een JPEG‑bestand leest, Oekraïens (of een andere ondersteunde taal) herkent, en het resultaat naar de console print. Geen vage verwijzingen, geen ontbrekende onderdelen—gewoon een complete oplossing die je kunt kopiëren‑plakken en uitvoeren. + +--- + +## Wat je zult leren + +* Hoe je het Aspose.OCR NuGet‑pakket installeert. +* De exacte code die nodig is om **load image for OCR** in C# te gebruiken. +* Hoe je de taal instelt en daadwerkelijk **extract text from image**. +* Trucs voor **convert jpg to text** efficiënt. +* Veelvoorkomende valkuilen en hoe je ze vermijdt. + +Als je al een .NET‑ontwikkelomgeving hebt opgezet, ben je klaar om te beginnen. Anders zorgt de sectie met vereisten hieronder ervoor dat je up‑to‑date bent. + +--- + +## Vereisten + +| Requirement | Why it matters | +|-------------|----------------| +| .NET 6.0 SDK (or newer) | Biedt de runtime voor de console‑app. | +| Visual Studio 2022 of VS Code | Maakt bewerken en debuggen gemakkelijker. | +| Internetverbinding (eerste uitvoering) | NuGet moet Aspose.OCR downloaden. | +| Een JPEG‑afbeelding die je wilt verwerken (bijv. `ukrainian_sign.jpg`) | Het bronbestand voor de OCR‑engine. | + +> **Pro tip:** Als je op Linux of macOS werkt, werkt dezelfde code met de .NET‑CLI (`dotnet new console`), dus voel je vrij om de zware IDE over te slaan. + +--- + +## Stap 1 – Installeer Aspose.OCR via NuGet + +Open je terminal (of Package Manager Console) en voer uit: + +```bash +dotnet add package Aspose.OCR +``` + +Die ene regel haalt de nieuwste Aspose.OCR‑binaries en alle transitieve afhankelijkheden op. Handmatig DLL‑beheer is niet nodig. + +--- + +## Stap 2 – Maak de OCR‑engine (Het hart van extractie) + +Nu de bibliotheek aanwezig is, kunnen we een instantie van `OcrEngine` maken. Dit object is verantwoordelijk voor **extracting text from image** gegevens. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Waarom dit belangrijk is:** De engine omvat de OCR‑algoritmen, taalmode­len en configuratie‑opties. Eenmalig instantieren en hergebruiken voor meerdere afbeeldingen is zowel geheugen‑efficiënt als snel. + +--- + +## Stap 3 – Laad afbeelding voor OCR (en stel de taal in) + +De volgende stap is de engine te vertellen welke afbeelding gelezen moet worden. Hier komt de term **load image for OCR** van pas. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Randgeval:** Als het bestand niet bestaat, gooit `Image.FromFile` een `FileNotFoundException`. Omring de aanroep met een try‑catch‑blok voor productiecodel. + +--- + +## Stap 4 – Voer OCR uit en extraheren tekst + +Met de afbeelding geladen, kan de engine nu **extract text from image**. De `Recognize`‑methode doet het zware werk. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Als alles goed gaat, zal `recognizedText` de platte‑tekst representatie bevatten van alles wat de OCR‑engine kon lezen. + +--- + +## Stap 5 – Converteer JPG naar tekst (alles samenvoegen) + +De code die we tot nu toe hebben gebouwd **convert jpg to text** al, maar laten we het in een nette methode plaatsen die je herhaaldelijk kunt aanroepen. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Nu kun je simpelweg doen: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Verwachte output** (afgekapt voor beknoptheid): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Als de afbeelding Engelse tekst bevat, wijzig `OcrLanguage.English` en je zult de overeenkomstige output zien. + +--- + +## Stap 6 – Veelvoorkomende “How to OCR Image” vragen behandelen + +### 6.1 Kan ik een PNG of BMP OCR‑en? + +Absoluut. De `Image.FromFile`‑methode ondersteunt alle formaten die System.Drawing herkent, dus verwijs gewoon naar een `.png`‑ of `.bmp`‑bestand en de rest van de code blijft identiek. + +### 6.2 Wat als de afbeelding een lage resolutie heeft? + +De OCR‑nauwkeurigheid daalt drastisch onder 300 dpi. Een snelle oplossing is de afbeelding te vergroten met `Graphics` voordat je deze aan de engine voedt: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Heb ik een licentie nodig voor Aspose.OCR? + +Aspose biedt een gratis proefversie met een watermerk. Voor productiegebruik koop je een licentie en voeg je toe: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Volledig werkend voorbeeld + +Hieronder staat een complete, kant‑klaar console‑applicatie die **how to OCR image**, **load image for OCR**, en **convert jpg to text** in één net pakket demonstreert. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Hoe je het uitvoert** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Je zou de geëxtraheerde tekst in de console moeten zien verschijnen, wat bevestigt dat je succesvol **extract text from image** hebt uitgevoerd met C#. + +--- + +## Veelvoorkomende valkuilen & pro‑tips + +| Probleem | Waarom het gebeurt | Oplossing | +|----------|--------------------|-----------| +| Lege output | Afbeelding te donker of laag contrast. | Voorverwerken met `Bitmap` om de helderheid te verhogen. | +| Verkeerde taal | `Language`‑eigenschap staat op standaard Engels. | Stel expliciet `ocrEngine.Language = OcrLanguage.Ukrainian;` in (of je gewenste taal). | +| Out‑of‑memory‑fout | Zeer grote afbeeldingen geladen zonder vrijgave. | Omring `Image.FromFile` met een `using`‑blok (zoals getoond). | +| Licentie‑watermerk | Uitvoeren met een proefversie zonder licentie. | Pas een aangeschafte licentie toe vroeg in `Main`. | + +--- + +## Conclusie + +We hebben zojuist alles behandeld wat je nodig hebt om **extract text from image** in C# te doen — van het installeren van Aspose.OCR, **loading image for OCR**, tot **convert jpg to text** en het omgaan met meertalige scenario's. Het volledige voorbeeldprogramma verbindt alle onderdelen, waardoor je een betrouwbare basis krijgt voor elk OCR‑gerelateerd project. + +Vervolgens kun je verkennen: + +* **How to OCR image** streams in plaats van bestanden (gebruik `MemoryStream`). +* Toevoegen van **c# image to text** post‑processing zoals spell‑checking. +* Integreren van de OCR‑stap in een grotere pipeline (bijv. resultaten opslaan in een database). + +Voel je vrij om te experimenteren met verschillende talen, afbeeldingsformaten en voorverwerkingstrucs. OCR is net zo veel een kunst als een wetenschap, en hoe meer je speelt, hoe beter de resultaten. + +Veel plezier met coderen, en moge je afbeeldingen altijd leesbaar zijn! + +## Gerelateerde tutorials + +- [Afbeeldingstekst extraheren C# met taalselectie met Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Tekst uit afbeelding extraheren – OCR‑optimalisatie met Aspose.OCR voor .NET](/ocr/english/net/ocr-optimization/) +- [Hoe tekst uit afbeelding extraheren door rechthoeken voor te bereiden in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/dutch/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..3410bc308 --- /dev/null +++ b/ocr/dutch/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: Hoe OCR in C# te gebruiken om tekst uit afbeeldingsbestanden te extraheren. + Leer Chinese tekens te herkennen uit een JPG met Aspose.OCR in een paar eenvoudige + stappen. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: nl +og_description: Hoe OCR in C# te gebruiken om tekst uit afbeeldingsbestanden te extraheren. + Deze gids laat zien hoe je Chinese tekens uit een JPG kunt herkennen met Aspose.OCR. +og_title: Hoe OCR te gebruiken in C# – Herken Chinese tekst uit JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Hoe OCR in C# te gebruiken – Chinese tekst herkennen uit JPG +url: /nl/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hoe OCR te gebruiken in C# – Chinese tekst herkennen vanuit JPG + +Heb je je ooit afgevraagd **hoe je OCR kunt gebruiken** om woorden uit een foto die je met je telefoon hebt gemaakt te halen? Je bent niet de enige. In veel real‑world projecten—denk aan bonnenlezers, vertaalapps of geautomatiseerde gegevensinvoer—heb je **tekst uit afbeelding** bestanden snel en betrouwbaar nodig. + +In deze tutorial lopen we een volledig, uitvoerbaar voorbeeld door dat **tekst uit JPG** bestanden herkent en zelfs het lastige geval van **Chinese tekens herkennen** aanpakt met het **OCR Chinese Simplified** taalpakket. Aan het einde heb je een zelfstandige console‑app die de gedetecteerde string naar de console print, zonder extra handmatige downloads. + +> **Korte tip:** De code werkt met Aspose.OCR ≥ 23.7, dat automatisch taalbronnen downloadt bij eerste gebruik. Als je een oudere versie gebruikt, moet je de taal handmatig toevoegen. + +## Voorvereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +- .NET 6.0 SDK of later (het voorbeeld richt zich op .NET 6, maar .NET 5 werkt ook) +- Een recente versie van Visual Studio 2022 of VS Code met de C#‑extensie +- Een internetverbinding voor de eerste taal‑download +- Een JPG‑afbeelding die Vereenvoudigd Chinees bevat (we noemen deze `chinese_sign.jpg`) + +Dat is alles—geen zware OCR‑engines, geen native DLL‑handelingen. Alleen een paar NuGet‑commando’s en een paar regels code. + +## Stap 1: Installeer Aspose.OCR via NuGet + +Allereerst hebben we de OCR‑bibliotheek nodig. Open een terminal in je projectmap en voer uit: + +```bash +dotnet add package Aspose.OCR +``` + +Of, als je de Visual Studio‑UI verkiest, klik met de rechtermuisknop op **Dependencies → Manage NuGet Packages**, zoek naar “Aspose.OCR” en klik op **Install**. + +> **Pro tip:** Houd je pakketten up‑to‑date. Nieuwe taalpakketten en prestatie‑verbeteringen komen bij elke kleine release. + +## Stap 2: Maak een nieuw console‑project (als je dat nog niet hebt) + +Als je vanaf nul begint, maak dan een nieuwe console‑app: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Nu heb je een `Program.cs`‑bestand klaar voor de OCR‑code. + +## Stap 3: Schrijf de OCR‑code – Vereenvoudigd Chinees herkennen uit een JPG + +Open `Program.cs` en vervang de inhoud door het volgende. Elke regel is geannoteerd zodat je kunt zien *waarom* we elke stap doen, niet alleen *wat* we doen. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Wat gebeurt er achter de schermen? + +- **`OcrEngine.Language`** vertelt Aspose welke woordenlijst te gebruiken. Door `ChineseSimplified` te kiezen, instrueren we de engine om het Vereenvoudigd Chinees‑taalpakket te zoeken. +- **Eerste‑keer download**: Wanneer `Recognize` wordt uitgevoerd, haalt de SDK het ≈6 MB‑taalbestand op van Aspose’s CDN, slaat het lokaal op en gaat dan verder met de OCR. Volgende oproepen zijn direct. +- **`Image.FromFile`** werkt met elk rasterformaat dat .NET kan decoderen—JPG, PNG, BMP—zodat je **tekst uit afbeelding** bestanden van vele types kunt **extraheren**, niet alleen JPG. + +## Stap 4: Voer de applicatie uit en controleer de output + +Bouw en voer uit: + +```bash +dotnet run +``` + +Je zou iets moeten zien als: + +``` +=== Recognized Text === +欢迎光临 +``` + +Als de console onzin of een lege string print, controleer dan het volgende: + +1. De afbeelding bevat daadwerkelijk duidelijke, hoog‑contrast Chinese tekens. +2. Het bestandspad is correct (geen vreemde spaties of ontbrekende extensies). +3. Je machine kan `https://download.aspose.com` bereiken voor het taalpakket. + +## Stap 5: Edge‑cases en veelvoorkomende valkuilen behandelen + +### 5.1 Omgaan met afbeeldingen van lage kwaliteit + +OCR‑nauwkeurigheid daalt wanneer de bronafbeelding wazig, ruisig of slecht belicht is. Een snelle oplossing is de afbeelding voor te bewerken: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Uitvoeren in een headless omgeving + +Als je naar een Linux‑container zonder GUI deployt, zorg dan dat de `libgdiplus`‑bibliotheek (vereist voor `System.Drawing`) geïnstalleerd is: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Het taalpakket handmatig cachen + +Je kunt het taalbestand één keer downloaden en Aspose ernaar laten wijzen via de `License`‑API, waardoor de eenmalige netwerk‑call wegvalt. Handig voor offline scenario’s. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Volledig werkend voorbeeld (alles‑in‑één) + +Hieronder staat het *complete* programma dat je kunt kopiëren‑plakken in `Program.cs`. Geen verborgen stukjes, geen externe scripts. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Verwachte output + +Bevat de JPG de zin “欢迎光临”, dan print de console: + +``` +=== Recognized Text === +欢迎光临 +``` + +Voel je vrij om de afbeelding te vervangen door een andere Vereenvoudigd Chinees‑bord, straatnaam of productlabel—de engine doet zijn best. + +## Conclusie + +We hebben net behandeld **hoe je OCR kunt gebruiken** in C# om **tekst uit afbeelding** bestanden te **extraheren**, specifiek gericht op de uitdaging van **Chinese tekens herkennen** in een **JPG**. Door gebruik te maken van Aspose.OCR’s on‑the‑fly taal‑download kun je je deployment licht houden terwijl je toch **OCR Chinese Simplified** direct ondersteunt. + +Wat nu? Probeer deze ideeën: + +- **Batchverwerking**: Loop over een map met afbeeldingen en schrijf elk resultaat naar een CSV. +- **Combineren met vertaal‑API’s**: Stuur de herkende string naar Azure Translator voor realtime meertalige apps. +- **Andere talen verkennen**: Vervang `OcrLanguage.ChineseSimplified` door `Japanese` of `Arabic` en zie hoe dezelfde code zich aanpast. + +Heb je vragen over prestatie‑optimalisatie, licenties of het integreren van OCR in een webservice? Laat een reactie achter—happy coding! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + + +## Gerelateerde tutorials + +- [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/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/dutch/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/dutch/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..bb2e75e88 --- /dev/null +++ b/ocr/dutch/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Leer hoe je Russische tekst OCR‑t in C# en tekst uit een afbeelding haalt + met Aspose OCR. Stapsgewijze code om snel een afbeelding naar tekst te converteren + in C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: nl +og_description: OCR van Russische tekst in C# eenvoudig gemaakt. Leer hoe je tekst + uit een afbeelding haalt, afbeelding naar tekst converteert in C# en een afbeelding + laadt voor OCR met Aspose OCR. +og_title: OCR van Russische tekst in C# – Complete Aspose OCR-gids +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR van Russische tekst in C# – Complete gids met Aspose OCR +url: /nl/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR van Russische tekst in C# – Complete gids met Aspose OCR + +Heb je ooit Russische tekst moeten OCR'en in C#, maar wist je niet welke bibliotheek je kon vertrouwen? Je bent niet de enige. Schone, leesbare tekens uit een Cyrillisch beeld krijgen kan aanvoelen als het ontcijferen van geheime berichten—vooral als je het juiste taalmodel niet hebt ingesteld. + +In deze tutorial lopen we een praktische voorbeeld stap voor stap door dat laat zien hoe je **tekst uit afbeelding** kunt extraheren, *image to text C#* stijl kunt omzetten, en de nuances van Russische taalherkenning met Aspose OCR kunt behandelen. Aan het einde heb je een kant‑klaar console‑applicatie die een afbeelding laadt voor OCR, de herkende string afdrukt, en je een solide basis geeft voor meer geavanceerde scenario's. + +## Wat je zult leren + +- Hoe je **Aspose OCR C#** installeert en configureert voor ondersteuning van de Russische taal. +- De exacte stappen om **afbeelding te laden voor OCR** en de engine aan te roepen. +- Tips voor het omgaan met veelvoorkomende valkuilen zoals ontbrekende taalmiddelen of onscherpe scans. +- Manieren om de oplossing uit te breiden, zoals batchverwerking van meerdere bestanden of het aanpassen van vertrouwensdrempels. + +Ervaring met Aspose is niet vereist; een basiskennis van C# en .NET is voldoende om aan de slag te gaan. + +## Vereisten + +Voordat we beginnen, zorg dat je het volgende hebt: + +1. **.NET 6.0** (of later) SDK geïnstalleerd – de code werkt zowel op .NET Core als .NET Framework. +2. **Visual Studio 2022** (of een IDE naar keuze). +3. Een **Aspose.OCR for .NET** NuGet‑pakket – je kunt een gratis trial‑sleutel van de Aspose‑website halen. +4. Een **Russisch taalmodel** bestand (`rus.traineddata`) – download het van de Aspose‑resourcepagina en plaats het in een map die je later zult refereren. +5. Een voorbeeldafbeelding (`russian_doc.png`) met duidelijke Cyrillische tekst. + +Heb je alles? Geweldig—laten we beginnen. + +## Stap 1: Het project opzetten en Aspose OCR installeren + +Maak eerst een nieuw console‑project aan: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Voeg nu het Aspose OCR‑pakket toe: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Als je een trial‑licentie gebruikt, houd het `Aspose.Total.lic`‑bestand bij de hand; je laadt het in de code om watermerken te vermijden. + +Zodra het pakket geïnstalleerd is, open `Program.cs`. Je ziet de standaard `Main`‑methode—vervang de inhoud door het skelet dat we gaan bouwen. + +## Stap 2: Het OCR‑engine configureren voor de Russische taal + +Het hart van de operatie is het `OcrEngine`‑object. We moeten het twee dingen vertellen: welke taal herkend moet worden en waar de taalmodelbestanden te vinden zijn. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Waarom dit belangrijk is:** Als je `Language = OcrLanguage.Russian` overslaat, stelt de engine standaard Engels in, en zullen Cyrillische tekens verschijnen als onleesbare symbolen. De `ResourceFolder` wijst naar de map die het `rus.traineddata`‑bestand bevat; zonder dit geeft Aspose een *resource not found*‑exception. + +## Stap 3: De afbeelding laden voor OCR + +Nu moeten we **afbeelding laden voor OCR**. Aspose OCR werkt met `System.Drawing.Image`, dus je kunt elk ondersteund formaat (PNG, JPEG, BMP, enz.) gebruiken. Zorg dat het bestandspad correct is; relatieve paden zijn prima als je de afbeelding naast het uitvoerbare bestand houdt. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Randgeval:** Als de afbeelding groot is (meer dan 5 MB) wil je deze eerst verkleinen. De OCR‑nauwkeurigheid daalt wanneer de DPI te laag is, maar enorme bestanden kunnen geheugenbelasting veroorzaken. Een snelle verkleining kan met `Graphics` worden gedaan indien nodig. + +## Stap 4: De tekst herkennen – Van afbeelding naar tekst C#‑stijl + +Met de engine geconfigureerd en de afbeelding geladen, is de daadwerkelijke herkenning één enkele aanroep: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Wanneer je het programma uitvoert (`dotnet run`), zie je iets als: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Als de output er onleesbaar uitziet, controleer dan: + +- Het `rus.traineddata`‑bestand staat aanwezig in `ResourceFolder`. +- De afbeelding is niet te onscherp; overweeg een eenvoudige binarisatiefilter toe te passen vóór OCR. +- De taalinstelling is daadwerkelijk `OcrLanguage.Russian`. + +## Stap 5: Fijn afstellen en veelvoorkomende valkuilen + +### Aanpassen van de vertrouwensdrempel + +Aspose OCR geeft intern een vertrouwenswaarde per teken terug. Hoewel de API dit niet direct blootstelt, kun je **gedetailleerde output** inschakelen om te zien welke woorden een lage vertrouwenswaarde hadden: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Als je vaak verkeerde herkenningen ziet, probeer dan: + +- **Pre‑processing**: Converteer de afbeelding naar grijstinten, verhoog het contrast, of pas een medianfilter toe. +- **DPI‑instellingen**: Zorg dat de afbeelding minimaal 300 DPI is voor Cyrillische scripts. + +### Batchverwerking van meerdere afbeeldingen + +Als je **tekst uit afbeelding** bestanden in bulk moet extraheren, wikkel dan de herkenningslogica in een lus: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Nu krijgt elke PNG zijn eigen `.txt`‑tegenhanger—handig voor documentarchivering. + +### Unicode‑output verwerken + +Cyrillische tekens zijn Unicode, zorg dus dat de console‑codering ze kan weergeven: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Plaats deze regel direct na de start van de `Main`‑methode. Zonder deze zie je mogelijk vraagtekens (`?`) in plaats van Russische letters. + +## Volledig werkend voorbeeld + +Hieronder staat de volledige, kant‑klaar code. Kopieer‑en plak het in `Program.cs`, pas de paden aan, en je bent klaar om te gaan. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Verwachte output** (ervan uitgaande dat de voorbeeldafbeelding “Пример текста на русском языке.” zegt): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Als je iets anders ziet, bekijk dan opnieuw de foutoplossingstips in Stap 5. + +## Conclusie + +Je hebt nu een solide, end‑to‑end voorbeeld van hoe je **Russische tekst OCR't** in C# met Aspose OCR. Van het installeren van de bibliotheek, het configureren van het Russische taalmodel, tot het laden van een afbeelding en deze omzetten naar schone Unicode‑tekst, elk onderdeel is behandeld. + +Onthoud dat de sleutel tot betrouwbare OCR goed bronmateriaal is: duidelijke lettertypen, voldoende DPI, en de juiste taalmiddelen. Zodra je de basis onder de knie hebt, kun je uitbreiden naar batchverwerking, integratie met cloudopslag, of zelfs combineren met AI‑post‑processing voor spell‑checking. + +### Wat nu? + +- Verken geavanceerde opties van **aspose ocr c#** zoals lay-outanalyse of PDF‑output. +- Combineer dit met **tekst uit afbeelding** workflows in Azure Functions voor serverloze verwerking. +- Probeer verschillende talen—schakel simpelweg `OcrLanguage.Russian` over naar `OcrLanguage.English` of een andere ondersteunde code. + +Heb je vragen of een lastig beeld dat niet meewerkt? Laat een reactie achter hieronder, en happy coding! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russisch tekst voorbeeld"} + +## Gerelateerde tutorials + +- [Afbeeldingstekst extraheren in C# met taalkeuze via Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [tekstafbeelding herkennen met Aspose OCR voor meerdere talen](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Tekst uit afbeelding extraheren met Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/dutch/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..9e09ed93a --- /dev/null +++ b/ocr/dutch/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-25 +description: herken tekst van een afbeelding met Aspose OCR in C#. Leer hoe je een + afbeelding laadt voor OCR, de OCR-taal instelt, een OCR-engine maakt en tekst uit + een TIFF extraheert. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: nl +og_description: herken tekst van afbeelding met Aspose OCR in C#. Deze tutorial laat + zien hoe je een OCR‑engine maakt, een afbeelding laadt voor OCR, de OCR‑taal instelt + en tekst uit een TIFF extraheert. +og_title: herken tekst uit afbeelding met Aspose OCR – Complete C#-gids +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Tekst herkennen van afbeelding met Aspose OCR – Complete C#-gids +url: /nl/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tekst herkennen uit afbeelding met Aspose OCR – Complete C# Gids + +Heb je ooit **tekst herkennen uit afbeelding** moeten doen, maar wist je niet welke bibliotheek zowel snelheid als nauwkeurigheid biedt? Je bent niet de enige. In veel factuur‑verwerkings- of archiveringsprojecten is het grootste pijnpunt het verkrijgen van schone, doorzoekbare tekst uit TIFF‑bestanden zonder een aangepaste parser te schrijven. + +Het punt is: Aspose OCR voor .NET maakt die hele pijplijn een eitje. In deze gids lopen we alles door wat je nodig hebt—het installeren van het pakket, **een OCR‑engine maken**, een TIFF laden, de OCR‑taal instellen, en uiteindelijk **tekst uit TIFF extraheren**. Aan het einde heb je een kant‑klaar console‑applicatie die **tekst herkennen uit afbeelding**‑bestanden in een handomdraai kan. + +## Vereisten + +- .NET 6.0 of later (de code werkt ook met .NET Core en .NET Framework) +- Visual Studio 2022 (of een IDE naar keuze) +- Aspose.OCR NuGet‑pakket (GPU‑ondersteuning vereist de `Aspose.OCR.Gpu` add‑on) +- Een GPU met CUDA‑ondersteuning als je extra snelheid wilt (optioneel maar aanbevolen) + +> **Pro tip:** Als je geen GPU hebt, laat dan gewoon de `GpuDevice`‑regel weg en de engine schakelt automatisch terug naar de CPU. + +## Stap 1: Installeer Aspose OCR en Maak OCR‑Engine + +Eerst, voeg de benodigde pakketten toe via NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Nu kunnen we **een OCR‑engine maken**. Dit object is het hart van het proces; het bevat configuratie zoals het apparaat waarop het draait en geheugenlimieten. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Waarom dit belangrijk is:** Door de engine aan een GPU te binden, verkort je de tijd die nodig is om **tekst te herkennen uit afbeelding** drastisch, vooral bij grote batches van hoge‑resolutie TIFF‑bestanden. + +## Stap 2: Afbeelding Laden voor OCR + +Vervolgens moeten we **een afbeelding laden voor OCR**. Aspose.OCR werkt met `System.Drawing.Image`, dus elk formaat dat door GDI+ wordt ondersteund (inclusief multi‑page TIFF) is geschikt. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Als je met een multi‑page TIFF werkt, kun je door de pagina's loopen met `image.SelectActiveFrame`, maar voor de meeste scenario's is één enkele aanroep voldoende. + +## Stap 3: OCR‑Taal Instellen + +De engine weet niet vanzelf welke taal je scant. **Stel de OCR‑taal in** voordat je de herkenner uitvoert; anders krijg je veel onleesbare output. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Wist je dat?** Het wisselen van talen tijdens runtime is goedkoop—je kunt zelfs een document met meerdere talen verwerken door deze eigenschap tussen pagina's te wijzigen. + +## Stap 4: Voer de Herkenning Uit – Tekst Herkennen uit Afbeelding + +Nu het leuke gedeelte: daadwerkelijk **tekst herkennen uit afbeelding**. De `Recognize`‑methode retourneert een eenvoudige string met alle gedetecteerde tekens. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Als je vertrouwensscores of begrenzingskaders nodig hebt, kun je de overload gebruiken die een `OcrResult`‑object retourneert, maar voor de meeste extractietaken is de eenvoudige string voldoende. + +## Stap 5: Tekst Extraheren uit TIFF (en multi‑page bestanden afhandelen) + +Wanneer de bron een TIFF met meerdere pagina's is, wil je stappen 2‑4 voor elk frame herhalen. Hier is een snelle lus die **tekst uit TIFF** pagina voor pagina **extraheert**: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +De bovenstaande code print de geëxtraheerde tekst voor elke pagina, waardoor het eenvoudig is om de resultaten naar een database of een zoekindex te sturen. + +## Stap 6: Toon of Sla de Geëxtraheerde Tekst Op + +Ten slotte, laten we **de geëxtraheerde tekst tonen** en optioneel naar een bestand schrijven voor latere verwerking. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Het uitvoeren van het programma moet de herkende tekens weergeven en `extracted_text.txt` naast je bron‑TIFF aanmaken. + +--- + +## Veelgestelde Vragen & Randgevallen + +- **Wat als mijn GPU niet wordt gedetecteerd?** + Verwijder de `GpuDevice`‑regel; de engine schakelt automatisch over naar CPU‑modus. De prestaties zullen trager zijn, maar de resultaten blijven nauwkeurig. + +- **Kan ik PNG‑ of JPEG‑bestanden verwerken?** + Zeker—`Image.FromFile` werkt met elk formaat dat door System.Drawing wordt ondersteund, dus je kunt **een afbeelding laden voor OCR** ongeacht de extensie. + +- **Hoe ga ik om met scans met lage resolutie?** + Verhoog `ocrEngine.PreprocessOptions.Dpi` vóór het aanroepen van `Recognize`. Een hogere DPI geeft de engine meer pixels om mee te werken, waardoor de nauwkeurigheid verbetert. + +- **Is er een limiet aan de grootte van de TIFF?** + De eigenschap `GpuMemoryLimit` beperkt het GPU‑gebruik. Als je de limiet bereikt, schakelt de engine over naar CPU voor de resterende pagina's. + +## Conclusie + +Je hebt nu een volledige, productie‑klare code‑fragment dat **tekst herkent uit afbeelding**‑bestanden met Aspose OCR in C#. De tutorial behandelde hoe je **een OCR‑engine maakt**, **een afbeelding laadt voor OCR**, **de OCR‑taal instelt**, en **tekst uit TIFF extraheert**—alles terwijl je GPU‑versnelling benut voor snelheid. + +Van hieruit kun je: + +- Experimenteer met verschillende talen (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, enz.). +- Integreer de output in een doorzoekbare ElasticSearch‑index. +- Voeg post‑processing toe (spellingcontrole, regex‑opschoning) om de gegevenskwaliteit te verbeteren. + +Probeer het op je eigen factuurbatch, pas de geheugenlimieten aan, en zie de OCR‑prestaties stijgen. Veel programmeerplezier! + +## Gerelateerde Tutorials + +- [Afbeeldingstekst extraheren C# met taalkeuze met Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Hoe Tekst uit Afbeelding te Extraheren door Rechthoeken Voor te Bereiden in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Tekst uit Afbeelding Extraheren – Regel Herkennen met Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..3bb633d14 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. +### [Create OCR Engine in C# – Complete Guide](./create-ocr-engine-in-c-complete-guide/) +Learn how to build and configure a custom OCR engine in C# using Aspose.OCR, covering setup, language selection, and performance tuning. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/english/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..eb70496c9 --- /dev/null +++ b/ocr/english/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-05-25 +description: Create OCR engine in C# and learn how to check its evaluation mode and + licensing status in a few lines of code. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: en +og_description: Create OCR engine in C# and instantly see how to detect evaluation + mode and display licensing status. +og_title: Create OCR Engine in C# – Step‑by‑Step Guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Create OCR Engine in C# – Complete Guide +url: /net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Create OCR Engine in C# – Complete Guide + +Ever wondered how to **create OCR engine** objects in C# without hunting through endless docs? You're not the only one. Many developers hit a wall when they need to spin up an OCR engine, verify whether it's running in trial mode, and surface the licensing status to users. + +In this tutorial we'll walk through a concise, end‑to‑end example that **creates an OCR engine**, checks its **OCR engine evaluation mode**, and prints a friendly message about the licensing state. By the end you'll have a ready‑to‑run console app and a clear mental model for handling OCR licensing in your own projects. + +## What You'll Learn + +- How to instantiate an `OcrEngine` (the core of any OCR workflow). +- Why detecting **evaluation mode** matters for compliance and user experience. +- The best way to **check OCR license** status and react to unexpected states. +- Common pitfalls—null references, exception handling, and version mismatches. + +No external tools required beyond the OCR SDK you already have installed. If you’re comfortable with basic C# syntax, you’re good to go. + +## Prerequisites + +- .NET 6.0 or later (the code compiles with .NET Core and .NET Framework). +- An OCR SDK that exposes an `OcrEngine` class with an `IsEvaluation` property (for example, the hypothetical `MyOcrSdk`). +- A text editor or IDE (Visual Studio, VS Code, Rider—pick your favorite). + +That’s it. Let’s dive in. + +## Step 1: Set Up a New Console Project + +First, spin up a fresh console app so you can run the code in isolation. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Open the generated `Program.cs`. We'll replace its contents with a complete example that **creates OCR engine** instances and handles licensing. + +## Step 2: Import the OCR SDK Namespace + +Assuming the SDK is referenced via NuGet (`MyOcrSdk` is a placeholder), add the using directive at the top of the file. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +If you haven’t added the package yet, run: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Keep your SDK version up‑to‑date; newer releases often improve evaluation‑mode detection. + +## Step 3: Create the OCR Engine Instance + +Now we finally **create OCR engine** objects. This is the heart of any OCR workflow—think of it as the brain that will later read images. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Why is this step crucial? The `OcrEngine` encapsulates all configuration, language packs, and licensing data. Without it, you cannot process images or query the evaluation flag. + +> **Side note:** Some SDKs let you pass a configuration object to the constructor (e.g., language, DPI). If you need custom settings, modify the line accordingly. + +## Step 4: Determine the OCR Engine Evaluation Mode + +Most OCR vendors ship a trial version that runs in **evaluation mode** until a valid license key is supplied. Knowing whether you’re in trial mode lets you display appropriate UI cues or restrict certain features. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +The `IsEvaluation` property returns `true` when the engine is unlicensed or using a time‑limited trial. It’s a quick, reliable way to guard premium features. + +### What If the Property Is Missing? + +Older SDK versions might expose a method like `GetLicenseInfo()` instead. In that case, you’d inspect the returned object for a `IsTrial` flag. Always consult the SDK changelog when upgrading. + +## Step 5: Display the Current Licensing Status + +Finally, let’s show the user whether the engine is licensed or still in trial. A simple console write‑line does the trick, but you can adapt it for GUI apps. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +The ternary operator keeps the code tidy, and the messages are clear enough for end‑users or developers reading logs. + +## Full Working Example + +Putting it all together, here’s a self‑contained program you can copy‑paste into `Program.cs` and run with `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Expected Output + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +If the SDK throws an exception (e.g., missing native DLL), the catch block will print a helpful error message instead of crashing the whole app. + +## Handling Edge Cases and Common Pitfalls + +### 1. Null Engine Instances + +Although the constructor usually returns a valid object, some SDKs may return `null` if required native dependencies are missing. Guard against it: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. License Expiration While Running + +A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` if your app stays alive for a long time. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Different Property Names Across Versions + +Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. When you upgrade, search the SDK release notes for breaking changes. + +### 4. Multi‑Threaded Scenarios + +If you spin up several OCR workers, instantiate **one OCR engine per thread** unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine can lead to race conditions and false licensing reads. + +## Pro Tips for Production Use + +- **Cache the licensing status** after the first check to avoid unnecessary property calls. +- **Log the license key** (masked) on startup for audit trails—helps support teams diagnose licensing issues. +- **Provide a UI toggle** that tells users they’re in trial mode and offers a “Buy License” button. +- **Automate license renewal** using the SDK’s activation API, if available, to keep the user experience seamless. + +## Conclusion + +We’ve just **created OCR engine** objects in a handful of lines, inspected the **OCR engine evaluation mode**, and printed a clear **OCR licensing status** message. The full example runs out of the box, handles errors gracefully, and highlights the “why” behind each step—so you can adapt it to desktop, web, or service‑side scenarios. + +Next, you might explore: + +- Feeding images into `engine.Recognize` and handling multi‑language support. +- Using **check OCR license** APIs to programmatically activate a purchased key. +- Integrating with UI frameworks (WinForms, WPF, MAUI) to show licensing badges. + +Give those a try, and you’ll have a robust OCR foundation ready for any application. Happy coding! + + +## Related Tutorials + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/ocr-optimization/_index.md b/ocr/english/net/ocr-optimization/_index.md index ff28e4eeb..b9c8f3eeb 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. +### [Preprocess Image for OCR – Complete Aspose C# Guide](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Comprehensive guide to preprocess images for OCR using Aspose in C#, covering filters, deskew, and binarization for optimal results. ## Frequently Asked Questions diff --git a/ocr/english/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/english/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..b1e580942 --- /dev/null +++ b/ocr/english/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: en +og_description: Preprocess image for OCR with Aspose to boost OCR accuracy. Follow + this guide to run OCR on JPEG and extract text using Aspose in C#. +og_title: Preprocess Image for OCR – Aspose C# Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Preprocess Image for OCR – Complete Aspose C# Guide +url: /net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Preprocess Image for OCR – Complete Aspose C# Guide + +Ever wondered how to **preprocess image for OCR** so the text comes out clean every time? You’re not the only one—developers constantly battle noisy scans, low‑contrast JPEGs, and unpredictable lighting. The good news? With a few smart tweaks you can **improve OCR accuracy** dramatically, and Aspose makes it painless. + +In this tutorial we’ll walk through a real‑world example that shows you how to **run OCR on JPEG** images, apply a custom image‑processing pipeline, and finally **extract text using Aspose**. By the end you’ll have a ready‑to‑paste C# snippet that you can drop into any .NET project. + +## What You’ll Learn + +- Why preprocessing matters and which filters give the biggest win. +- How to configure Aspose.OCR’s `ImageProcessingOptions` for deskewing, denoising, binarization, and contrast boosting. +- The exact code needed to **run OCR on JPEG** files and retrieve clean text. +- Tips and pitfalls that keep your OCR pipeline robust in production. + +No prior experience with Aspose is required; just a basic C# background and Visual Studio (or your favorite IDE). Let’s get started. + +![Preprocess image for OCR example](preprocess-ocr.png "Preprocess image for OCR") + +## Step 1: Set Up the Aspose.OCR Engine – Preprocess Image for OCR + +First things first. We need an `OcrEngine` instance and we must tell it which language we expect. In most cases English is the default, but you can swap it out for French, German, etc., by changing the `OcrLanguage` enum. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Why this matters:** The engine is the heart of the operation; without it you can’t apply any of the image filters that actually **preprocess image for OCR**. Think of it as the kitchen where all the ingredients get mixed. + +## Step 2: Build a Custom Image‑Processing Pipeline – Improve OCR Accuracy + +Now comes the juicy part. Aspose lets you chain several filters together. Below we enable four of the most effective ones: + +1. **Deskew** – straightens tilted documents (max 5° by default). +2. **Denoise** – smooths out grainy backgrounds. +3. **Binarize** – converts the image to black‑and‑white using a threshold. +4. **ContrastBoost** – makes faint characters pop. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** If your source images are already crisp, you can dial the `Strength` down or turn a filter off entirely. Over‑processing can sometimes erase faint characters, so experiment with real samples. + +## Step 3: Load the JPEG (or Any Image) and Run OCR – Run OCR on JPEG + +Aspose works with any image format that .NET can read—JPEG, PNG, BMP, you name it. Here’s how you feed a JPEG file into the engine and kick off the recognition process. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Why JPEG?** JPEG compression often introduces artifacts that confuse OCR. Our preprocessing pipeline, especially the denoise and binarize steps, mitigates those issues, letting you **run OCR on JPEG** with confidence. + +## Step 4: Output the Recognized Text – Extract Text Using Aspose + +Finally, we simply write the text to the console, a file, or any downstream service. For demonstration purposes, the console is enough. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +When you run the program, you should see something like: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +If the output looks garbled, go back to **Step 2** and tweak the filter settings. Small adjustments often yield big gains in **improve OCR accuracy**. + +## Common Edge Cases and How to Handle Them + +| Situation | Suggested Adjustment | +|-----------|----------------------| +| **Very dark images** | Increase `ContrastBoost.Level` to 1.5 or higher. | +| **Skew > 5°** | Raise `DeskewOptions.MaxAngle` (e.g., 10.0) or pre‑rotate the image manually. | +| **Colored text on colored background** | Use `BinarizeOptions` with a custom threshold or switch to `AdaptiveBinarizeOptions`. | +| **Large files ( > 5 MB )** | Load the image into a `MemoryStream` first to avoid file‑lock issues. | + +These tweaks keep your pipeline flexible and future‑proof, especially when you need to **extract text using Aspose** from diverse sources. + +## Full Working Example – All Steps in One Place + +Below is the complete, copy‑and‑paste‑ready program. It compiles with .NET 6+ and only requires the `Aspose.OCR` NuGet package. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Save this as `Program.cs`, add the Aspose.OCR package (`dotnet add package Aspose.OCR`), and run `dotnet run`. You’ll see the cleaned‑up text printed to the console. + +## Recap – Why This Approach Works + +- **Preprocess image for OCR**: The pipeline removes the most common sources of error (skew, noise, low contrast). +- **Improve OCR accuracy**: Each filter is tuned to boost the signal‑to‑noise ratio that the engine sees. +- **Run OCR on JPEG**: Even compressed images become legible after deskewing and binarization. +- **Extract text using Aspose**: The `Recognize` method returns a plain string, ready for any downstream logic. + +Together, these steps give you a reliable, production‑grade OCR solution in just a handful of lines. + +## Next Steps and Related Topics + +- **Batch processing** – Loop over a folder of images and write each result to a `.txt` file. +- **Language packs** – Swap `OcrLanguage.English` for `OcrLanguage.Spanish` or add custom dictionaries. +- **PDF extraction** – Combine Aspose.OCR with Aspose.PDF to pull text directly from scanned PDFs. +- **Performance tuning** – Run the engine in parallel using `Parallel.ForEach` for large workloads. + +Feel free to experiment with the filter values, try different image formats, or chain additional Aspose filters like `SharpnessOptions`. The sky’s the limit once you’ve mastered the basics. + +--- + +*Happy coding! If you hit any snags, drop a comment below and we’ll troubleshoot together.* + + +## Related Tutorials + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/text-recognition/_index.md b/ocr/english/net/text-recognition/_index.md index b3bb5f052..6d0b95021 100644 --- a/ocr/english/net/text-recognition/_index.md +++ b/ocr/english/net/text-recognition/_index.md @@ -55,9 +55,24 @@ 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. +### [recognize text from image with Aspose OCR – Complete C# Guide](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Learn how to recognize text from images using Aspose OCR in C#. Follow a complete step-by-step guide for .NET developers. +### [How to Use OCR in C# – Recognize Chinese Text from JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Learn to recognize Chinese text from JPG images using Aspose.OCR in C#. Follow a detailed step-by-step guide for .NET developers. +### [OCR Russian Text in C# – Complete Guide Using Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Learn how to recognize Russian text from images using Aspose OCR in C#. Follow a comprehensive step-by-step guide for .NET developers. +### [Extract Text from Image in C# – Complete Aspose OCR Guide](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Learn to extract text from images using Aspose OCR in C#. Follow a comprehensive step-by-step guide for .NET developers. +### [Extract Text from Image in ASP.NET Core Minimal API – Complete Guide](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Learn how to extract text from images using Aspose OCR in an ASP.NET Core Minimal API. Follow a complete step-by-step guide for .NET developers. +### [c# OCR tutorial: Extract Text from PNG Receipts with Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Learn how to extract text from PNG receipt images using Aspose OCR in C#. Follow a step-by-step guide for .NET developers. +### [Convert TIFF to Text in C# – Complete Batch OCR Guide](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Convert TIFF images to text using Aspose.OCR in C#. Follow a complete batch OCR guide for .NET developers. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/english/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..addaa2cf5 --- /dev/null +++ b/ocr/english/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR tutorial that shows how to load image file c# and recognize png + text from a receipt using Aspose OCR – step‑by‑step guide. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: en +og_description: c# OCR tutorial that walks you through loading an image file c# and + recognizing png text from a receipt using Aspose OCR. +og_title: c# OCR tutorial – Extract Text from PNG Receipts +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' +url: /net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Extract Text from PNG Receipts with Aspose + +Ever needed a **c# OCR tutorial** that actually gets the job done without endless Googling? You're in the right place. In this guide we'll **load image file c#**, **recognize png text**, and **read receipt OCR** results, all while showing you how to **perform OCR image** processing with Aspose OCR. + +We'll start by installing the required NuGet package, walk through each line of code, and finish with a tidy JSON dump you can pipe straight into your next data‑pipeline. No fluff, just a practical, ready‑to‑run solution. + +## What You’ll Learn + +- How to set up Aspose OCR in a .NET 6 (or later) project. +- The exact steps to **load an image file c#** and hand it to the engine. +- How to **recognize png text** from a receipt image and capture the result. +- Ways to **read receipt OCR** output as nicely formatted JSON. +- Tips for **perform OCR image** operations on different file types and handling common pitfalls. + +**Prerequisites** +- Visual Studio 2022 (or any IDE you like). +- .NET 6 SDK or newer. +- A PNG receipt image handy (we’ll call it `receipt.png`). + +If you’ve got those, let’s dive in. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR Tutorial – Setting Up Aspose OCR Engine + +First off, we need the Aspose OCR library. Open your terminal in the solution folder and run: + +```bash +dotnet add package Aspose.OCR +``` + +That single command pulls in everything required, including native binaries for image decoding. Once installed, create a new console project or add the code to an existing one. + +### Why Aspose? + +Aspose OCR supports over 30 languages, works offline, and returns a rich `OcrResult` object—perfect for **perform OCR image** tasks where you need more than just plain text. + +## Load image file c# and Prepare the Receipt + +Now that the library is ready, let’s **load image file c#**. The `System.Drawing.Image` class does the heavy lifting, but you could also use `SkiaSharp` if you prefer a cross‑platform alternative. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** Wrap the `Image` in a `using` statement (as shown) to free native resources promptly—especially important when you **perform OCR image** on many files in a loop. + +## Recognize PNG text with Aspose + +With the image in memory, the engine can now **recognize png text**. Aspose returns an `OcrResult` that contains both the raw string and detailed data about each recognized word. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Why call `RecognizeWithResult` instead of the simpler `Recognize`? The former gives you access to confidence scores, bounding boxes, and line breaks—handy if you later need to **read receipt OCR** for line‑item extraction. + +## Read receipt OCR Result as JSON + +Most downstream systems love JSON, so let’s serialize the `OcrResult`. The `System.Text.Json` serializer handles complex objects gracefully, and we’ll enable indentation for readability. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +The resulting JSON looks something like this (trimmed for brevity): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +You can now pipe `jsonResult` into a database, a message queue, or simply log it for debugging. + +## Perform OCR Image Processing and Display Output + +Finally, output the JSON to the console. In a real‑world app you’d probably write it to a file or send it over HTTP, but the console makes it easy to verify everything worked. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Run the program (`dotnet run`) and you should see the nicely formatted JSON printed. If the receipt image is clear, the text will be spot‑on; if not, consider increasing the image resolution or applying a preprocessing filter (e.g., grayscale, contrast boost) before feeding it to the engine. + +### Handling Common Edge Cases + +| Situation | What to do | +|-----------|------------| +| **Image is blurry** | Pre‑process with `System.Drawing` to sharpen or increase DPI. | +| **Receipt contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Large batch processing** | Reuse a single `OcrEngine` instance; only change the `Image` each iteration. | +| **Memory pressure** | Dispose `Image` objects promptly and consider `await Task.Run` for async pipelines. | + +These tweaks keep your **perform OCR image** workflow robust even when the input isn’t perfect. + +## Wrap‑Up + +Congratulations—you’ve just completed a **c# OCR tutorial** that loads an image, **recognizes png text**, and **reads receipt OCR** output as clean JSON. The core steps (engine setup, image loading, OCR execution, serialization, and display) form a solid foundation you can extend to invoices, passports, or any other scanned document. + +### What’s Next? + +- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform support. +- Dive deeper into `OcrResult.Words` to extract line items, prices, and dates—perfect for expense‑tracking apps. +- Combine this tutorial with Azure Functions or AWS Lambda to build a serverless receipt‑processing API. + +Feel free to tweak the code, throw in more images, or even switch to a different language pack. The world of OCR is full of surprises, and now you have the tools to explore them. + +Happy coding, and may your receipts always be readable! + + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Use OCR - Recognize Image without Text Area Detection](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/english/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..2d9ec66d7 --- /dev/null +++ b/ocr/english/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: en +og_description: Convert TIFF to text with Aspose.OCR. This guide shows batch image + to text conversion and how to extract text from TIFF files in a few lines of C#. +og_title: Convert TIFF to Text in C# – Complete Batch OCR Guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Convert TIFF to Text in C# – Complete Batch OCR Guide +url: /net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert TIFF to Text in C# – Complete Batch OCR Guide + +Ever needed to **convert TIFF to text** but weren’t sure where to start? You’re not alone—many developers stumble over batch OCR when dealing with scanned documents. In this tutorial we’ll walk through a hands‑on solution that **extracts text from TIFF** files using Aspose.OCR, and we’ll do it in parallel so large folders finish in seconds. + +We’ll also touch on **batch image to text conversion** best practices, so by the end you’ll have a reusable snippet that turns a whole directory of scanned images into neat *.txt* files—perfect for indexing, searching, or feeding into downstream analytics. + +## What You’ll Need + +- **.NET 6.0** or later (the code compiles on .NET Framework too) +- **Aspose.OCR for .NET** NuGet package (`Install-Package Aspose.OCR`) +- A folder containing one or more *.tif* files (the classic TIFF scan format) +- Your favorite IDE (Visual Studio, VS Code, Rider—whatever you like) + +That’s it. No external services, no API keys, just pure C# and Aspose. + +![Screenshot of a TIFF file being processed and the resulting text file](/images/ocr-result.png "OCR result showing converted TIFF to text output") + +*(Alt text: Screenshot showing converted TIFF to text output on screen)* + +## Step 1: Set Up the OCR Engine – Convert TIFF to Text + +First things first, we need an `OcrEngine` instance that knows it should read English characters. The engine is the heart of the conversion; configuring it correctly ensures reliable results. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Why this matters:* +Aspose.OCR supports dozens of languages. If you’re dealing with multilingual scans, simply change `OcrLanguage.English` to the appropriate enum value. Leaving the language undefined forces the engine into auto‑detect mode, which can be slower and less accurate. + +## Step 2: Gather All TIFF Files – Extract Text from TIFF Efficiently + +Next we pull every *.tif* file from a folder you specify. Using `Directory.GetFiles` gives us a clean array that we can feed into the batch processor. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro tip:* The `SearchOption.AllDirectories` flag can be used if your scans are nested in sub‑folders. Just remember that deeper recursion may increase memory usage during the batch step. + +## Step 3: Perform Parallel OCR – Batch Image to Text Conversion + +Now the fun part. Aspose.OCR ships with a static helper `BatchOcr.RecognizeAll` that accepts an array of file paths, an engine, and a `parallelism` hint. We’ll spin up four threads, which on a modern quad‑core laptop gives near‑linear speed‑up. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Why parallelism?* +Scanning a batch of high‑resolution TIFFs can be CPU‑intensive. By spreading the work across multiple threads we keep all cores busy, cutting total runtime dramatically. If you run this on a server with more cores, bump the `parallelism` value accordingly. + +## Step 4: Write the Output – Convert Scanned Images TXT Files + +Finally we loop through the dictionary and write each piece of text to a *.txt* file that shares the original base name. This is the moment where **convert scanned images txt** becomes a reality. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### What the code does, in plain English + +1. **Create** an OCR engine set for English. +2. **Collect** every TIFF file from the target folder. +3. **Run** `BatchOcr.RecognizeAll` with four threads, turning each image into a string. +4. **Loop** over the results, swapping the `.tif` extension for `.txt` and writing the string to disk. + +That’s the entire **convert TIFF to text** workflow in under 50 lines of code. + +## Handling Edge Cases – When Things Don’t Go Smoothly + +- **Missing or corrupted TIFFs** – `BatchOcr` will throw an `OcrException`. Wrap the call in a `try / catch` if you need graceful degradation. +- **Non‑English documents** – change `OcrLanguage.English` to `OcrLanguage.Spanish`, `OcrLanguage.French`, etc., or use `OcrLanguage.AutoDetect`. +- **Very large images** – consider lowering the DPI before OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) to save memory, though you may lose some accuracy. +- **Output encoding** – if you need a specific code page (e.g., Windows‑1252), pass it to `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Pro Tips for Robust Batch Conversions + +- **Log failures**: create a `List failedFiles` and append any file that throws; write the list to a log after the loop. +- **Reuse the engine**: the same `OcrEngine` instance can be reused across many files; don’t instantiate inside the loop. +- **Validate the result**: a quick `if (string.IsNullOrWhiteSpace(extractedText))` can flag scans that were blank or unreadable. +- **Combine with PDF**: if your source is a multi‑page PDF, convert each page to TIFF first (Aspose.PDF does that) and then run this batch. + +## Next Steps – Going Beyond Simple Conversion + +Now that you can **extract text from TIFF** files in bulk, you might want to: + +- Feed the *.txt* files into a search index (Elasticsearch, Azure Cognitive Search). +- Run language detection on each result to route documents to locale‑specific pipelines. +- Generate searchable PDFs by overlaying the OCR text back onto the original images (Aspose.PDF again). + +All of those scenarios build on the same core idea: **batch image to text conversion** is a building block for larger document‑processing systems. + +--- + +### Conclusion + +You’ve just learned how to **convert TIFF to text** using Aspose.OCR, process an entire folder in parallel, and save each result as a clean *.txt* file. The solution is lightweight, fully configurable, and ready for production—whether you’re digitizing legacy invoices, archiving scanned contracts, or powering a text‑search engine. + +Give it a spin, tweak the parallelism, and start feeding those newly minted text files into whatever workflow you need. Happy OCRing! + +--- + + +## Related Tutorials + +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/english/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..b3312152e --- /dev/null +++ b/ocr/english/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: en +og_description: Extract text from image using a minimal ASP.NET Core API. This guide + shows how to upload image via POST, read multipart form data, and perform OCR on + image. +og_title: Extract Text from Image in ASP.NET Core – Step‑by‑Step +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide +url: /net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + +Ever wondered how to **extract text from image** without wrestling with heavyweight frameworks? You’re not alone. Many developers need a quick way to let users drop a picture and get back the raw characters, whether it’s scanning receipts, digitizing handwritten notes, or powering a search index. + +In this tutorial we’ll spin up a tiny ASP.NET Core Minimal API that **uploads image via POST**, parses the *multipart/form‑data* payload, and then **perform OCR on image** using a singleton `OcrEngine`. By the end you’ll have a fully runnable app that you can drop into any .NET 8 project and start extracting text from image right away. + +## What You’ll Build + +- A minimal web app that listens on `/ocr`. +- An endpoint that accepts an image file sent with a `multipart/form-data` POST request. +- Logic that reads the uploaded file, feeds it to the OCR engine, and returns plain‑text results. +- Optional GPU acceleration snippet (commented out) for those with a compatible card. + +**Prerequisites** +- .NET 8 SDK (or later). +- Basic familiarity with C# and the command line. +- An OCR library that exposes an `OcrEngine` class (the sample assumes a hypothetical NuGet package). + +If you’ve got those, let’s dive in. + +## Step 1: Set Up the Project and Add the OCR Package + +First, create a new web project and pull in the OCR library. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro tip:** Keep your dependencies up to date. Newer versions often bring performance gains, especially for GPU‑accelerated inference. + +## Step 2: Register a Singleton OCR Engine (Primary Service) + +We want a single `OcrEngine` instance for the whole app—no need to spin up a new engine per request. Register it in the builder’s service container. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Why a singleton?** +Creating an OCR engine can be expensive—think loading neural‑network weights into memory. By reusing the same instance we save both CPU cycles and RAM, which translates to faster response times for every `/ocr` call. + +## Step 3: Build the Application + +Now we materialize the `WebApplication` object. + +```csharp +var app = builder.Build(); +``` + +That line looks almost magical, but under the hood it wires up routing, middleware, and the DI container we just configured. + +## Step 4: Define the POST Endpoint – “Upload Image via POST” + +Here’s the heart of the tutorial: an endpoint that **upload image via POST**, reads the multipart payload, and hands the data to the OCR engine. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Breaking Down the Logic + +| Step | What Happens | Why It Matters | +|------|--------------|----------------| +| **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without this, you can’t access the uploaded files. | +| **form.Files["image"]** | Retrieves the file whose form‑field name is `image`. | Guarantees a predictable contract for callers. | +| **Content‑type check** | Verifies the file is an image (e.g., `image/png`). | Prevents the OCR engine from choking on non‑image data. | +| **Image.FromStream** | Converts the raw stream into a `System.Drawing.Image`. | The OCR library expects an `Image` object, not a raw byte array. | +| **ocr.Recognize(img)** | Calls the OCR engine to **how to recognize text from image**. | This is the core **perform OCR on image** step. | +| **Results.Text** | Sends back the plain‑text response. | A simple, consumable format for downstream services. | + +## Step 5: Run the API + +Finally, start the web server. + +```csharp +app.Run(); +``` + +When you execute `dotnet run`, the API will listen on `http://localhost:5000` (or a port of your choosing). You can test it with `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Expected output:** The console will print the recognized characters, e.g.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +If the image is blurry or the language isn’t supported, the OCR engine will return an empty string or an error message—handle those cases in production code. + +## Edge Cases & Best Practices + +### 1. Large Files + +The default request body limit is 30 MB. For larger scans you might need to adjust: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynchronous OCR + +Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the lambda as `async`. + +### 3. Security Considerations + +- **Validate file size** before loading it into memory. +- **Sanitize the filename** if you ever write it to disk. +- **Rate‑limit** the endpoint to avoid denial‑of‑service attacks. + +### 4. GPU Acceleration + +If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially on high‑resolution images. + +## Full Working Example + +Below is the complete `Program.cs` you can copy‑paste into a fresh Minimal API project. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Save, run `dotnet run`, and you’re ready to **extract text from image** on demand. + +## Conclusion + +We’ve walked through a **complete, end‑to‑end solution** for extracting text from image using ASP.NET Core Minimal API. Starting from project scaffolding, we **registered a singleton OCR engine**, built an endpoint that **uploads image via POST**, **read multipart form data**, and finally **perform OCR on image** to return clean plain‑text. + +From here you can: + +- Add JSON wrappers for richer responses. +- Plug in a database to store the extracted text. +- Extend support to multiple languages (`OcrLanguage.Spanish`, etc.). + +The pattern scales nicely—just drop the same endpoint into a larger microservice or expose it behind an API gateway. + +Got questions about handling PDFs, batch processing, or GPU tuning? Drop a comment, and happy coding! + + +## Related Tutorials + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/english/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..1c34fa4dd --- /dev/null +++ b/ocr/english/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-05-25 +description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: en +og_description: Extract text from image with C#. This guide shows how to convert jpg + to text, load image for OCR, and handle multilingual content. +og_title: Extract Text from Image in C# – Aspose OCR Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Extract Text from Image in C# – Complete Aspose OCR Guide +url: /net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Image in C# – Complete Aspose OCR Guide + +Ever wondered how to **extract text from image** using plain C# code? You’re not the only one. Whether you’re digitizing receipts, scanning signboards, or just curious about OCR, the ability to pull characters out of a picture is a handy skill. In this tutorial we’ll walk through a full, runnable example that shows exactly how to **extract text from image** with Aspose.OCR, and we’ll also cover how to **convert jpg to text**, **load image for OCR**, and answer the classic “**how to ocr image**” question once and for all. + +By the end of this guide you’ll have a self‑contained console app that reads a JPEG file, recognizes Ukrainian (or any other supported language), and prints the result to the console. No vague references, no missing pieces—just a complete solution you can copy‑paste and run. + +--- + +## What You’ll Learn + +* How to install the Aspose.OCR NuGet package. +* The exact code needed to **load image for OCR** in C#. +* How to set the language and actually **extract text from image**. +* Tricks for **convert jpg to text** efficiently. +* Common pitfalls and how to avoid them. + +If you already have a .NET development environment set up, you’re ready to dive in. Otherwise, the prerequisites section below will get you up to speed. + +--- + +## Prerequisites + +| Requirement | Why it matters | +|-------------|----------------| +| .NET 6.0 SDK (or newer) | Provides the runtime for the console app. | +| Visual Studio 2022 or VS Code | Makes editing and debugging easier. | +| Internet connection (first run) | NuGet needs to download Aspose.OCR. | +| A JPEG image you want to process (e.g., `ukrainian_sign.jpg`) | The source file for the OCR engine. | + +> **Pro tip:** If you’re on Linux or macOS, the same code works with the .NET CLI (`dotnet new console`), so feel free to skip the heavy IDE. + +--- + +## Step 1 – Install Aspose.OCR via NuGet + +Open your terminal (or Package Manager Console) and run: + +```bash +dotnet add package Aspose.OCR +``` + +That single line pulls the latest Aspose.OCR binaries and all transitive dependencies. No manual DLL juggling required. + +--- + +## Step 2 – Create the OCR Engine (The Heart of Extraction) + +Now that the library is in place, we can create an instance of `OcrEngine`. This object is responsible for **extracting text from image** data. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Why this matters:** The engine encapsulates the OCR algorithms, language models, and configuration options. Instantiating it once and re‑using it across multiple images is both memory‑efficient and fast. + +--- + +## Step 3 – Load Image for OCR (And Set the Language) + +The next step is to tell the engine which picture to read. This is where the **load image for OCR** phrase comes into play. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Edge case:** If the file doesn’t exist, `Image.FromFile` throws a `FileNotFoundException`. Wrap the call in a try‑catch block for production code. + +--- + +## Step 4 – Perform OCR and Extract Text + +With the image loaded, the engine can now **extract text from image**. The `Recognize` method does the heavy lifting. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +If everything goes well, `recognizedText` will contain the plain‑text representation of everything the OCR engine could read. + +--- + +## Step 5 – Convert JPG to Text (Putting It All Together) + +The code we’ve built so far already **convert jpg to text**, but let’s wrap it in a neat method that you can call repeatedly. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Now you can simply do: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Expected output** (truncated for brevity): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +If the image contains English text, change `OcrLanguage.English` and you’ll see the corresponding output. + +--- + +## Step 6 – Handling Common “How to OCR Image” Questions + +### 6.1 Can I OCR a PNG or BMP? + +Absolutely. The `Image.FromFile` method supports all formats that System.Drawing recognizes, so just point the path to a `.png` or `.bmp` file and the rest of the code stays identical. + +### 6.2 What if the image is low‑resolution? + +OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale the image with `Graphics` before feeding it to the engine: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Do I need a license for Aspose.OCR? + +Aspose offers a free trial with a watermark. For production use, purchase a license and add: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Full Working Example + +Below is a complete, ready‑to‑run console application that demonstrates **how to OCR image**, **load image for OCR**, and **convert jpg to text** in one tidy package. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**How to run it** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +You should see the extracted text printed to the console, confirming that you have successfully **extract text from image** using C#. + +--- + +## Common Pitfalls & Pro Tips + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| Blank output | Image too dark or low contrast. | Pre‑process with `Bitmap` to increase brightness. | +| Wrong language | `Language` property left at default English. | Explicitly set `ocrEngine.Language = OcrLanguage.Ukrainian;` (or your target). | +| Out‑of‑memory error | Very large images loaded without disposal. | Wrap `Image.FromFile` in a `using` block (as shown). | +| License watermark | Running on a trial without a license. | Apply a purchased license early in `Main`. | + +--- + +## Conclusion + +We’ve just covered everything you need to **extract text from image** in C#—from installing Aspose.OCR, **loading image for OCR**, to **convert jpg to text** and handling multilingual scenarios. The complete sample program ties all the pieces together, giving you a reliable foundation for any OCR‑related project. + +Next, you might explore: + +* **How to OCR image** streams instead of files (use `MemoryStream`). +* Adding **c# image to text** post‑processing like spell‑checking. +* Integrating the OCR step into a larger pipeline (e.g., storing results in a database). + +Feel free to experiment with different languages, image formats, and preprocessing tricks. OCR is as much an art as a science, and the more you play, the better the results. + +Happy coding, and may your images always be readable! + + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/english/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..91c4f3cdb --- /dev/null +++ b/ocr/english/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-05-25 +description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: en +og_description: How to use OCR in C# to extract text from image files. This guide + shows you how to recognize Chinese characters from a JPG using Aspose.OCR. +og_title: How to Use OCR in C# – Recognize Chinese Text from JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: How to Use OCR in C# – Recognize Chinese Text from JPG +url: /net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# How to Use OCR in C# – Recognize Chinese Text from JPG + +Ever wondered **how to use OCR** to pull words out of a picture you snapped on your phone? You’re not alone. In many real‑world projects—think receipt scanners, translation apps, or automated data entry—you’ll need to **extract text from image** files quickly and reliably. + +In this tutorial we’ll walk through a complete, runnable example that **recognizes text from JPG** files and even handles the tricky case of **recognize Chinese characters** using the **OCR Chinese Simplified** language pack. By the end, you’ll have a self‑contained console app that prints the detected string to the console, no extra manual downloads required. + +> **Quick note:** The code works with Aspose.OCR ≥ 23.7, which automatically fetches language resources on first use. If you’re on an older version, you’ll need to add the language manually. + +## Prerequisites + +Before we dive in, make sure you have: + +- .NET 6.0 SDK or later (the example targets .NET 6, but .NET 5 works as well) +- A recent version of Visual Studio 2022 or VS Code with the C# extension +- An internet connection for the first language download +- A JPG image that contains Simplified Chinese text (we’ll call it `chinese_sign.jpg`) + +That’s it—no heavyweight OCR engines, no native DLL juggling. Just a few NuGet commands and a couple of lines of code. + +## Step 1: Install Aspose.OCR via NuGet + +First things first: we need the OCR library. Open a terminal in your project folder and run: + +```bash +dotnet add package Aspose.OCR +``` + +Or, if you prefer the Visual Studio UI, right‑click **Dependencies → Manage NuGet Packages**, search for “Aspose.OCR”, and click **Install**. + +> **Pro tip:** Keep your packages up‑to‑date. New language packs and performance tweaks land in every minor release. + +## Step 2: Create a New Console Project (If You Haven’t Already) + +If you’re starting from scratch, create a fresh console app: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Now you have a `Program.cs` file ready for the OCR code. + +## Step 3: Write the OCR Code – Recognize Chinese Simplified from a JPG + +Open `Program.cs` and replace its contents with the following. Every line is annotated so you can see *why* we’re doing each step, not just *what* we’re doing. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### What’s happening under the hood? + +- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese language pack. +- **First‑time download**: When `Recognize` runs, the SDK reaches out to Aspose’s CDN, pulls the ≈6 MB language file, caches it locally, and then proceeds with the OCR. Subsequent calls are instantaneous. +- **`Image.FromFile`** works with any raster format that .NET can decode—JPG, PNG, BMP—so you can **extract text from image** files of many types, not just JPG. + +## Step 4: Run the Application and Verify Output + +Build and run: + +```bash +dotnet run +``` + +You should see something like: + +``` +=== Recognized Text === +欢迎光临 +``` + +If the console prints gibberish or an empty string, double‑check that: + +1. The image actually contains clear, high‑contrast Chinese characters. +2. The file path is correct (no stray spaces or missing extensions). +3. Your machine can reach `https://download.aspose.com` for the language pack. + +## Step 5: Handling Edge Cases and Common Pitfalls + +### 5.1 Dealing with Low‑Quality Images + +OCR accuracy drops when the source image is blurry, noisy, or has poor lighting. A quick fix is to pre‑process the image: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Running in a Headless Environment + +If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` library (required for `System.Drawing`) is installed: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Caching the Language Pack Manually + +You can download the language file once and point Aspose to it via the `License` API, which eliminates the one‑time network call. This is handy for offline scenarios. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Full Working Example (All‑In‑One) + +Below is the *complete* program you can copy‑paste into `Program.cs`. No hidden pieces, no external scripts. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Expected Output + +If the JPG contains the phrase “欢迎光临”, the console will print: + +``` +=== Recognized Text === +欢迎光临 +``` + +Feel free to replace the image with any other Simplified Chinese sign, street name, or product label—the engine will do its best. + +## Conclusion + +We’ve just covered **how to use OCR** in C# to **extract text from image** files, specifically tackling the challenge of **recognize Chinese characters** in a **JPG**. By leveraging Aspose.OCR’s on‑the‑fly language download, you can keep your deployment lightweight while still supporting **OCR Chinese Simplified** out of the box. + +What’s next? Try these ideas: + +- **Batch processing**: Loop over a folder of images and write each result to a CSV. +- **Combine with translation APIs**: Feed the recognized string into Azure Translator for real‑time multilingual apps. +- **Explore other languages**: Swap `OcrLanguage.ChineseSimplified` for `Japanese` or `Arabic` and see how the same code adapts. + +Got questions about performance tuning, licensing, or integrating OCR into a web service? Drop a comment below—happy coding! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + + +## Related Tutorials + +- [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/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/english/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/english/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..ebf53a3e5 --- /dev/null +++ b/ocr/english/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,306 @@ +--- +category: general +date: 2026-05-25 +description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: en +og_description: OCR Russian text in C# made easy. Learn to extract text from image, + convert image to text C#, and load image for OCR with Aspose OCR. +og_title: OCR Russian Text in C# – Complete Aspose OCR Guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR Russian Text in C# – Complete Guide Using Aspose OCR +url: /net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Russian Text in C# – Complete Guide Using Aspose OCR + +Ever needed to OCR Russian text in C# but weren't sure which library to trust? You're not alone. Getting clean, readable characters from a Cyrillic image can feel like decoding secret messages—especially if you haven't set the right language model. + +In this tutorial we’ll walk through a hands‑on example that shows you how to **extract text from image** files, convert *image to text C#* style, and handle the nuances of Russian language recognition with Aspose OCR. By the end you’ll have a ready‑to‑run console app that loads an image for OCR, prints the recognized string, and gives you a solid foundation for more advanced scenarios. + +## What You’ll Learn + +- How to install and configure **Aspose OCR C#** for Russian language support. +- The exact steps to **load image for OCR** and call the engine. +- Tips for handling common pitfalls like missing language resources or blurry scans. +- Ways to extend the solution, such as batch processing multiple files or tweaking confidence thresholds. + +No prior experience with Aspose is required; just a basic familiarity with C# and .NET will get you moving. + +## Prerequisites + +Before we dive in, make sure you have the following: + +1. **.NET 6.0** (or later) SDK installed – the code works on .NET Core and .NET Framework alike. +2. **Visual Studio 2022** (or any IDE you prefer). +3. An **Aspose.OCR for .NET** NuGet package – you can grab a free trial key from the Aspose website. +4. A **Russian language model** file (`rus.traineddata`) – download it from the Aspose resource page and place it in a folder you’ll reference later. +5. A sample image (`russian_doc.png`) containing clear Cyrillic text. + +Got all that? Great—let’s get started. + +## Step 1: Set Up the Project and Install Aspose OCR + +First, create a new console project: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Now add the Aspose OCR package: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** If you’re using a trial license, keep the `Aspose.Total.lic` file handy; you’ll load it in code to avoid watermarks. + +Once the package is installed, open `Program.cs`. You’ll see the default `Main` method—replace its content with the skeleton we’ll build. + +## Step 2: Configure the OCR Engine for Russian Language + +The heart of the operation is the `OcrEngine` object. We need to tell it two things: which language to recognize and where to find the language model files. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Why this matters:** If you skip setting `Language = OcrLanguage.Russian`, the engine defaults to English, and any Cyrillic characters will appear as garbled symbols. The `ResourceFolder` points to the directory that holds the `rus.traineddata` file; without it, Aspose throws a *resource not found* exception. + +## Step 3: Load the Image for OCR + +Now we need to **load image for OCR**. Aspose OCR works with `System.Drawing.Image`, so you can pass any supported format (PNG, JPEG, BMP, etc.). Make sure the file path is correct; relative paths are fine if you keep the image next to the executable. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** If the image is large (over 5 MB) you might want to downscale it first. OCR accuracy drops when the DPI is too low, but huge files can cause memory pressure. A quick resize can be done with `Graphics` if needed. + +## Step 4: Recognize the Text – From Image to Text C# Style + +With the engine configured and the image loaded, the actual recognition is a single call: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +When you run the program (`dotnet run`), you should see something like: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +If the output looks like gibberish, double‑check that: + +- The `rus.traineddata` file is present in `ResourceFolder`. +- The image isn’t too blurry; consider applying a simple binarization filter before OCR. +- The language setting is truly `OcrLanguage.Russian`. + +## Step 5: Fine‑Tuning and Common Pitfalls + +### Adjusting Confidence Threshold + +Aspose OCR returns a confidence value per character internally. While the API doesn’t expose it directly, you can enable **detailed output** to see which words were low‑confidence: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +If you notice frequent mis‑recognitions, try: + +- **Pre‑processing**: Convert the image to grayscale, increase contrast, or apply a median filter. +- **DPI settings**: Ensure the image is at least 300 DPI for Cyrillic scripts. + +### Batch Processing Multiple Images + +If you need to **extract text from image** files in bulk, wrap the recognition logic in a loop: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Now each PNG gets its own `.txt` counterpart—handy for document archiving. + +### Handling Unicode Output + +Cyrillic characters are Unicode, so make sure your console encoding can display them: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Place this line right after the `Main` method starts. Without it, you might see question marks (`?`) instead of Russian letters. + +## Full Working Example + +Below is the complete, ready‑to‑run code. Copy‑paste it into `Program.cs`, adjust the paths, and you’re good to go. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Expected output** (assuming the sample image says “Пример текста на русском языке."): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +If you see anything else, revisit the troubleshooting tips in Step 5. + +## Conclusion + +You now have a solid, end‑to‑end example of how to **ocr russian text** in C# using Aspose OCR. From installing the library, configuring the Russian language model, to loading an image and converting it to clean Unicode text, every piece is covered. + +Remember, the key to reliable OCR is good source material: clear fonts, adequate DPI, and the correct language resources. Once you master the basics, you can expand to batch processing, integrate with cloud storage, or even combine with AI post‑processing for spell‑checking. + +### What’s Next? + +- Explore **aspose ocr c#** advanced options like layout analysis or PDF output. +- Combine this with **extract text from image** workflows in Azure Functions for serverless processing. +- Try different languages—simply switch `OcrLanguage.Russian` to `OcrLanguage.English` or another supported code. + +Got questions or a tricky image that won’t cooperate? Drop a comment below, and happy coding! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + + +## Related Tutorials + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/english/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..2676c50d3 --- /dev/null +++ b/ocr/english/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: recognize text from image using Aspose OCR in C#. Learn how to load image + for OCR, set OCR language, create OCR engine and extract text from TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: en +og_description: recognize text from image using Aspose OCR in C#. This tutorial shows + how to create OCR engine, load image for OCR, set OCR language, and extract text + from TIFF. +og_title: recognize text from image with Aspose OCR – Complete C# Guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: recognize text from image with Aspose OCR – Complete C# Guide +url: /net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# recognize text from image with Aspose OCR – Complete C# Guide + +Ever needed to **recognize text from image** but weren’t sure which library would give you both speed and accuracy? You’re not alone. In many invoice‑processing or archival projects the biggest pain point is getting clean, searchable text out of TIFF files without writing a custom parser. + +Here’s the thing: Aspose OCR for .NET makes that whole pipeline a piece of cake. In this guide we’ll walk through everything you need—installing the package, **creating OCR engine**, loading a TIFF, setting the OCR language, and finally **extracting text from TIFF**. By the end you’ll have a ready‑to‑run console app that can **recognize text from image** files in a flash. + +## Prerequisites + +- .NET 6.0 or later (the code works with .NET Core and .NET Framework as well) +- Visual Studio 2022 (or any IDE you prefer) +- Aspose.OCR NuGet package (GPU support requires the `Aspose.OCR.Gpu` add‑on) +- A GPU with CUDA support if you want the extra speed (optional but recommended) + +> **Pro tip:** If you don’t have a GPU, just omit the `GpuDevice` line and the engine will fall back to CPU automatically. + +## Step 1: Install Aspose OCR and Create OCR Engine + +First, add the necessary packages via NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Now we can **create OCR engine**. This object is the heart of the process; it holds configuration such as the device to run on and memory limits. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Why this matters:** By binding the engine to a GPU you dramatically cut down the time it takes to **recognize text from image**, especially for large batches of high‑resolution TIFFs. + +## Step 2: Load Image for OCR + +Next, we need to **load image for OCR**. Aspose.OCR works with `System.Drawing.Image`, so any format supported by GDI+ (including multi‑page TIFF) is fine. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +If you’re dealing with a multi‑page TIFF you can loop through the pages using `image.SelectActiveFrame`, but for most scenarios a single call is enough. + +## Step 3: Set OCR Language + +The engine doesn’t magically know which language you’re scanning. **Set OCR language** before you run the recognizer; otherwise you’ll get a lot of garbled output. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Did you know?** Switching languages at runtime is cheap—you can even process a mixed‑language document by changing this property between pages. + +## Step 4: Perform the Recognition – Recognize Text from Image + +Now the fun part: actually **recognize text from image**. The `Recognize` method returns a plain string with all detected characters. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +If you need confidence scores or bounding boxes you can use the overload that returns an `OcrResult` object, but for most extraction tasks the plain string is sufficient. + +## Step 5: Extract Text from TIFF (and handle multi‑page files) + +When the source is a TIFF containing several pages, you’ll want to repeat steps 2‑4 for each frame. Here’s a quick loop that **extracts text from TIFF** page by page: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +The code above prints the extracted text for every page, making it trivial to pipe the results into a database or a search index. + +## Step 6: Display or Persist the Extracted Text + +Finally, let’s **display the extracted text** and optionally write it to a file for later processing. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Running the program should output the recognized characters and create `extracted_text.txt` beside your source TIFF. + +--- + +## Common Questions & Edge Cases + +- **What if my GPU isn’t detected?** + Remove the `GpuDevice` line; the engine will automatically switch to CPU mode. Performance will be slower but the results remain accurate. + +- **Can I process PNG or JPEG files?** + Absolutely—`Image.FromFile` works with any format supported by System.Drawing, so you can **load image for OCR** regardless of extension. + +- **How do I handle low‑resolution scans?** + Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. Higher DPI gives the engine more pixels to work with, improving accuracy. + +- **Is there a limit to the size of the TIFF?** + The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the engine will fallback to CPU for the remaining pages. + +--- + +## Conclusion + +You now have a complete, production‑ready snippet that **recognize text from image** files using Aspose OCR in C#. The tutorial covered how to **create OCR engine**, **load image for OCR**, **set OCR language**, and **extract text from TIFF**—all while leveraging GPU acceleration for speed. + +From here you might: + +- Experiment with different languages (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, etc.). +- Integrate the output into a searchable ElasticSearch index. +- Add post‑processing (spell‑check, regex cleanup) to improve data quality. + +Give it a try on your own invoice batch, tweak the memory limits, and watch the OCR performance soar. Happy coding! + + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..c20e97ed5 100644 --- a/ocr/french/net/ocr-configuration/_index.md +++ b/ocr/french/net/ocr-configuration/_index.md @@ -66,6 +66,8 @@ Libérez la puissance de la reconnaissance d’images OCR dans .NET avec Aspose. ### [OCROOpération avec sélection de langue dans la reconnaissance d'images OCR](./ocr-operation-with-lingual-selection/) 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/) +### [Créer un moteur OCR en C# – Guide complet](./create-ocr-engine-in-c-complete-guide/) +Apprenez à créer et configurer un moteur OCR en C# avec Aspose.OCR, du code initial aux options avancées. 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. @@ -115,4 +117,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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/french/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..bb7230148 --- /dev/null +++ b/ocr/french/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Créer un moteur OCR en C# et apprendre à vérifier son mode d'évaluation + ainsi que son statut de licence en quelques lignes de code. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: fr +og_description: Créez un moteur OCR en C# et voyez instantanément comment détecter + le mode d'évaluation et afficher le statut de la licence. +og_title: Créer un moteur OCR en C# – Guide étape par étape +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Créer un moteur OCR en C# – Guide complet +url: /fr/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Créer un moteur OCR en C# – Guide complet + +Vous vous êtes déjà demandé comment **créer des objets moteur OCR** en C# sans fouiller dans d'innombrables documents ? Vous n'êtes pas le seul. De nombreux développeurs se heurtent à un mur lorsqu'ils doivent lancer un moteur OCR, vérifier s'il fonctionne en mode d'essai, et afficher l'état de la licence aux utilisateurs. + +Dans ce tutoriel, nous parcourrons un exemple concis, de bout en bout, qui **crée un moteur OCR**, vérifie son **mode d'évaluation du moteur OCR**, et affiche un message convivial sur l'état de la licence. À la fin, vous disposerez d'une application console prête à l'emploi et d'un modèle mental clair pour gérer la licence OCR dans vos propres projets. + +## Ce que vous allez apprendre + +- Comment instancier un `OcrEngine` (le cœur de tout flux de travail OCR). +- Pourquoi la détection du **mode d'évaluation** est importante pour la conformité et l'expérience utilisateur. +- La meilleure façon de **vérifier l'état de la licence OCR** et de réagir aux états inattendus. +- Pièges courants — références nulles, gestion des exceptions et incompatibilités de version. + +Aucun outil externe requis au-delà du SDK OCR que vous avez déjà installé. Si vous êtes à l'aise avec la syntaxe de base du C#, vous êtes prêt. + +## Prérequis + +- .NET 6.0 ou supérieur (le code se compile avec .NET Core et .NET Framework). +- Un SDK OCR qui expose une classe `OcrEngine` avec une propriété `IsEvaluation` (par exemple, le hypothétique `MyOcrSdk`). +- Un éditeur de texte ou un IDE (Visual Studio, VS Code, Rider—choisissez votre préféré). + +C’est tout. Plongeons‑y. + +## Étape 1 : Configurer un nouveau projet console + +Tout d'abord, créez une nouvelle application console afin de pouvoir exécuter le code isolément. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Ouvrez le fichier `Program.cs` généré. Nous remplacerons son contenu par un exemple complet qui **crée des instances de moteur OCR** et gère la licence. + +## Étape 2 : Importer l'espace de noms du SDK OCR + +En supposant que le SDK est référencé via NuGet (`MyOcrSdk` est un espace réservé), ajoutez la directive using en haut du fichier. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Si vous n'avez pas encore ajouté le paquet, exécutez : + +```bash +dotnet add package MyOcrSdk +``` + +> **Astuce :** Gardez votre version du SDK à jour ; les nouvelles versions améliorent souvent la détection du mode d'évaluation. + +## Étape 3 : Créer l'instance du moteur OCR + +Nous allons enfin **créer des objets moteur OCR**. C’est le cœur de tout flux de travail OCR — pensez-y comme le cerveau qui lira plus tard les images. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Pourquoi cette étape est‑elle cruciale ? Le `OcrEngine` encapsule toute la configuration, les packs de langues et les données de licence. Sans lui, vous ne pouvez pas traiter les images ni interroger le drapeau d'évaluation. + +> **Note :** Certains SDK permettent de passer un objet de configuration au constructeur (par ex., langue, DPI). Si vous avez besoin de paramètres personnalisés, modifiez la ligne en conséquence. + +## Étape 4 : Déterminer le mode d'évaluation du moteur OCR + +La plupart des fournisseurs OCR proposent une version d'essai qui fonctionne en **mode d'évaluation** jusqu'à ce qu'une clé de licence valide soit fournie. Savoir si vous êtes en mode d'essai vous permet d'afficher des indications UI appropriées ou de restreindre certaines fonctionnalités. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +La propriété `IsEvaluation` renvoie `true` lorsque le moteur n'est pas licencié ou utilise un essai limité dans le temps. C’est un moyen rapide et fiable de protéger les fonctionnalités premium. + +### Et si la propriété est absente ? + +Les versions plus anciennes du SDK peuvent exposer une méthode comme `GetLicenseInfo()` à la place. Dans ce cas, vous inspecteriez l'objet retourné pour un indicateur `IsTrial`. Consultez toujours le journal des modifications du SDK lors d'une mise à jour. + +## Étape 5 : Afficher l'état actuel de la licence + +Enfin, affichons à l'utilisateur si le moteur est licencié ou toujours en version d'essai. Une simple instruction console WriteLine suffit, mais vous pouvez l'adapter pour des applications GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +L'opérateur ternaire garde le code propre, et les messages sont suffisamment clairs pour les utilisateurs finaux ou les développeurs lisant les journaux. + +## Exemple complet fonctionnel + +En combinant le tout, voici un programme autonome que vous pouvez copier‑coller dans `Program.cs` et exécuter avec `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Résultat attendu + +- **Version d'essai :** + `Running in evaluation mode – limited functionality.` + +- **Version licenciée :** + `Licensed – full OCR capabilities enabled.` + +Si le SDK lève une exception (par ex., DLL native manquante), le bloc catch affichera un message d'erreur utile au lieu de faire planter l'application entière. + +## Gestion des cas limites et des pièges courants + +### 1. Instances d'engines nulles + +Bien que le constructeur renvoie généralement un objet valide, certains SDK peuvent retourner `null` si des dépendances natives requises sont manquantes. Protégez‑vous contre cela : + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Expiration de la licence pendant l'exécution + +Une licence d'essai peut expirer en cours de session. Interrogez périodiquement `IsEvaluation` si votre application reste active longtemps. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Noms de propriétés différents selon les versions + +Les versions plus anciennes peuvent exposer `engine.EvaluationMode` ou `engine.License.IsTrial`. Lors d'une mise à jour, recherchez les notes de version du SDK pour les changements majeurs. + +### 4. Scénarios multi‑thread + +Si vous lancez plusieurs travailleurs OCR, créez **un moteur OCR par thread** sauf si le SDK supporte explicitement le partage thread‑safe. Partager un seul moteur peut entraîner des conditions de concurrence et des lectures de licence erronées. + +## Astuces pro pour la production + +- **Mettez en cache l'état de la licence** après la première vérification pour éviter les appels de propriété inutiles. +- **Enregistrez la clé de licence** (masquée) au démarrage pour les traces d’audit — cela aide les équipes de support à diagnostiquer les problèmes de licence. +- **Fournissez un commutateur UI** qui indique aux utilisateurs qu’ils sont en mode d'essai et propose un bouton « Acheter la licence ». +- **Automatisez le renouvellement de licence** en utilisant l'API d'activation du SDK, si disponible, pour garantir une expérience utilisateur fluide. + +## Conclusion + +Nous venons de **créer des objets moteur OCR** en quelques lignes, d’inspecter le **mode d'évaluation du moteur OCR**, et d’afficher un message clair sur le **statut de la licence OCR**. L’exemple complet fonctionne immédiatement, gère les erreurs avec grâce, et souligne le « pourquoi » de chaque étape—vous permettant de l’adapter aux scénarios desktop, web ou côté service. + +Ensuite, vous pourriez explorer : + +- Alimenter des images dans `engine.Recognize` et gérer le support multilingue. +- Utiliser les API **check OCR license** pour activer programmatiquement une clé achetée. +- Intégrer avec des frameworks UI (WinForms, WPF, MAUI) pour afficher des badges de licence. + +Essayez-les, et vous disposerez d’une base OCR robuste prête pour toute application. Bon codage ! + +## Tutoriels associés + +- [Comment extraire OCR – Configuration OCR](/ocr/english/net/ocr-configuration/) +- [Comment obtenir les résultats OCR avec Aspose.OCR pour .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Comment OCR un PDF en .NET avec Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/ocr-optimization/_index.md b/ocr/french/net/ocr-optimization/_index.md index 8d188ea7d..2e4a79302 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. +### [Prétraiter l'image pour l'OCR – Guide complet Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Apprenez à préparer vos images pour l'OCR avec Aspose en C#, incluant filtres et réglages avancés. ## Questions fréquemment posées diff --git a/ocr/french/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/french/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..6b26334b6 --- /dev/null +++ b/ocr/french/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-25 +description: Prétraitez l'image pour l'OCR avec Aspose afin d'améliorer la précision + de l'OCR et exécutez l'OCR sur des fichiers JPEG. Apprenez à extraire du texte avec + Aspose dans un tutoriel clair, étape par étape. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: fr +og_description: Prétraitez l'image pour l'OCR avec Aspose afin d'améliorer la précision + de l'OCR. Suivez ce guide pour exécuter l'OCR sur un JPEG et extraire le texte en + utilisant Aspose en C#. +og_title: Prétraiter l'image pour l'OCR – Tutoriel Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Prétraiter l'image pour l'OCR – Guide complet Aspose C# +url: /fr/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Prétraiter l'image pour l'OCR – Guide complet Aspose C# + +Vous vous êtes déjà demandé comment **prétraiter l'image pour l'OCR** afin que le texte soit toujours propre ? Vous n'êtes pas le seul — les développeurs luttent constamment contre des numérisations bruyantes, des JPEG à faible contraste et un éclairage imprévisible. La bonne nouvelle ? Avec quelques ajustements intelligents, vous pouvez **améliorer la précision de l'OCR** de façon spectaculaire, et Aspose rend cela indolore. + +Dans ce tutoriel, nous parcourrons un exemple concret qui vous montre comment **exécuter l'OCR sur des JPEG** , appliquer un pipeline de traitement d'image personnalisé, et enfin **extraire du texte avec Aspose**. À la fin, vous disposerez d'un extrait C# prêt à coller que vous pourrez intégrer dans n'importe quel projet .NET. + +## Ce que vous allez apprendre + +- Pourquoi le prétraitement est important et quels filtres offrent le meilleur gain. +- Comment configurer `ImageProcessingOptions` d’Aspose.OCR pour la correction d’inclinaison, la réduction du bruit, la binarisation et l’augmentation du contraste. +- Le code exact nécessaire pour **exécuter l'OCR sur des JPEG** et récupérer du texte propre. +- Astuces et pièges pour que votre pipeline OCR reste robuste en production. + +Aucune expérience préalable avec Aspose n'est requise ; il suffit d'une connaissance de base en C# et de Visual Studio (ou votre IDE préféré). Commençons. + +![Exemple de prétraitement d'image pour l'OCR](preprocess-ocr.png "Prétraitement d'image pour l'OCR") + +## Étape 1 : Configurer le moteur Aspose.OCR – Prétraiter l'image pour l'OCR + +Tout d'abord. Nous avons besoin d'une instance `OcrEngine` et nous devons lui indiquer la langue attendue. Dans la plupart des cas, l'anglais est la langue par défaut, mais vous pouvez le remplacer par le français, l'allemand, etc., en modifiant l'énumération `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Pourquoi c’est important :** Le moteur est le cœur de l’opération ; sans lui, vous ne pouvez appliquer aucun des filtres d’image qui **prétraitent l'image pour l'OCR**. Pensez-y comme à la cuisine où tous les ingrédients sont mélangés. + +## Étape 2 : Construire un pipeline de traitement d'image personnalisé – Améliorer la précision de l'OCR + +Voici la partie intéressante. Aspose vous permet d’enchaîner plusieurs filtres. Ci-dessous, nous activons quatre des plus efficaces : + +1. **Deskew** – redresse les documents inclinés (max 5° par défaut). +2. **Denoise** – lisse les arrière‑plans granuleux. +3. **Binarize** – convertit l'image en noir et blanc à l'aide d'un seuil. +4. **ContrastBoost** – fait ressortir les caractères faibles. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Astuce :** Si vos images sources sont déjà nettes, vous pouvez diminuer le `Strength` ou désactiver complètement un filtre. Un sur‑traitement peut parfois effacer les caractères faibles, alors expérimentez avec des échantillons réels. + +## Étape 3 : Charger le JPEG (ou toute image) et exécuter l'OCR – Exécuter l'OCR sur JPEG + +Aspose fonctionne avec tout format d'image que .NET peut lire — JPEG, PNG, BMP, etc. Voici comment fournir un fichier JPEG au moteur et lancer le processus de reconnaissance. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Pourquoi le JPEG ?** La compression JPEG introduit souvent des artefacts qui perturbent l'OCR. Notre pipeline de prétraitement, en particulier les étapes de débruitage et de binarisation, atténue ces problèmes, vous permettant d'**exécuter l'OCR sur JPEG** en toute confiance. + +## Étape 4 : Produire le texte reconnu – Extraire le texte avec Aspose + +Enfin, nous écrivons simplement le texte dans la console, un fichier ou tout service en aval. À des fins de démonstration, la console suffit. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Lorsque vous exécutez le programme, vous devriez voir quelque chose comme : + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Si la sortie semble brouillée, revenez à **l'étape 2** et ajustez les paramètres des filtres. De petits ajustements donnent souvent de grands gains en **améliorant la précision de l'OCR**. + +## Cas limites courants et comment les gérer + +| Situation | Ajustement suggéré | +|-----------|--------------------| +| **Images très sombres** | Augmenter `ContrastBoost.Level` à 1,5 ou plus. | +| **Inclinaison > 5°** | Augmenter `DeskewOptions.MaxAngle` (par ex., 10.0) ou pré‑faire pivoter l'image manuellement. | +| **Texte coloré sur fond coloré** | Utiliser `BinarizeOptions` avec un seuil personnalisé ou passer à `AdaptiveBinarizeOptions`. | +| **Fichiers volumineux ( > 5 Mo )** | Charger l'image dans un `MemoryStream` d'abord pour éviter les problèmes de verrouillage de fichier. | + +## Exemple complet fonctionnel – Toutes les étapes en un seul endroit + +Voici le programme complet, prêt à copier‑coller. Il compile avec .NET 6+ et ne nécessite que le package NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Enregistrez-le sous `Program.cs`, ajoutez le package Aspose.OCR (`dotnet add package Aspose.OCR`) et exécutez `dotnet run`. Vous verrez le texte nettoyé affiché dans la console. + +## Récapitulatif – Pourquoi cette approche fonctionne + +- **Prétraiter l'image pour l'OCR** : le pipeline élimine les sources d’erreur les plus courantes (inclinaison, bruit, faible contraste). +- **Améliorer la précision de l'OCR** : chaque filtre est réglé pour augmenter le rapport signal‑bruit perçu par le moteur. +- **Exécuter l'OCR sur JPEG** : même les images compressées deviennent lisibles après la correction d’inclinaison et la binarisation. +- **Extraire le texte avec Aspose** : la méthode `Recognize` renvoie une chaîne brute, prête pour toute logique en aval. + +Ensemble, ces étapes vous offrent une solution OCR fiable, de niveau production, en seulement quelques lignes. + +## Prochaines étapes et sujets associés + +- **Traitement par lots** – Parcourir un dossier d'images et écrire chaque résultat dans un fichier `.txt`. +- **Packs de langues** – Remplacer `OcrLanguage.English` par `OcrLanguage.Spanish` ou ajouter des dictionnaires personnalisés. +- **Extraction PDF** – Combiner Aspose.OCR avec Aspose.PDF pour extraire le texte directement des PDF numérisés. +- **Optimisation des performances** – Exécuter le moteur en parallèle avec `Parallel.ForEach` pour de gros volumes. + +N'hésitez pas à expérimenter avec les valeurs des filtres, essayer différents formats d'image, ou enchaîner des filtres Aspose supplémentaires comme `SharpnessOptions`. Le ciel est la limite une fois que vous avez maîtrisé les bases. + +--- + +*Bon codage ! Si vous rencontrez des problèmes, laissez un commentaire ci‑dessous et nous les résoudrons ensemble.* + +## Tutoriels associés + +- [Prétraiter l'image OCR avec les filtres Aspose.OCR pour .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/text-recognition/_index.md b/ocr/french/net/text-recognition/_index.md index 1b27348f2..a59d16b00 100644 --- a/ocr/french/net/text-recognition/_index.md +++ b/ocr/french/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Améliorez vos applications .NET avec Aspose.OCR pour une reconnaissance efficac 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. ### [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. +### [Reconnaître du texte à partir d'une image avec Aspose OCR – Guide complet C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Apprenez à extraire du texte d'images avec Aspose OCR en C#, étape par étape, pour des applications .NET performantes. +### [Comment utiliser l'OCR en C# – Reconnaître du texte chinois à partir d'un JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Découvrez comment extraire du texte chinois d'un fichier JPG avec Aspose.OCR en C#, étape par étape. +### [OCR du texte russe en C# – Guide complet avec Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Apprenez à extraire du texte russe d'images en C# avec Aspose OCR grâce à ce guide complet, étape par étape. +### [Extraire du texte à partir d'une image en C# – Guide complet Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Apprenez à extraire du texte d'images en C# avec Aspose OCR, guide complet étape par étape pour des applications .NET performantes. +### [Extraire du texte à partir d'une image dans ASP.NET Core Minimal API – Guide complet](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Apprenez à extraire du texte d'images en utilisant ASP.NET Core Minimal API, guide complet étape par étape pour des applications .NET performantes. +### [Tutoriel OCR C# : Extraire du texte à partir de reçus PNG avec Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Apprenez à extraire du texte de reçus au format PNG en utilisant Aspose OCR avec C# dans vos applications .NET. +### [Convertir le TIFF en texte en C# – Guide complet d’OCR par lots](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Apprenez à convertir des fichiers TIFF en texte avec Aspose.OCR en C#, traitement par lots simple et efficace. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/french/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..d9d3c3090 --- /dev/null +++ b/ocr/french/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-25 +description: Tutoriel C# OCR qui montre comment charger un fichier image C# et reconnaître + le texte PNG d’un reçu à l’aide d’Aspose OCR – guide étape par étape. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: fr +og_description: Tutoriel C# OCR qui vous guide à travers le chargement d’un fichier + image C# et la reconnaissance du texte PNG d’un reçu à l’aide d’Aspose OCR. +og_title: Tutoriel OCR C# – Extraire le texte des reçus PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# tutoriel OCR : Extraire le texte des reçus PNG avec Aspose' +url: /fr/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutoriel OCR c# – Extraire du texte des reçus PNG avec Aspose + +Vous avez déjà eu besoin d'un **c# OCR tutorial** qui fonctionne réellement sans passer des heures à googler ? Vous êtes au bon endroit. Dans ce guide, nous allons **load image file c#**, **recognize png text**, et **read receipt OCR** results, tout en vous montrant comment **perform OCR image** processing avec Aspose OCR. + +Nous commencerons par installer le package NuGet requis, parcourir chaque ligne de code, et terminer avec un dump JSON propre que vous pouvez acheminer directement dans votre prochain pipeline de données. Pas de fioritures, juste une solution pratique, prête à l'emploi. + +## Ce que vous apprendrez + +- Comment configurer Aspose OCR dans un projet .NET 6 (ou supérieur). +- Les étapes exactes pour **load an image file c#** et le transmettre au moteur. +- Comment **recognize png text** à partir d'une image de reçu et capturer le résultat. +- Moyens de **read receipt OCR** la sortie sous forme de JSON bien formaté. +- Conseils pour les opérations **perform OCR image** sur différents types de fichiers et la gestion des pièges courants. + +**Prérequis** +- Visual Studio 2022 (ou tout IDE de votre choix). +- .NET 6 SDK ou version plus récente. +- Une image de reçu PNG à portée de main (nous l'appellerons `receipt.png`). + +Si vous avez tout cela, plongeons‑nous dedans. + +![Capture d'écran du tutoriel OCR c#](ocr-demo.png "Résultat du tutoriel OCR c# affichant la sortie JSON") + +## Tutoriel OCR c# – Configuration du moteur Aspose OCR + +Tout d'abord, nous avons besoin de la bibliothèque Aspose OCR. Ouvrez votre terminal dans le dossier de la solution et exécutez : + +```bash +dotnet add package Aspose.OCR +``` + +### Pourquoi Aspose ? + +Aspose OCR prend en charge plus de 30 langues, fonctionne hors ligne, et renvoie un objet `OcrResult` riche—parfait pour les tâches **perform OCR image** où vous avez besoin de plus que du texte brut. + +## Charger un fichier image c# et préparer le reçu + +Maintenant que la bibliothèque est prête, chargeons **load image file c#**. La classe `System.Drawing.Image` fait le travail lourd, mais vous pouvez également utiliser `SkiaSharp` si vous préférez une alternative multiplateforme. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Astuce :** Enveloppez le `Image` dans une instruction `using` (comme indiqué) pour libérer rapidement les ressources natives—particulièrement important lorsque vous **perform OCR image** sur de nombreux fichiers dans une boucle. + +## Reconnaître le texte PNG avec Aspose + +Avec l'image en mémoire, le moteur peut maintenant **recognize png text**. Aspose renvoie un `OcrResult` qui contient à la fois la chaîne brute et des données détaillées sur chaque mot reconnu. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Pourquoi appeler `RecognizeWithResult` au lieu du plus simple `Recognize` ? Le premier vous donne accès aux scores de confiance, aux boîtes englobantes et aux sauts de ligne—pratique si vous devez plus tard **read receipt OCR** pour extraire les lignes d'articles. + +## Lire le résultat OCR du reçu au format JSON + +La plupart des systèmes en aval adorent le JSON, donc sérialisons le `OcrResult`. Le sérialiseur `System.Text.Json` gère les objets complexes avec élégance, et nous activerons l'indentation pour la lisibilité. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Le JSON résultant ressemble à ceci (troncé pour la brièveté) : + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Vous pouvez maintenant acheminer `jsonResult` vers une base de données, une file de messages, ou simplement l’enregistrer pour le débogage. + +## Effectuer le traitement d'image OCR et afficher la sortie + +Enfin, affichez le JSON dans la console. Dans une application réelle, vous écririez probablement dans un fichier ou l'enverriez via HTTP, mais la console facilite la vérification du bon fonctionnement. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Exécutez le programme (`dotnet run`) et vous devriez voir le JSON joliment formaté s'afficher. Si l'image du reçu est claire, le texte sera précis ; sinon, envisagez d'augmenter la résolution de l'image ou d'appliquer un filtre de prétraitement (par ex., niveaux de gris, amélioration du contraste) avant de le transmettre au moteur. + +### Gestion des cas limites courants + +| Situation | Que faire | +|-----------|------------| +| **Image floue** | Pré‑traiter avec `System.Drawing` pour affûter ou augmenter le DPI. | +| **Le reçu contient plusieurs langues** | Définir `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Traitement de gros lots** | Réutiliser une seule instance `OcrEngine` ; ne changer que le `Image` à chaque itération. | +| **Pression mémoire** | Libérer rapidement les objets `Image` et envisager `await Task.Run` pour les pipelines asynchrones. | + +Ces ajustements maintiennent votre flux de travail **perform OCR image** robuste même lorsque l'entrée n'est pas parfaite. + +## Conclusion + +Félicitations—vous venez de terminer un **c# OCR tutorial** qui charge une image, **recognizes png text**, et **reads receipt OCR** la sortie sous forme de JSON propre. Les étapes principales (configuration du moteur, chargement de l'image, exécution de l'OCR, sérialisation et affichage) constituent une base solide que vous pouvez étendre aux factures, passeports ou tout autre document numérisé. + +### Et après ? + +- Expérimentez avec **load image file c#** en utilisant `SkiaSharp` pour un véritable support multiplateforme. +- Plongez plus profondément dans `OcrResult.Words` pour extraire les lignes d'articles, les prix et les dates—parfait pour les applications de suivi des dépenses. +- Combinez ce tutoriel avec Azure Functions ou AWS Lambda pour créer une API de traitement de reçus sans serveur. + +N'hésitez pas à ajuster le code, ajouter plus d'images, ou même passer à un autre pack de langues. Le monde de l'OCR regorge de surprises, et vous avez maintenant les outils pour les explorer. + +Bon codage, et que vos reçus soient toujours lisibles ! + +## Tutoriels associés + +- [Extraire le texte d'image C# avec sélection de langue en utilisant Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extraire du texte d'image – Optimisation OCR avec Aspose.OCR pour .NET](/ocr/english/net/ocr-optimization/) +- [Comment utiliser l'OCR - Reconnaître une image sans détection de zone de texte](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/french/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..5f53dfd33 --- /dev/null +++ b/ocr/french/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-05-25 +description: Convertir les fichiers TIFF en texte avec Aspose.OCR en C#. Apprenez + la conversion d’images en texte par lots et extrayez efficacement le texte des fichiers + TIFF. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: fr +og_description: Convertissez les TIFF en texte avec Aspose.OCR. Ce guide montre la + conversion d’images en texte par lots et comment extraire le texte des fichiers + TIFF en quelques lignes de C#. +og_title: Convertir TIFF en texte en C# – Guide complet d'OCR par lots +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Convertir TIFF en texte en C# – Guide complet d’OCR par lots +url: /fr/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir TIFF en texte en C# – Guide complet d'OCR par lots + +Vous avez déjà eu besoin de **convertir TIFF en texte** sans savoir par où commencer ? Vous n'êtes pas seul — de nombreux développeurs rencontrent des difficultés avec l'OCR par lots lorsqu'ils traitent des documents numérisés. Dans ce tutoriel, nous allons parcourir une solution pratique qui **extrait le texte des fichiers TIFF** à l'aide d'Aspose.OCR, et nous le ferons en parallèle afin que les gros dossiers se terminent en quelques secondes. + +Nous aborderons également les meilleures pratiques de **conversion d'image en texte par lots**, de sorte qu'à la fin vous disposerez d'un extrait réutilisable qui transforme un répertoire complet d'images numérisées en fichiers *.txt* propres — parfaits pour l'indexation, la recherche ou l'alimentation d'analyses en aval. + +## Ce dont vous avez besoin + +- **.NET 6.0** ou ultérieur (le code se compile également sur .NET Framework) +- **Aspose.OCR for .NET** package NuGet (`Install-Package Aspose.OCR`) +- Un dossier contenant un ou plusieurs fichiers *.tif* (le format de numérisation TIFF classique) +- Votre IDE préféré (Visual Studio, VS Code, Rider—ce que vous préférez) + +C’est tout. Aucun service externe, aucune clé API, juste du pur C# et Aspose. + +![Capture d'écran d'un fichier TIFF en cours de traitement et du fichier texte résultant](/images/ocr-result.png "Résultat OCR montrant la sortie du TIFF converti en texte") + +* (Texte alternatif : Capture d'écran montrant la sortie du TIFF converti en texte à l'écran) + +## Étape 1 : Configurer le moteur OCR – Convertir TIFF en texte + +Tout d'abord, nous avons besoin d'une instance `OcrEngine` qui sait qu'elle doit lire les caractères anglais. Le moteur est le cœur de la conversion ; le configurer correctement garantit des résultats fiables. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Pourquoi c'est important :* +Aspose.OCR prend en charge des dizaines de langues. Si vous traitez des numérisations multilingues, il suffit de remplacer `OcrLanguage.English` par la valeur d'énumération appropriée. Laisser la langue non définie force le moteur en mode détection automatique, ce qui peut être plus lent et moins précis. + +## Étape 2 : Rassembler tous les fichiers TIFF – Extraire le texte du TIFF efficacement + +Ensuite, nous récupérons chaque fichier *.tif* d'un dossier que vous spécifiez. L'utilisation de `Directory.GetFiles` nous fournit un tableau propre que nous pouvons transmettre au processeur par lots. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Astuce :* Le drapeau `SearchOption.AllDirectories` peut être utilisé si vos numérisations sont imbriquées dans des sous‑dossiers. N'oubliez pas que la récursion plus profonde peut augmenter l'utilisation de la mémoire pendant l'étape par lots. + +## Étape 3 : Effectuer l'OCR en parallèle – Conversion d'image en texte par lots + +Passons maintenant à la partie amusante. Aspose.OCR fournit un helper statique `BatchOcr.RecognizeAll` qui accepte un tableau de chemins de fichiers, un moteur, et un indice de `parallelism`. Nous lancerons quatre threads, ce qui, sur un ordinateur portable quad‑core moderne, donne un gain de vitesse quasi linéaire. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Pourquoi le parallélisme ?* +Analyser un lot de TIFF haute résolution peut être très gourmand en CPU. En répartissant le travail sur plusieurs threads, nous gardons tous les cœurs occupés, réduisant considérablement le temps d'exécution total. Si vous exécutez cela sur un serveur avec davantage de cœurs, augmentez la valeur de `parallelism` en conséquence. + +## Étape 4 : Écrire la sortie – Convertir les images numérisées en fichiers TXT + +Enfin, nous parcourons le dictionnaire et écrivons chaque morceau de texte dans un fichier *.txt* qui partage le même nom de base que l'original. C’est le moment où **convertir des images numérisées en txt** devient une réalité. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Ce que fait le code, en français simple + +1. **Créer** un moteur OCR configuré pour l'anglais. +2. **Collecter** chaque fichier TIFF du dossier cible. +3. **Exécuter** `BatchOcr.RecognizeAll` avec quatre threads, transformant chaque image en chaîne de caractères. +4. **Parcourir** les résultats, en remplaçant l'extension `.tif` par `.txt` et en écrivant la chaîne sur le disque. + +C’est l’ensemble du flux de travail **convertir TIFF en texte** en moins de 50 lignes de code. + +## Gestion des cas particuliers – Quand les choses ne se passent pas bien + +- **TIFF manquants ou corrompus** – `BatchOcr` lèvera une `OcrException`. Enveloppez l’appel dans un `try / catch` si vous avez besoin d’une dégradation douce. +- **Documents non anglais** – changez `OcrLanguage.English` en `OcrLanguage.Spanish`, `OcrLanguage.French`, etc., ou utilisez `OcrLanguage.AutoDetect`. +- **Images très grandes** – envisagez de réduire le DPI avant l’OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) pour économiser de la mémoire, même si vous pouvez perdre un peu de précision. +- **Encodage de sortie** – si vous avez besoin d’une page de code spécifique (par ex., Windows‑1252), passez‑la à `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Astuces pro pour des conversions par lots robustes + +- **Journaliser les échecs** : créez une `List failedFiles` et ajoutez tout fichier qui lève une exception ; écrivez la liste dans un journal après la boucle. +- **Réutiliser le moteur** : la même instance `OcrEngine` peut être réutilisée pour de nombreux fichiers ; ne l’instanciez pas à l’intérieur de la boucle. +- **Valider le résultat** : un simple `if (string.IsNullOrWhiteSpace(extractedText))` peut signaler des numérisations vides ou illisibles. +- **Combiner avec PDF** : si votre source est un PDF multipage, convertissez chaque page en TIFF d’abord (Aspose.PDF le fait) puis lancez ce lot. + +## Prochaines étapes – Aller au-delà de la simple conversion + +Maintenant que vous pouvez **extraire le texte des fichiers TIFF** en masse, vous pourriez vouloir : + +- Alimenter les fichiers *.txt* dans un index de recherche (Elasticsearch, Azure Cognitive Search). +- Exécuter une détection de langue sur chaque résultat pour orienter les documents vers des pipelines spécifiques à la locale. +- Générer des PDF recherchables en superposant le texte OCR sur les images originales (Aspose.PDF à nouveau). + +Tous ces scénarios reposent sur la même idée centrale : **la conversion d'image en texte par lots** est un bloc de construction pour des systèmes de traitement de documents plus vastes. + +--- + +### Conclusion + +Vous venez d’apprendre comment **convertir TIFF en texte** avec Aspose.OCR, traiter un dossier complet en parallèle, et sauvegarder chaque résultat sous forme de fichier *.txt* propre. La solution est légère, entièrement configurable et prête pour la production—que vous numérisiez des factures anciennes, archiviez des contrats scannés ou alimentiez un moteur de recherche texte. + +Testez‑la, ajustez le parallélisme, et commencez à injecter ces nouveaux fichiers texte dans le workflow de votre choix. Bonne OCR ! + +--- + +## Tutoriels associés + +- [Extraire du texte d'images à l'aide de l'opération OCR sur dossiers](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extraire du texte d'image – Optimisation OCR avec Aspose.OCR pour .NET](/ocr/english/net/ocr-optimization/) +- [Extraire le texte d'image C# avec sélection de langue 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/french/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..5071aac0f --- /dev/null +++ b/ocr/french/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Apprenez à extraire du texte d’une image avec une API ASP.NET Core minimale. + Téléversez l’image via POST, lisez les données de formulaire multipart et effectuez + la reconnaissance optique de caractères (OCR) sur l’image. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: fr +og_description: Extraire du texte d’une image à l’aide d’une API ASP.NET Core minimale. + Ce guide montre comment télécharger une image via POST, lire les données de formulaire + multipart et effectuer la reconnaissance optique de caractères (OCR) sur l’image. +og_title: Extraire du texte d’une image dans ASP.NET Core – Étape par étape +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Extraire du texte d’une image dans une API minimale ASP.NET Core – Guide complet +url: /fr/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraire du texte d'une image avec ASP.NET Core Minimal API – Guide complet + +Vous êtes‑vous déjà demandé comment **extraire du texte d'une image** sans vous battre avec des frameworks lourds ? Vous n'êtes pas seul. De nombreux développeurs ont besoin d'une méthode rapide pour permettre aux utilisateurs de déposer une image et de récupérer les caractères bruts, que ce soit pour scanner des reçus, numériser des notes manuscrites ou alimenter un index de recherche. + +Dans ce tutoriel, nous créerons une petite ASP.NET Core Minimal API qui **télécharge une image via POST**, analyse la charge *multipart/form‑data*, puis **effectue une OCR sur l'image** à l'aide d'un singleton `OcrEngine`. À la fin, vous disposerez d'une application entièrement fonctionnelle que vous pourrez intégrer à n'importe quel projet .NET 8 et commencer à extraire du texte d'une image immédiatement. + +## Ce que vous allez construire + +- Une application web minimale qui écoute sur `/ocr`. +- Un point de terminaison qui accepte un fichier image envoyé avec une requête POST `multipart/form-data`. +- Une logique qui lit le fichier téléchargé, le transmet au moteur OCR et renvoie les résultats en texte brut. +- Extrait de code optionnel d'accélération GPU (commenté) pour ceux disposant d'une carte compatible. + +**Prérequis** +- .NET 8 SDK (ou ultérieur). +- Familiarité de base avec C# et la ligne de commande. +- Une bibliothèque OCR qui expose une classe `OcrEngine` (l'exemple suppose un package NuGet hypothétique). + +Si vous avez tout cela, plongeons‑y. + +## Étape 1 : Configurer le projet et ajouter le package OCR + +Tout d'abord, créez un nouveau projet web et ajoutez la bibliothèque OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Astuce :** Gardez vos dépendances à jour. Les versions plus récentes offrent souvent des gains de performance, notamment pour l'inférence accélérée par GPU. + +## Étape 2 : Enregistrer un moteur OCR singleton (service principal) + +Nous voulons une seule instance de `OcrEngine` pour toute l'application — pas besoin de créer un nouveau moteur à chaque requête. Enregistrez‑le dans le conteneur de services du builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Pourquoi un singleton ?** +Créer un moteur OCR peut être coûteux — pensez au chargement des poids du réseau neuronal en mémoire. En réutilisant la même instance, nous économisons à la fois des cycles CPU et de la RAM, ce qui se traduit par des temps de réponse plus rapides pour chaque appel `/ocr`. + +## Étape 3 : Construire l'application + +Nous matérialisons maintenant l'objet `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Cette ligne semble presque magique, mais en coulisses elle configure le routage, le middleware et le conteneur d’injection de dépendances que nous venons de configurer. + +## Étape 4 : Définir le point de terminaison POST – « Télécharger une image via POST » + +Voici le cœur du tutoriel : un point de terminaison qui **télécharge une image via POST**, lit la charge multipart et transmet les données au moteur OCR. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Décomposition de la logique + +| Étape | Ce qui se passe | Pourquoi c’est important | +|------|------------------|---------------------------| +| **ReadFormAsync** | Analyse la requête *multipart/form-data* entrante. | Sans cela, vous ne pouvez pas accéder aux fichiers téléchargés. | +| **form.Files["image"]** | Récupère le fichier dont le nom du champ de formulaire est `image`. | Garantit un contrat prévisible pour les appelants. | +| **Content‑type check** | Vérifie que le fichier est une image (par ex., `image/png`). | Empêche le moteur OCR de planter avec des données non‑image. | +| **Image.FromStream** | Convertit le flux brut en un `System.Drawing.Image`. | La bibliothèque OCR attend un objet `Image`, pas un tableau d'octets brut. | +| **ocr.Recognize(img)** | Appelle le moteur OCR pour **reconnaître le texte à partir de l'image**. | C’est l’étape principale pour **effectuer l’OCR sur l’image**. | +| **Results.Text** | Renvoie la réponse en texte brut. | Un format simple et exploitable pour les services en aval. | + +## Étape 5 : Exécuter l'API + +Enfin, démarrez le serveur web. + +```csharp +app.Run(); +``` + +Lorsque vous exécutez `dotnet run`, l'API écoutera sur `http://localhost:5000` (ou le port de votre choix). Vous pouvez la tester avec `curl` : + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Sortie attendue :** La console affichera les caractères reconnus, par ex. : + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Si l'image est floue ou que la langue n’est pas prise en charge, le moteur OCR renverra une chaîne vide ou un message d’erreur — gérez ces cas dans le code de production. + +## Cas limites & bonnes pratiques + +### 1. Fichiers volumineux + +La limite par défaut du corps de la requête est de 30 Mo. Pour des scans plus grands, vous pourriez devoir l’ajuster : + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR asynchrone + +Certaines bibliothèques OCR exposent des méthodes asynchrones (`RecognizeAsync`). Si la vôtre le fait, remplacez `ocr.Recognize(img)` par `await ocr.RecognizeAsync(img)` et marquez le lambda comme `async`. + +### 3. Considérations de sécurité + +- **Validez la taille du fichier** avant de le charger en mémoire. +- **Sanitisez le nom de fichier** si vous l’écrivez jamais sur le disque. +- **Limitez le taux** du point de terminaison pour éviter les attaques par déni de service. + +### 4. Accélération GPU + +Si vous décommentez la ligne `engine.GpuDevice = new GpuDevice(0);` et que votre matériel prend en charge CUDA ou DirectML, vous constaterez une amélioration de vitesse notable, surtout sur des images haute résolution. + +## Exemple complet fonctionnel + +Voici le `Program.cs` complet que vous pouvez copier‑coller dans un nouveau projet Minimal API. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Enregistrez, exécutez `dotnet run`, et vous êtes prêt à **extraire du texte d'une image** à la demande. + +## Conclusion + +Nous avons parcouru une **solution complète, de bout en bout** pour extraire du texte d'une image avec ASP.NET Core Minimal API. En partant de la structure du projet, nous **avons enregistré un moteur OCR singleton**, construit un point de terminaison qui **télécharge une image via POST**, **lit les données multipart du formulaire**, et enfin **effectue l’OCR sur l’image** pour renvoyer du texte brut propre. + +À partir d'ici, vous pouvez : + +- Ajouter des enveloppes JSON pour des réponses plus riches. +- Brancher une base de données pour stocker le texte extrait. +- Étendre le support à plusieurs langues (`OcrLanguage.Spanish`, etc.). + +Le modèle s’adapte bien — il suffit d’insérer le même point de terminaison dans un microservice plus grand ou de l’exposer derrière une passerelle API. + +Des questions sur la gestion des PDF, le traitement par lots ou l’optimisation GPU ? Laissez un commentaire, et bon codage ! + +## Tutoriels associés + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/french/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..6d9603d57 --- /dev/null +++ b/ocr/french/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-05-25 +description: Extraire du texte d’une image avec C# et Aspose OCR. Apprenez comment + convertir un JPG en texte, charger une image pour l’OCR et obtenir des résultats + fiables rapidement. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: fr +og_description: Extraire du texte d’une image avec C#. Ce guide montre comment convertir + un JPG en texte, charger une image pour l’OCR et gérer le contenu multilingue. +og_title: Extraire du texte d’une image en C# – Tutoriel OCR Aspose +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Extraire du texte d’une image en C# – Guide complet d’Aspose OCR +url: /fr/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraire du texte d'une image en C# – Guide complet Aspose OCR + +Vous êtes-vous déjà demandé comment **extraire du texte d'une image** en utilisant du simple code C# ? Vous n'êtes pas le seul. Que vous numérisiez des reçus, scanniez des panneaux ou soyez simplement curieux à propos de l’OCR, la capacité de récupérer des caractères à partir d’une photo est une compétence très pratique. Dans ce tutoriel, nous parcourrons un exemple complet, exécutable, qui montre exactement comment **extraire du texte d'une image** avec Aspose.OCR, et nous aborderons également comment **convertir jpg en texte**, **charger une image pour l’OCR**, et répondre une bonne fois pour toutes à la question classique « **comment OCR une image** ». + +À la fin de ce guide, vous disposerez d’une application console autonome qui lit un fichier JPEG, reconnaît l’ukrainien (ou toute autre langue prise en charge) et affiche le résultat dans la console. Pas de références vagues, pas de pièces manquantes — juste une solution complète que vous pouvez copier‑coller et exécuter. + +--- + +## Ce que vous allez apprendre + +* Comment installer le package NuGet Aspose.OCR. +* Le code exact nécessaire pour **charger une image pour l’OCR** en C#. +* Comment définir la langue et réellement **extraire du texte d'une image**. +* Astuces pour **convertir jpg en texte** efficacement. +* Pièges courants et comment les éviter. + +Si vous avez déjà un environnement de développement .NET configuré, vous êtes prêt à plonger. Sinon, la section prérequis ci‑dessous vous mettra à niveau. + +--- + +## Prérequis + +| Prérequis | Pourquoi c’est important | +|-----------|---------------------------| +| .NET 6.0 SDK (ou version supérieure) | Fournit le runtime pour l’application console. | +| Visual Studio 2022 ou VS Code | Facilite l’édition et le débogage. | +| Connexion Internet (première exécution) | NuGet doit télécharger Aspose.OCR. | +| Une image JPEG à traiter (par ex. `ukrainian_sign.jpg`) | Le fichier source pour le moteur OCR. | + +> **Astuce :** Si vous êtes sous Linux ou macOS, le même code fonctionne avec la CLI .NET (`dotnet new console`), vous pouvez donc ignorer l’IDE lourd. + +--- + +## Étape 1 – Installer Aspose.OCR via NuGet + +Ouvrez votre terminal (ou la console du gestionnaire de packages) et exécutez : + +```bash +dotnet add package Aspose.OCR +``` + +Cette unique ligne récupère les derniers binaires Aspose.OCR ainsi que toutes les dépendances transitives. Aucun DLL à manipuler manuellement. + +--- + +## Étape 2 – Créer le moteur OCR (le cœur de l’extraction) + +Une fois la bibliothèque en place, nous pouvons créer une instance de `OcrEngine`. Cet objet est responsable de **extraire du texte d'une image**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Pourquoi c’est important :** Le moteur encapsule les algorithmes OCR, les modèles linguistiques et les options de configuration. L’instancier une fois et le réutiliser pour plusieurs images est à la fois économique en mémoire et rapide. + +--- + +## Étape 3 – Charger l’image pour l’OCR (et définir la langue) + +L’étape suivante consiste à indiquer au moteur quelle image lire. C’est ici que la phrase **charger une image pour l’OCR** prend tout son sens. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Cas limite :** Si le fichier n’existe pas, `Image.FromFile` lève une `FileNotFoundException`. Enveloppez l’appel dans un bloc try‑catch pour le code de production. + +--- + +## Étape 4 – Effectuer l’OCR et extraire le texte + +Avec l’image chargée, le moteur peut maintenant **extraire du texte d'une image**. La méthode `Recognize` fait le gros du travail. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Si tout se passe bien, `recognizedText` contiendra la représentation texte brut de tout ce que le moteur OCR a pu lire. + +--- + +## Étape 5 – Convertir JPG en texte (assembler le tout) + +Le code que nous avons construit jusqu’ici **convertit déjà jpg en texte**, mais encapsulons‑le dans une méthode propre que vous pourrez appeler à plusieurs reprises. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Vous pouvez alors simplement faire : + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Sortie attendue** (troncature pour la brièveté) : + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Si l’image contient du texte anglais, changez `OcrLanguage.English` et vous verrez la sortie correspondante. + +--- + +## Étape 6 – Gérer les questions fréquentes « Comment OCR une image » + +### 6.1 Puis‑je OCR un PNG ou BMP ? + +Absolument. La méthode `Image.FromFile` prend en charge tous les formats reconnus par System.Drawing, il suffit donc de pointer le chemin vers un fichier `.png` ou `.bmp` et le reste du code reste identique. + +### 6.2 Que faire si l’image est de basse résolution ? + +La précision de l’OCR chute drastiquement en dessous de 300 dpi. Une solution rapide consiste à agrandir l’image avec `Graphics` avant de la transmettre au moteur : + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Ai‑je besoin d’une licence pour Aspose.OCR ? + +Aspose propose un essai gratuit avec filigrane. Pour une utilisation en production, achetez une licence et ajoutez : + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Exemple complet fonctionnel + +Voici une application console complète, prête à être exécutée, qui démontre **comment OCR une image**, **charger une image pour l’OCR**, et **convertir jpg en texte** dans un seul paquet élégant. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Comment l’exécuter** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Vous devriez voir le texte extrait affiché dans la console, confirmant que vous avez réussi à **extraire du texte d'une image** avec C#. + +--- + +## Pièges courants & Astuces pro + +| Problème | Pourquoi cela se produit | Solution | +|----------|--------------------------|----------| +| Sortie vide | Image trop sombre ou contraste faible. | Pré‑traiter avec `Bitmap` pour augmenter la luminosité. | +| Mauvaise langue | Propriété `Language` laissée sur l’anglais par défaut. | Définissez explicitement `ocrEngine.Language = OcrLanguage.Ukrainian;` (ou votre cible). | +| Erreur de mémoire | Images très volumineuses chargées sans libération. | Enveloppez `Image.FromFile` dans un bloc `using` (comme montré). | +| Filigrane de licence | Exécution en version d’essai sans licence. | Appliquez une licence achetée dès le début du `Main`. | + +--- + +## Conclusion + +Nous venons de couvrir tout ce dont vous avez besoin pour **extraire du texte d'une image** en C# — de l’installation d’Aspose.OCR, **charger une image pour l’OCR**, à **convertir jpg en texte** et gérer les scénarios multilingues. Le programme d’exemple complet assemble tous les éléments, vous offrant une base fiable pour tout projet lié à l’OCR. + +Ensuite, vous pourriez explorer : + +* **Comment OCR une image** à partir de flux plutôt que de fichiers (utilisez `MemoryStream`). +* Ajouter du post‑traitement **c# image to text** comme la correction orthographique. +* Intégrer l’étape OCR dans un pipeline plus large (par ex. stocker les résultats dans une base de données). + +N’hésitez pas à expérimenter avec différentes langues, formats d’image et astuces de pré‑traitement. L’OCR est autant un art qu’une science, et plus vous jouez, meilleurs seront les résultats. + +Bon codage, et que vos images soient toujours lisibles ! + +## Tutoriels associés + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/french/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..740d76f06 --- /dev/null +++ b/ocr/french/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Comment utiliser l'OCR en C# pour extraire du texte à partir de fichiers + image. Apprenez à reconnaître les caractères chinois à partir d'un JPG en utilisant + Aspose.OCR en quelques étapes simples. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: fr +og_description: Comment utiliser l'OCR en C# pour extraire du texte à partir de fichiers + image. Ce guide vous montre comment reconnaître les caractères chinois à partir + d'un JPG en utilisant Aspose.OCR. +og_title: Comment utiliser l'OCR en C# – Reconnaître le texte chinois à partir d'un + JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Comment utiliser l'OCR en C# – Reconnaître le texte chinois à partir d’un JPG +url: /fr/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Comment utiliser l’OCR en C# – Reconnaître du texte chinois depuis un JPG + +Vous êtes-vous déjà demandé **comment utiliser l’OCR** pour extraire des mots d’une photo que vous avez prise avec votre téléphone ? Vous n’êtes pas seul. Dans de nombreux projets réels—pensez aux scanners de reçus, aux applications de traduction ou à la saisie automatisée de données—vous aurez besoin d’**extraire du texte depuis une image** rapidement et de manière fiable. + +Dans ce tutoriel, nous allons parcourir un exemple complet et exécutable qui **reconnaît le texte depuis des fichiers JPG** et gère même le cas délicat de **reconnaître des caractères chinois** en utilisant le pack linguistique **OCR Chinese Simplified**. À la fin, vous disposerez d’une application console autonome qui affiche la chaîne détectée dans la console, sans téléchargements manuels supplémentaires. + +> **Note rapide :** Le code fonctionne avec Aspose.OCR ≥ 23.7, qui télécharge automatiquement les ressources linguistiques lors de la première utilisation. Si vous utilisez une version antérieure, vous devrez ajouter la langue manuellement. + +## Prérequis + +Avant de commencer, assurez-vous d’avoir : + +- Le SDK .NET 6.0 ou une version ultérieure (l’exemple cible .NET 6, mais .NET 5 fonctionne également) +- Une version récente de Visual Studio 2022 ou VS Code avec l’extension C# +- Une connexion Internet pour le premier téléchargement de la langue +- Une image JPG contenant du texte chinois simplifié (nous l’appellerons `chinese_sign.jpg`) + +C’est tout—pas de moteurs OCR lourds, pas de manipulation de DLL natives. Juste quelques commandes NuGet et quelques lignes de code. + +## Étape 1 : Installer Aspose.OCR via NuGet + +Première chose à faire : nous avons besoin de la bibliothèque OCR. Ouvrez un terminal dans le dossier de votre projet et exécutez : + +```bash +dotnet add package Aspose.OCR +``` + +Ou, si vous préférez l’interface Visual Studio, faites un clic droit sur **Dependencies → Manage NuGet Packages**, recherchez “Aspose.OCR”, puis cliquez sur **Install**. + +> **Astuce :** Gardez vos packages à jour. De nouveaux packs linguistiques et des améliorations de performances arrivent à chaque version mineure. + +## Étape 2 : Créer un nouveau projet console (si vous ne l’avez pas encore fait) + +Si vous partez de zéro, créez une nouvelle application console : + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Vous avez maintenant un fichier `Program.cs` prêt pour le code OCR. + +## Étape 3 : Écrire le code OCR – Reconnaître le chinois simplifié depuis un JPG + +Ouvrez `Program.cs` et remplacez son contenu par ce qui suit. Chaque ligne est commentée afin que vous puissiez voir *pourquoi* nous faisons chaque étape, pas seulement *quoi* nous faisons. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Que se passe-t-il en coulisses ? + +- **`OcrEngine.Language`** indique à Aspose quel dictionnaire utiliser. En choisissant `ChineseSimplified`, nous demandons au moteur de charger le pack linguistique chinois simplifié. +- **Téléchargement initial** : lorsque `Recognize` s’exécute, le SDK contacte le CDN d’Aspose, télécharge le fichier linguistique d’environ 6 Mo, le met en cache localement, puis poursuit l’OCR. Les appels suivants sont instantanés. +- **`Image.FromFile`** fonctionne avec n’importe quel format raster que .NET peut décoder—JPG, PNG, BMP—vous permettant ainsi d’**extraire du texte depuis une image** de nombreux types, pas seulement JPG. + +## Étape 4 : Exécuter l’application et vérifier la sortie + +Compilez et lancez : + +```bash +dotnet run +``` + +Vous devriez voir quelque chose comme : + +``` +=== Recognized Text === +欢迎光临 +``` + +Si la console affiche du texte illisible ou une chaîne vide, revérifiez : + +1. L’image contient bien des caractères chinois clairs et à fort contraste. +2. Le chemin du fichier est correct (pas d’espaces superflus ou d’extensions manquantes). +3. Votre machine peut accéder à `https://download.aspose.com` pour le pack linguistique. + +## Étape 5 : Gestion des cas limites et des pièges courants + +### 5.1 Traiter des images de mauvaise qualité + +La précision de l’OCR diminue lorsque l’image source est floue, bruitée ou mal éclairée. Une solution rapide consiste à pré‑traiter l’image : + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Exécution dans un environnement sans interface graphique + +Si vous déployez dans un conteneur Linux sans GUI, assurez‑vous que la bibliothèque `libgdiplus` (requise par `System.Drawing`) est installée : + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Mettre en cache le pack linguistique manuellement + +Vous pouvez télécharger le fichier linguistique une fois et indiquer à Aspose son emplacement via l’API `License`, ce qui élimine l’appel réseau unique. Cela est pratique pour les scénarios hors ligne. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Exemple complet (tout‑en‑un) + +Voici le programme *complet* que vous pouvez copier‑coller dans `Program.cs`. Aucun morceau caché, aucun script externe. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Sortie attendue + +Si le JPG contient la phrase « 欢迎光临 », la console affichera : + +``` +=== Recognized Text === +欢迎光临 +``` + +N’hésitez pas à remplacer l’image par tout autre signe, nom de rue ou étiquette produit en chinois simplifié — le moteur fera de son mieux. + +## Conclusion + +Nous venons de voir **comment utiliser l’OCR** en C# pour **extraire du texte depuis une image**, en abordant spécifiquement le défi de **reconnaître des caractères chinois** dans un **JPG**. En tirant parti du téléchargement à la volée du pack linguistique d’Aspose.OCR, vous pouvez garder votre déploiement léger tout en supportant **OCR Chinese Simplified** dès le départ. + +Et après ? Essayez ces idées : + +- **Traitement par lots** : parcourez un dossier d’images et écrivez chaque résultat dans un CSV. +- **Combinaison avec des API de traduction** : transmettez la chaîne reconnue à Azure Translator pour des applications multilingues en temps réel. +- **Explorer d’autres langues** : remplacez `OcrLanguage.ChineseSimplified` par `Japanese` ou `Arabic` et voyez comment le même code s’adapte. + +Des questions sur l’optimisation des performances, la licence ou l’intégration de l’OCR dans un service web ? Laissez un commentaire ci‑dessous—bon codage ! + +--- + +![Capture d’écran de la sortie console montrant comment utiliser l’OCR en C# pour reconnaître du texte chinois depuis une image JPG](ocr-chinese-demo.png "sortie console de l’utilisation de l’OCR") + + +## Tutoriels associés + +- [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/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/french/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/french/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..6b27f48ec --- /dev/null +++ b/ocr/french/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Apprenez à effectuer la reconnaissance optique de caractères (OCR) du + texte russe en C# et à extraire le texte d’une image avec Aspose OCR. Code étape + par étape pour convertir rapidement une image en texte C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: fr +og_description: OCR du texte russe en C# simplifié. Apprenez à extraire du texte d’une + image, à convertir une image en texte avec C#, et à charger une image pour l’OCR + avec Aspose OCR. +og_title: OCR du texte russe en C# – Guide complet d'Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR du texte russe en C# – Guide complet utilisant Aspose OCR +url: /fr/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR texte russe en C# – Guide complet avec Aspose OCR + +Vous avez déjà eu besoin d’OCR du texte russe en C# sans savoir quelle bibliothèque choisir ? Vous n’êtes pas seul. Extraire des caractères lisibles à partir d’une image cyrillique peut ressembler à décoder des messages secrets—surtout si le bon modèle de langue n’est pas configuré. + +Dans ce tutoriel, nous allons parcourir un exemple pratique qui montre comment **extraire du texte d’une image**, convertir *image en texte C#*, et gérer les subtilités de la reconnaissance du russe avec Aspose OCR. À la fin, vous disposerez d’une application console prête à l’emploi qui charge une image pour l’OCR, affiche la chaîne reconnue, et vous offre une base solide pour des scénarios plus avancés. + +## Ce que vous allez apprendre + +- Comment installer et configurer **Aspose OCR C#** pour la prise en charge du russe. +- Les étapes exactes pour **charger l’image pour l’OCR** et appeler le moteur. +- Astuces pour gérer les pièges courants comme les ressources linguistiques manquantes ou les scans flous. +- Moyens d’étendre la solution, par exemple le traitement par lots de plusieurs fichiers ou l’ajustement des seuils de confiance. + +Aucune expérience préalable avec Aspose n’est requise ; une connaissance de base de C# et .NET suffit. + +## Prérequis + +Avant de commencer, assurez‑vous de disposer de : + +1. **.NET 6.0** (ou version ultérieure) SDK installé – le code fonctionne aussi bien sur .NET Core que sur .NET Framework. +2. **Visual Studio 2022** (ou tout autre IDE de votre choix). +3. Un package NuGet **Aspose.OCR for .NET** – vous pouvez obtenir une clé d’essai gratuite sur le site d’Aspose. +4. Un fichier de modèle de langue russe (`rus.traineddata`) – téléchargez‑le depuis la page de ressources Aspose et placez‑le dans un dossier que vous référencerez plus tard. +5. Une image d’exemple (`russian_doc.png`) contenant du texte cyrillique clair. + +Tout est‑t‑il prêt ? Parfait—c’est parti. + +## Étape 1 : Créer le projet et installer Aspose OCR + +Tout d’abord, créez un nouveau projet console : + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Installez maintenant le package Aspose OCR : + +```bash +dotnet add package Aspose.OCR +``` + +> **Astuce pro** : si vous utilisez une licence d’essai, gardez le fichier `Aspose.Total.lic` à portée de main ; vous le chargerez dans le code pour éviter les filigranes. + +Une fois le package installé, ouvrez `Program.cs`. Vous verrez la méthode `Main` par défaut—remplacez son contenu par le squelette que nous allons construire. + +## Étape 2 : Configurer le moteur OCR pour la langue russe + +Le cœur de l’opération est l’objet `OcrEngine`. Nous devons lui indiquer deux choses : quelle langue reconnaître et où se trouvent les fichiers de modèle linguistique. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Pourquoi c’est important** : si vous omettez `Language = OcrLanguage.Russian`, le moteur utilise l’anglais par défaut, et les caractères cyrilliques apparaissent comme des symboles illisibles. `ResourceFolder` pointe vers le répertoire contenant le fichier `rus.traineddata` ; sans cela, Aspose lève une exception *resource not found*. + +## Étape 3 : Charger l’image pour l’OCR + +Nous devons maintenant **charger l’image pour l’OCR**. Aspose OCR travaille avec `System.Drawing.Image`, vous pouvez donc fournir n’importe quel format supporté (PNG, JPEG, BMP, etc.). Assurez‑vous que le chemin du fichier est correct ; les chemins relatifs fonctionnent tant que l’image reste à côté de l’exécutable. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Cas particulier** : si l’image est volumineuse (plus de 5 Mo) vous pourriez la réduire d’abord. La précision de l’OCR chute quand le DPI est trop bas, mais les gros fichiers peuvent entraîner une pression mémoire. Un redimensionnement rapide peut être effectué avec `Graphics` si besoin. + +## Étape 4 : Reconnaître le texte – De l’image au texte C# style + +Avec le moteur configuré et l’image chargée, la reconnaissance réelle ne nécessite qu’un appel unique : + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Lorsque vous exécutez le programme (`dotnet run`), vous devriez voir quelque chose comme : + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Si la sortie ressemble à du charabia, revérifiez que : + +- Le fichier `rus.traineddata` est présent dans `ResourceFolder`. +- L’image n’est pas trop floue ; pensez à appliquer un filtre de binarisation simple avant l’OCR. +- Le paramètre de langue est bien `OcrLanguage.Russian`. + +## Étape 5 : Ajustements fins et pièges courants + +### Ajuster le seuil de confiance + +Aspose OCR renvoie une valeur de confiance par caractère en interne. Bien que l’API ne l’expose pas directement, vous pouvez activer **la sortie détaillée** pour voir quels mots ont une faible confiance : + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Si vous constatez des erreurs fréquentes, essayez : + +- **Pré‑traitement** : convertir l’image en niveaux de gris, augmenter le contraste, ou appliquer un filtre médian. +- **Paramètres DPI** : assurez‑vous que l’image fait au moins 300 DPI pour les scripts cyrilliques. + +### Traitement par lots de plusieurs images + +Si vous devez **extraire du texte d’images** en masse, encapsulez la logique de reconnaissance dans une boucle : + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Chaque PNG obtient alors son propre fichier `.txt`—pratique pour l’archivage de documents. + +### Gestion de la sortie Unicode + +Les caractères cyrilliques sont Unicode, assurez‑vous que votre console utilise le bon encodage : + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Placez cette ligne juste après le démarrage de la méthode `Main`. Sans elle, vous pourriez voir des points d’interrogation (`?`) à la place des lettres russes. + +## Exemple complet fonctionnel + +Voici le code complet, prêt à être exécuté. Copiez‑collez‑le dans `Program.cs`, ajustez les chemins, et le tour est joué. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Sortie attendue** (en supposant que l’image d’exemple contient « Пример текста на русском языке. ») : + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Si vous obtenez autre chose, revenez aux conseils de dépannage de l’Étape 5. + +## Conclusion + +Vous disposez maintenant d’un exemple complet, de bout en bout, pour **ocr texte russe** en C# avec Aspose OCR. De l’installation de la bibliothèque, la configuration du modèle de langue russe, au chargement d’une image et à sa conversion en texte Unicode propre, chaque étape est couverte. + +Rappelez‑vous, la clé d’un OCR fiable réside dans la qualité de la source : polices claires, DPI suffisant, et ressources linguistiques adéquates. Une fois les bases maîtrisées, vous pouvez passer au traitement par lots, à l’intégration avec le stockage cloud, ou même combiner avec un post‑traitement IA pour la correction orthographique. + +### Et après ? + +- Explorez les options avancées **aspose ocr c#** comme l’analyse de mise en page ou la sortie PDF. +- Combinez cela avec des flux de travail **extract text from image** dans Azure Functions pour un traitement serverless. +- Essayez d’autres langues—il suffit de remplacer `OcrLanguage.Russian` par `OcrLanguage.English` ou un autre code supporté. + +Des questions ou une image récalcitrante ? Laissez un commentaire ci‑dessous, et bon codage ! + +![ocr russian text example](ocr-russian-example.png){alt="exemple de texte OCR russe"} + +## Tutoriels associés + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/french/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..6dfc013ec --- /dev/null +++ b/ocr/french/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-25 +description: Reconnaître le texte d’une image avec Aspose OCR en C#. Apprenez comment + charger une image pour l’OCR, définir la langue de l’OCR, créer le moteur OCR et + extraire le texte d’un fichier TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: fr +og_description: Reconnaître le texte d’une image avec Aspose OCR en C#. Ce tutoriel + montre comment créer un moteur OCR, charger une image pour l’OCR, définir la langue + OCR et extraire le texte d’un fichier TIFF. +og_title: Reconnaître le texte à partir d'une image avec Aspose OCR – Guide complet + C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Reconnaître le texte à partir d'une image avec Aspose OCR – Guide complet C# +url: /fr/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Reconnaître du texte à partir d'une image avec Aspose OCR – Guide complet C# + +Vous avez déjà eu besoin de **reconnaître du texte à partir d'une image** mais vous ne saviez pas quelle bibliothèque vous offrirait à la fois rapidité et précision ? Vous n'êtes pas seul. Dans de nombreux projets de traitement de factures ou d'archivage, le principal problème est d'obtenir du texte propre et interrogeable à partir de fichiers TIFF sans écrire un analyseur personnalisé. + +Voici le point : Aspose OCR pour .NET rend toute cette chaîne de traitement un jeu d'enfant. Dans ce guide, nous passerons en revue tout ce dont vous avez besoin — installation du package, **création du moteur OCR**, chargement d'un TIFF, définition de la langue OCR, et enfin **extraction du texte d'un TIFF**. À la fin, vous disposerez d’une application console prête à l’emploi qui peut **reconnaître du texte à partir d'une image** en un clin d’œil. + +## Prérequis + +- .NET 6.0 ou version ultérieure (le code fonctionne également avec .NET Core et .NET Framework) +- Visual Studio 2022 (ou tout autre IDE de votre choix) +- Package NuGet Aspose.OCR (le support GPU nécessite le module additionnel `Aspose.OCR.Gpu`) +- Un GPU avec support CUDA si vous voulez la vitesse supplémentaire (optionnel mais recommandé) + +> **Astuce :** Si vous n’avez pas de GPU, il suffit d’omettre la ligne `GpuDevice` et le moteur reviendra automatiquement sur le CPU. + +## Étape 1 : Installer Aspose OCR et créer le moteur OCR + +First, add the necessary packages via NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Now we can **create OCR engine**. This object is the heart of the process; it holds configuration such as the device to run on and memory limits. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Why this matters:** By binding the engine to a GPU you dramatically cut down the time it takes to **recognize text from image**, especially for large batches of high‑resolution TIFFs. + +## Étape 2 : Charger l'image pour l'OCR + +Next, we need to **load image for OCR**. Aspose.OCR works with `System.Drawing.Image`, so any format supported by GDI+ (including multi‑page TIFF) is fine. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +If you’re dealing with a multi‑page TIFF you can loop through the pages using `image.SelectActiveFrame`, but for most scenarios a single call is enough. + +## Étape 3 : Définir la langue OCR + +The engine doesn’t magically know which language you’re scanning. **Set OCR language** before you run the recognizer; otherwise you’ll get a lot of garbled output. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Le saviez‑vous ?** Changer de langue à l’exécution est peu coûteux — vous pouvez même traiter un document multilingue en modifiant cette propriété entre les pages. + +## Étape 4 : Effectuer la reconnaissance – Reconnaître du texte à partir d'une image + +Now the fun part: actually **recognize text from image**. The `Recognize` method returns a plain string with all detected characters. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +If you need confidence scores or bounding boxes you can use the overload that returns an `OcrResult` object, but for most extraction tasks the plain string is sufficient. + +## Étape 5 : Extraire le texte d'un TIFF (et gérer les fichiers multi‑pages) + +When the source is a TIFF containing several pages, you’ll want to repeat steps 2‑4 for each frame. Here’s a quick loop that **extracts text from TIFF** page by page: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +The code above prints the extracted text for every page, making it trivial to pipe the results into a database or a search index. + +## Étape 6 : Afficher ou enregistrer le texte extrait + +Finally, let’s **display the extracted text** and optionally write it to a file for later processing. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Running the program should output the recognized characters and create `extracted_text.txt` beside your source TIFF. + +--- + +## Questions fréquentes et cas limites + +- **Et si mon GPU n’est pas détecté ?** + Supprimez la ligne `GpuDevice` ; le moteur basculera automatiquement en mode CPU. Les performances seront plus lentes, mais les résultats resteront précis. + +- **Puis‑je traiter des fichiers PNG ou JPEG ?** + Absolument — `Image.FromFile` fonctionne avec tout format pris en charge par System.Drawing, vous pouvez donc **load image for OCR** quel que soit l’extension. + +- **Comment gérer les scans à basse résolution ?** + Augmentez `ocrEngine.PreprocessOptions.Dpi` avant d’appeler `Recognize`. Un DPI plus élevé fournit à l’engin plus de pixels, améliorant ainsi la précision. + +- **Existe‑t‑il une limite de taille pour le TIFF ?** + La propriété `GpuMemoryLimit` plafonne l’utilisation du GPU. Si vous atteignez cette limite, le moteur reviendra sur le CPU pour les pages restantes. + +## Conclusion + +You now have a complete, production‑ready snippet that **recognize text from image** files using Aspose OCR in C#. The tutorial covered how to **create OCR engine**, **load image for OCR**, **set OCR language**, and **extract text from TIFF**—all while leveraging GPU acceleration for speed. + +From here you might: + +- Expérimenter avec différentes langues (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, etc.). +- Intégrer la sortie dans un index ElasticSearch interrogeable. +- Ajouter du post‑traitement (vérification orthographique, nettoyage par expressions régulières) pour améliorer la qualité des données. + +Essayez-le sur votre propre lot de factures, ajustez les limites de mémoire, et observez les performances de l’OCR décoller. Bon codage ! + +## Tutoriels associés + +- [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/) +- [Comment extraire du texte d'une image en préparant des rectangles dans l'OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extraire le texte d'une image – Reconnaître une ligne avec Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..a5652dda8 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. +### [Erstellen einer OCR-Engine in C# – Vollständiger Leitfaden](./create-ocr-engine-in-c-complete-guide/) +Erfahren Sie, wie Sie mit Aspose.OCR eine OCR-Engine in C# erstellen und konfigurieren. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/german/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..9ec405ebe --- /dev/null +++ b/ocr/german/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Erstelle eine OCR‑Engine in C# und lerne, wie du den Evaluierungsmodus + und den Lizenzstatus in wenigen Codezeilen überprüfen kannst. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: de +og_description: Erstelle eine OCR-Engine in C# und sieh sofort, wie man den Evaluierungsmodus + erkennt und den Lizenzstatus anzeigt. +og_title: Erstelle eine OCR‑Engine in C# – Schritt‑für‑Schritt‑Anleitung +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Erstelle eine OCR-Engine in C# – Vollständiger Leitfaden +url: /de/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR-Engine in C# erstellen – Komplettanleitung + +Haben Sie sich jemals gefragt, wie man **OCR‑Engine**‑Objekte in C# erstellt, ohne endlos durch Dokumentationen zu wühlen? Sie sind nicht allein. Viele Entwickler stoßen an Grenzen, wenn sie eine OCR‑Engine starten, prüfen müssen, ob sie im Testmodus läuft, und den Lizenzstatus den Benutzern anzeigen wollen. + +In diesem Tutorial führen wir Sie durch ein prägnantes, durchgängiges Beispiel, das **eine OCR‑Engine erstellt**, deren **Evaluierungsmodus** prüft und eine freundliche Meldung zum Lizenzstatus ausgibt. Am Ende haben Sie eine sofort ausführbare Konsolen‑App und ein klares Konzept, wie Sie OCR‑Lizenzen in Ihren eigenen Projekten handhaben. + +## Was Sie lernen werden + +- Wie man eine `OcrEngine` instanziiert (das Kernstück jedes OCR‑Workflows). +- Warum das Erkennen des **Evaluierungsmodus** für Compliance und Benutzererlebnis wichtig ist. +- Der beste Weg, den **OCR‑Lizenz**‑Status zu prüfen und auf unerwartete Zustände zu reagieren. +- Häufige Stolperfallen – Null‑Referenzen, Ausnahmebehandlung und Versionskonflikte. + +Keine externen Werkzeuge erforderlich, außer dem OCR‑SDK, das Sie bereits installiert haben. Wenn Sie mit grundlegender C#‑Syntax vertraut sind, können Sie loslegen. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code kompiliert mit .NET Core und .NET Framework). +- Ein OCR‑SDK, das eine `OcrEngine`‑Klasse mit einer `IsEvaluation`‑Eigenschaft bereitstellt (z. B. das hypothetische `MyOcrSdk`). +- Ein Texteditor oder eine IDE (Visual Studio, VS Code, Rider – wählen Sie Ihren Favoriten). + +Das war's. Lassen Sie uns eintauchen. + +## Schritt 1: Ein neues Konsolenprojekt einrichten + +Zuerst erstellen Sie eine neue Konsolen‑App, damit Sie den Code isoliert ausführen können. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Öffnen Sie die erzeugte `Program.cs`. Wir ersetzen deren Inhalt durch ein vollständiges Beispiel, das **OCR‑Engine**‑Instanzen erstellt und die Lizenzierung behandelt. + +## Schritt 2: Das OCR‑SDK‑Namespace importieren + +Angenommen, das SDK wird über NuGet referenziert (`MyOcrSdk` ist ein Platzhalter), fügen Sie die using‑Direktive am Anfang der Datei hinzu. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Falls Sie das Paket noch nicht hinzugefügt haben, führen Sie aus: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro‑Tipp:** Halten Sie Ihre SDK‑Version aktuell; neuere Releases verbessern häufig die Erkennung des Evaluierungsmodus. + +## Schritt 3: Die OCR‑Engine‑Instanz erstellen + +Jetzt erstellen wir endlich **OCR‑Engine**‑Objekte. Das ist das Herzstück jedes OCR‑Workflows – denken Sie an das Gehirn, das später Bilder liest. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Warum ist dieser Schritt entscheidend? Die `OcrEngine` kapselt alle Konfigurationen, Sprachpakete und Lizenzdaten. Ohne sie können Sie keine Bilder verarbeiten oder das Evaluierungs‑Flag abfragen. + +> **Hinweis:** Einige SDKs erlauben das Übergeben eines Konfigurationsobjekts an den Konstruktor (z. B. Sprache, DPI). Wenn Sie benutzerdefinierte Einstellungen benötigen, passen Sie die Zeile entsprechend an. + +## Schritt 4: Den Evaluierungsmodus der OCR‑Engine bestimmen + +Die meisten OCR‑Anbieter liefern eine Testversion, die im **Evaluierungsmodus** läuft, bis ein gültiger Lizenzschlüssel bereitgestellt wird. Zu wissen, ob Sie im Testmodus sind, ermöglicht es Ihnen, passende UI‑Hinweise anzuzeigen oder bestimmte Funktionen zu beschränken. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Die Eigenschaft `IsEvaluation` liefert `true`, wenn die Engine nicht lizenziert ist oder eine zeitlich begrenzte Testversion verwendet. Sie ist ein schneller, zuverlässiger Weg, Premium‑Funktionen zu schützen. + +### Was, wenn die Eigenschaft fehlt? + +Ältere SDK‑Versionen könnten stattdessen eine Methode wie `GetLicenseInfo()` bereitstellen. In diesem Fall würden Sie das zurückgegebene Objekt auf ein `IsTrial`‑Flag prüfen. Konsultieren Sie stets das SDK‑Changelog beim Upgrade. + +## Schritt 5: Den aktuellen Lizenzstatus anzeigen + +Zum Schluss zeigen wir dem Benutzer, ob die Engine lizenziert oder noch im Testmodus ist. Ein einfacher Console‑Write‑Line reicht aus, Sie können ihn jedoch für GUI‑Apps anpassen. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Der ternäre Operator hält den Code übersichtlich, und die Meldungen sind klar genug für Endbenutzer oder Entwickler, die Protokolle lesen. + +## Vollständiges funktionierendes Beispiel + +Alles zusammengefügt, hier ein eigenständiges Programm, das Sie in `Program.cs` kopieren und mit `dotnet run` ausführen können. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Erwartete Ausgabe + +- **Testversion:** + `Running in evaluation mode – limited functionality.` + +- **Lizenzierte Version:** + `Licensed – full OCR capabilities enabled.` + +Wenn das SDK eine Ausnahme wirft (z. B. fehlende native DLL), gibt der catch‑Block eine hilfreiche Fehlermeldung aus, anstatt die gesamte Anwendung zum Absturz zu bringen. + +## Umgang mit Randfällen und häufigen Stolperfallen + +### 1. Null‑Engine‑Instanzen + +Obwohl der Konstruktor normalerweise ein gültiges Objekt zurückgibt, können einige SDKs `null` zurückliefern, wenn erforderliche native Abhängigkeiten fehlen. Schützen Sie sich dagegen: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Lizenzablauf während des Betriebs + +Eine Testlizenz kann während einer Sitzung ablaufen. Fragen Sie periodisch `IsEvaluation` ab, wenn Ihre Anwendung lange aktiv bleibt. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Unterschiedliche Eigenschaftsnamen in verschiedenen Versionen + +Ältere Versionen könnten `engine.EvaluationMode` oder `engine.License.IsTrial` bereitstellen. Beim Upgrade suchen Sie in den SDK‑Release‑Notes nach Breaking‑Changes. + +### 4. Mehrthread‑Szenarien + +Wenn Sie mehrere OCR‑Worker starten, instanziieren Sie **eine OCR‑Engine pro Thread**, es sei denn, das SDK unterstützt ausdrücklich thread‑sicheres Teilen. Das Teilen einer einzigen Engine kann zu Race‑Conditions und falschen Lizenzabfragen führen. + +## Pro‑Tipps für den Produktionseinsatz + +- **Cache den Lizenzstatus** nach der ersten Prüfung, um unnötige Eigenschafts‑Aufrufe zu vermeiden. +- **Logge den Lizenzschlüssel** (maskiert) beim Start für Audit‑Logs – unterstützt Support‑Teams bei der Diagnose von Lizenzproblemen. +- **Biete einen UI‑Schalter** an, der den Benutzern anzeigt, dass sie im Testmodus sind, und einen „Lizenz kaufen“-Button anbietet. +- **Automatisiere die Lizenzverlängerung** mithilfe der Aktivierungs‑API des SDKs, falls verfügbar, um ein nahtloses Benutzererlebnis zu gewährleisten. + +## Fazit + +Wir haben gerade **OCR‑Engine**‑Objekte in wenigen Zeilen **erstellt**, den **Evaluierungsmodus der OCR‑Engine** geprüft und eine klare **OCR‑Lizenzstatus**‑Meldung ausgegeben. Das vollständige Beispiel läuft sofort, behandelt Fehler elegant und verdeutlicht das „Warum“ jedes Schrittes – sodass Sie es an Desktop-, Web‑ oder Service‑Szenarien anpassen können. + +Als Nächstes könnten Sie erkunden: + +- Bilder in `engine.Recognize` einspeisen und die Unterstützung mehrerer Sprachen handhaben. +- Verwendung von **check OCR license**‑APIs, um einen gekauften Schlüssel programmgesteuert zu aktivieren. +- Integration mit UI‑Frameworks (WinForms, WPF, MAUI), um Lizenz‑Badges anzuzeigen. + +Probieren Sie das aus, und Sie haben eine robuste OCR‑Grundlage, bereit für jede Anwendung. Viel Spaß beim Coden! + +## Verwandte Tutorials + +- [Wie man OCR extrahiert – OCR‑Konfiguration](/ocr/english/net/ocr-configuration/) +- [Wie man OCR‑Ergebnisse mit Aspose.OCR für .NET erhält](/ocr/english/net/text-recognition/get-recognition-result/) +- [Wie man PDF in .NET mit Aspose.OCR OCR‑t](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/ocr-optimization/_index.md b/ocr/german/net/ocr-optimization/_index.md index c77c30a65..5ca1a7842 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. +### [Bild für OCR vorverarbeiten – Vollständiger Aspose C# Leitfaden](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Erfahren Sie, wie Sie Bilder für die OCR mit Aspose in C# umfassend vorverarbeiten und die Erkennungsgenauigkeit steigern. ## Häufig gestellte Fragen diff --git a/ocr/german/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/german/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..1ec72bfe3 --- /dev/null +++ b/ocr/german/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Bild für OCR mit Aspose vorverarbeiten, um die OCR‑Genauigkeit zu verbessern + und OCR für JPEG‑Dateien auszuführen. Erfahren Sie, wie Sie Text mit Aspose in einer + klaren, Schritt‑für‑Schritt‑Anleitung extrahieren. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: de +og_description: Bild für OCR mit Aspose vorverarbeiten, um die OCR‑Genauigkeit zu + steigern. Folgen Sie dieser Anleitung, um OCR auf JPEG auszuführen und Text mit + Aspose in C# zu extrahieren. +og_title: Bild für OCR vorverarbeiten – Aspose C#‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Bild für OCR vorverarbeiten – Vollständiger Aspose C# Leitfaden +url: /de/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Bild für OCR vorverarbeiten – Vollständiger Aspose C# Leitfaden + +Haben Sie sich schon einmal gefragt, wie man **Bild für OCR vorverarbeitet**, damit der Text jedes Mal sauber herauskommt? Sie sind nicht allein – Entwickler kämpfen ständig mit verrauschten Scans, kontrastarmen JPEGs und unvorhersehbarer Beleuchtung. Die gute Nachricht? Mit ein paar cleveren Anpassungen können Sie die **OCR‑Genauigkeit verbessern** drastisch, und Aspose macht das mühelos. + +In diesem Tutorial führen wir Sie durch ein praxisnahes Beispiel, das zeigt, wie man **OCR auf JPEG**‑Bildern ausführt, eine benutzerdefinierte Bildverarbeitungspipeline anwendet und schließlich **Text mit Aspose extrahiert**. Am Ende haben Sie ein sofort einsetzbares C#‑Snippet, das Sie in jedes .NET‑Projekt einbinden können. + +## Was Sie lernen werden + +- Warum Vorverarbeitung wichtig ist und welche Filter den größten Nutzen bringen. +- Wie Sie `ImageProcessingOptions` von Aspose.OCR für Deskewing, Denoising, Binarisierung und Kontrastverstärkung konfigurieren. +- Den genauen Code, um **OCR auf JPEG**‑Dateien auszuführen und sauberen Text zu erhalten. +- Tipps und Stolperfallen, die Ihre OCR‑Pipeline in der Produktion robust halten. + +Vorkenntnisse mit Aspose sind nicht erforderlich; ein Grundverständnis von C# und Visual Studio (oder Ihrer bevorzugten IDE) reicht aus. Los geht’s. + +![Beispiel für Bildvorverarbeitung für OCR](preprocess-ocr.png "Preprocess image for OCR") + +## Schritt 1: Aspose.OCR‑Engine einrichten – Bild für OCR vorverarbeiten + +Zuerst benötigen wir eine `OcrEngine`‑Instanz und müssen ihr die erwartete Sprache mitteilen. In den meisten Fällen ist Englisch die Vorgabe, aber Sie können sie durch Französisch, Deutsch usw. ersetzen, indem Sie das `OcrLanguage`‑Enum ändern. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Warum das wichtig ist:** Die Engine ist das Herzstück der Operation; ohne sie können Sie keine der Bildfilter anwenden, die tatsächlich **Bild für OCR vorverarbeiten**. Denken Sie an die Engine wie an die Küche, in der alle Zutaten gemischt werden. + +## Schritt 2: Eine benutzerdefinierte Bild‑Verarbeitungspipeline erstellen – OCR‑Genauigkeit verbessern + +Jetzt kommt der spannende Teil. Aspose ermöglicht das Ketten mehrerer Filter. Unten aktivieren wir vier der effektivsten: + +1. **Deskew** – richtet schiefe Dokumente aus (standardmäßig max. 5°). +2. **Denoise** – glättet körnige Hintergründe. +3. **Binarize** – wandelt das Bild mittels Schwellenwert in Schwarz‑Weiß um. +4. **ContrastBoost** – lässt schwache Zeichen hervortreten. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro‑Tipp:** Wenn Ihre Quellbilder bereits scharf sind, können Sie die `Strength` verringern oder einen Filter komplett deaktivieren. Über‑Verarbeitung kann manchmal feine Zeichen löschen, also experimentieren Sie mit echten Beispielen. + +## Schritt 3: JPEG (oder jedes Bild) laden und OCR ausführen – OCR auf JPEG + +Aspose arbeitet mit jedem Bildformat, das .NET lesen kann – JPEG, PNG, BMP, usw. So füttern Sie eine JPEG‑Datei in die Engine und starten den Erkennungsprozess. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Warum JPEG?** JPEG‑Kompression führt häufig zu Artefakten, die OCR verwirren. Unsere Vorverarbeitungspipeline, insbesondere die Denoise‑ und Binarize‑Schritte, mildert diese Probleme, sodass Sie **OCR auf JPEG** mit Zuversicht ausführen können. + +## Schritt 4: Erkannten Text ausgeben – Text mit Aspose extrahieren + +Abschließend schreiben wir den Text einfach in die Konsole, in eine Datei oder an einen anderen Dienst. Für die Demonstration reicht die Konsole aus. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Wenn Sie das Programm ausführen, sollte etwa Folgendes erscheinen: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Sieht die Ausgabe verzerrt aus, gehen Sie zurück zu **Schritt 2** und passen Sie die Filtereinstellungen an. Kleine Anpassungen führen oft zu großen Verbesserungen bei der **Verbesserung der OCR‑Genauigkeit**. + +## Häufige Randfälle und deren Handhabung + +| Situation | Empfohlene Anpassung | +|-----------|----------------------| +| **Sehr dunkle Bilder** | `ContrastBoost.Level` auf 1,5 oder höher erhöhen. | +| **Schräglage > 5°** | `DeskewOptions.MaxAngle` erhöhen (z. B. 10,0) oder das Bild manuell vor‑drehen. | +| **Farbiger Text auf farbigem Hintergrund** | `BinarizeOptions` mit benutzerdefiniertem Schwellenwert verwenden oder zu `AdaptiveBinarizeOptions` wechseln. | +| **Große Dateien ( > 5 MB )** | Bild zuerst in einen `MemoryStream` laden, um Datei‑Lock‑Probleme zu vermeiden. | + +Diese Anpassungen halten Ihre Pipeline flexibel und zukunftssicher, besonders wenn Sie **Text mit Aspose extrahieren** müssen aus unterschiedlichen Quellen. + +## Vollständiges Beispiel – Alle Schritte an einem Ort + +Unten finden Sie das komplette, copy‑and‑paste‑fertige Programm. Es kompiliert mit .NET 6+ und benötigt nur das NuGet‑Paket `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Speichern Sie dies als `Program.cs`, fügen Sie das Aspose.OCR‑Paket hinzu (`dotnet add package Aspose.OCR`) und führen Sie `dotnet run` aus. Sie sehen den bereinigten Text in der Konsole. + +## Zusammenfassung – Warum dieser Ansatz funktioniert + +- **Bild für OCR vorverarbeiten**: Die Pipeline entfernt die häufigsten Fehlerquellen (Schräglage, Rauschen, geringer Kontrast). +- **OCR‑Genauigkeit verbessern**: Jeder Filter ist darauf abgestimmt, das Signal‑zu‑Rausch‑Verhältnis für die Engine zu erhöhen. +- **OCR auf JPEG**: Selbst komprimierte Bilder werden nach Deskewing und Binarisierung lesbar. +- **Text mit Aspose extrahieren**: Die `Recognize`‑Methode liefert einen Klartext‑String, bereit für jede nachgelagerte Logik. + +Zusammen geben Ihnen diese Schritte eine zuverlässige, produktionsreife OCR‑Lösung in nur wenigen Zeilen Code. + +## Nächste Schritte und verwandte Themen + +- **Batch‑Verarbeitung** – Durchlaufen Sie einen Ordner mit Bildern und schreiben Sie jedes Ergebnis in eine `.txt`‑Datei. +- **Sprachpakete** – Ersetzen Sie `OcrLanguage.English` durch `OcrLanguage.Spanish` oder fügen Sie eigene Wörterbücher hinzu. +- **PDF‑Extraktion** – Kombinieren Sie Aspose.OCR mit Aspose.PDF, um Text direkt aus gescannten PDFs zu holen. +- **Performance‑Optimierung** – Führen Sie die Engine parallel mit `Parallel.ForEach` für große Workloads aus. + +Probieren Sie die Filterwerte aus, testen Sie verschiedene Bildformate oder verketten Sie zusätzliche Aspose‑Filter wie `SharpnessOptions`. Sobald Sie die Grundlagen beherrschen, sind Ihrer Kreativität keine Grenzen gesetzt. + +--- + +*Viel Spaß beim Coden! Wenn Sie auf Probleme stoßen, hinterlassen Sie einen Kommentar unten und wir helfen Ihnen gemeinsam weiter.* + +## Verwandte Tutorials + +- [Preprocess Image OCR mit Aspose.OCR‑Filtern für .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Text aus Bild extrahieren – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Bildtext mit C# extrahieren – Sprachauswahl mit 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/text-recognition/_index.md b/ocr/german/net/text-recognition/_index.md index 164bd821b..06f2951ba 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 @@ -48,16 +48,31 @@ Erweitern Sie Ihre .NET-Anwendungen mit Aspose.OCR für eine genaue Zeichenerken ### [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. ### [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. +### [Text aus Bild mit Aspose OCR – Vollständiger C#‑Leitfaden](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Erfahren Sie, wie Sie mit Aspose OCR in C# Text aus Bildern extrahieren – Schritt‑für‑Schritt‑Anleitung für .NET‑Entwickler. +### [Wie man OCR in C# verwendet – Chinesischen Text aus JPG erkennen](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Erfahren Sie, wie Sie mit Aspose.OCR in C# chinesischen Text aus JPG‑Dateien extrahieren. +### [OCR russischer Text in C# – Vollständiger Leitfaden mit Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Erfahren Sie, wie Sie mit Aspose OCR in C# russischen Text aus Bildern extrahieren – Schritt‑für‑Schritt‑Anleitung für .NET‑Entwickler. +### [Text aus Bild in C# – Vollständiger Aspose OCR Leitfaden](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Erfahren Sie, wie Sie mit Aspose OCR in C# Text aus Bildern extrahieren – umfassende Schritt‑für‑Schritt‑Anleitung. +### [Text aus Bild in ASP.NET Core Minimal API – Vollständiger Leitfaden](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Erfahren Sie, wie Sie mit Aspose OCR in ASP.NET Core Minimal API Text aus Bildern extrahieren – Schritt‑für‑Schritt‑Anleitung für .NET‑Entwickler. +### [c# OCR‑Tutorial: Text aus PNG‑Belegen extrahieren mit Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Lernen Sie, wie Sie mit Aspose OCR Text aus PNG‑Belegen in C# extrahieren – Schritt‑für‑Schritt‑Anleitung für .NET‑Entwickler. +### [TIFF in Text konvertieren in C# – Vollständiger Batch-OCR-Leitfaden](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Erfahren Sie, wie Sie mit Aspose.OCR in C# TIFF‑Dateien stapelweise in Text umwandeln – 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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/german/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..79aa47e91 --- /dev/null +++ b/ocr/german/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR‑Tutorial, das zeigt, wie man eine Bilddatei in C# lädt und Text + aus einer PNG‑Quittung mit Aspose OCR erkennt – Schritt‑für‑Schritt‑Anleitung. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: de +og_description: c# OCR‑Tutorial, das Sie Schritt für Schritt durch das Laden einer + Bilddatei in C# führt und den Text einer PNG‑Quittung mit Aspose OCR erkennt. +og_title: c# OCR‑Tutorial – Text aus PNG‑Belegen extrahieren +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR‑Tutorial: Text aus PNG‑Quittungen mit Aspose extrahieren' +url: /de/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR Tutorial – Text aus PNG‑Belegen extrahieren mit Aspose + +Haben Sie schon einmal ein **c# OCR tutorial** gebraucht, das die Aufgabe wirklich erledigt, ohne endloses Googeln? Sie sind hier genau richtig. In diesem Leitfaden werden wir **load image file c#**, **recognize png text** und **read receipt OCR** Ergebnisse behandeln, und Ihnen zeigen, wie Sie **perform OCR image** Verarbeitung mit Aspose OCR durchführen. + +Wir beginnen mit der Installation des erforderlichen NuGet‑Pakets, gehen jede Codezeile durch und schließen mit einem sauberen JSON‑Dump ab, den Sie direkt in Ihre nächste Daten‑Pipeline einspeisen können. Kein Schnickschnack, nur eine praktische, sofort einsatzbereite Lösung. + +## Was Sie lernen werden + +- Wie man Aspose OCR in einem .NET 6 (oder höher) Projekt einrichtet. +- Die genauen Schritte, um **load an image file c#** zu laden und an die Engine zu übergeben. +- Wie man **recognize png text** aus einem Beleg‑Bild extrahiert und das Ergebnis erfasst. +- Möglichkeiten, **read receipt OCR** Ausgabe als schön formatiertes JSON zu erhalten. +- Tipps für **perform OCR image** Vorgänge mit verschiedenen Dateitypen und zum Umgang mit gängigen Fallstricken. + +**Prerequisites** +- Visual Studio 2022 (oder jede andere IDE Ihrer Wahl). +- .NET 6 SDK oder neuer. +- Ein PNG‑Beleg‑Bild zur Hand (wir nennen es `receipt.png`). + +Wenn Sie das haben, legen wir los. + +![c# OCR Tutorial Screenshot](ocr-demo.png "c# OCR Tutorial Ergebnis, das JSON‑Ausgabe zeigt") + +## c# OCR Tutorial – Einrichtung der Aspose OCR Engine + +Zunächst benötigen wir die Aspose OCR‑Bibliothek. Öffnen Sie Ihr Terminal im Projektordner und führen Sie aus: + +```bash +dotnet add package Aspose.OCR +``` + +Dieser einzelne Befehl lädt alles Notwendige, einschließlich nativer Binärdateien für die Bilddekodierung. Nach der Installation erstellen Sie ein neues Konsolenprojekt oder fügen den Code zu einem bestehenden Projekt hinzu. + +### Warum Aspose? + +Aspose OCR unterstützt über 30 Sprachen, funktioniert offline und liefert ein umfangreiches `OcrResult`‑Objekt – perfekt für **perform OCR image** Aufgaben, bei denen Sie mehr als nur reinen Text benötigen. + +## Bilddatei laden c# und Beleg vorbereiten + +Jetzt, wo die Bibliothek bereit ist, lassen Sie uns **load image file c#**. Die Klasse `System.Drawing.Image` übernimmt die schwere Arbeit, aber Sie können auch `SkiaSharp` verwenden, wenn Sie eine plattformübergreifende Alternative bevorzugen. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro‑Tipp:** Wickeln Sie das `Image` in eine `using`‑Anweisung (wie gezeigt), um native Ressourcen sofort freizugeben – besonders wichtig, wenn Sie **perform OCR image** auf vielen Dateien in einer Schleife ausführen. + +## PNG‑Text mit Aspose erkennen + +Mit dem Bild im Speicher kann die Engine nun **recognize png text**. Aspose liefert ein `OcrResult`, das sowohl den Rohstring als auch detaillierte Daten zu jedem erkannten Wort enthält. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Warum `RecognizeWithResult` anstelle des einfacheren `Recognize` aufrufen? Ersteres gibt Ihnen Zugriff auf Konfidenzwerte, Begrenzungsrahmen und Zeilenumbrüche – praktisch, wenn Sie später **read receipt OCR** für die Extraktion von Positionen benötigen. + +## OCR‑Ergebnis des Belegs als JSON lesen + +Die meisten nachgelagerten Systeme lieben JSON, also serialisieren wir das `OcrResult`. Der `System.Text.Json`‑Serializer verarbeitet komplexe Objekte elegant, und wir aktivieren Einrückungen für bessere Lesbarkeit. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Das resultierende JSON sieht etwa so aus (gekürzt zur Übersicht): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Sie können `jsonResult` nun in eine Datenbank, eine Nachrichtenwarteschlange einspeisen oder einfach zur Fehlersuche protokollieren. + +## OCR‑Bildverarbeitung durchführen und Ausgabe anzeigen + +Abschließend geben wir das JSON in der Konsole aus. In einer realen Anwendung würden Sie es wahrscheinlich in eine Datei schreiben oder über HTTP senden, aber die Konsole erleichtert die Überprüfung, dass alles funktioniert. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Führen Sie das Programm (`dotnet run`) aus und Sie sollten das schön formatierte JSON ausgegeben sehen. Ist das Beleg‑Bild klar, ist der Text exakt; andernfalls sollten Sie die Bildauflösung erhöhen oder einen Vorverarbeitungsfilter (z. B. Graustufen, Kontrastverstärkung) anwenden, bevor Sie es an die Engine übergeben. + +### Umgang mit häufigen Sonderfällen + +| Situation | Was zu tun ist | +|-----------|----------------| +| **Image is blurry** | Vorverarbeiten mit `System.Drawing`, um zu schärfen oder DPI zu erhöhen. | +| **Receipt contains multiple languages** | Setzen Sie `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Large batch processing** | Wiederverwenden einer einzelnen `OcrEngine`‑Instanz; nur das `Image` bei jeder Iteration ändern. | +| **Memory pressure** | `Image`‑Objekte sofort freigeben und `await Task.Run` für asynchrone Pipelines in Betracht ziehen. | + +Diese Anpassungen halten Ihren **perform OCR image** Workflow robust, selbst wenn die Eingabe nicht perfekt ist. + +## Abschluss + +Herzlichen Glückwunsch – Sie haben gerade ein **c# OCR tutorial** abgeschlossen, das ein Bild lädt, **recognizes png text** und **reads receipt OCR** Ausgabe als sauberes JSON liefert. Die Kernschritte (Engine‑Einrichtung, Bildladen, OCR‑Ausführung, Serialisierung und Anzeige) bilden eine solide Grundlage, die Sie auf Rechnungen, Reisepässe oder andere gescannte Dokumente ausweiten können. + +### Was kommt als Nächstes? + +- Experimentieren Sie mit **load image file c#** unter Verwendung von `SkiaSharp` für echten plattformübergreifenden Support. +- Tauchen Sie tiefer in `OcrResult.Words` ein, um Positionen, Preise und Daten zu extrahieren – ideal für Ausgaben‑Tracking‑Apps. +- Kombinieren Sie dieses Tutorial mit Azure Functions oder AWS Lambda, um eine serverlose Beleg‑Verarbeitungs‑API zu erstellen. + +Passen Sie den Code gerne an, fügen Sie weitere Bilder hinzu oder wechseln Sie sogar zu einem anderen Sprachpaket. Die Welt der OCR steckt voller Überraschungen, und jetzt haben Sie die Werkzeuge, um sie zu erkunden. + +Viel Spaß beim Coden, und möge Ihr Beleg stets lesbar sein! + +## Verwandte Tutorials + +- [Bildtext in C# mit Sprachauswahl extrahieren mit Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Text aus Bild extrahieren – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Wie man OCR verwendet – Bild ohne Texterkennungsbereich erkennen](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/german/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..903ff6347 --- /dev/null +++ b/ocr/german/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Konvertieren Sie TIFF in Text mit Aspose.OCR in C#. Erfahren Sie, wie + Sie Bilder stapelweise in Text umwandeln und Text aus TIFF‑Dateien effizient extrahieren. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: de +og_description: Konvertieren Sie TIFF in Text mit Aspose.OCR. Dieser Leitfaden zeigt + die Stapelkonvertierung von Bildern zu Text und wie man Text aus TIFF‑Dateien in + wenigen C#‑Zeilen extrahiert. +og_title: TIFF in Text konvertieren in C# – Vollständiger Batch‑OCR‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: TIFF zu Text konvertieren in C# – Vollständiger Batch‑OCR‑Leitfaden +url: /de/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# TIFF in Text konvertieren in C# – Vollständiger Batch-OCR-Leitfaden + +Haben Sie jemals **TIFF in Text konvertieren** müssen, wussten aber nicht, wo Sie anfangen sollen? Sie sind nicht allein – viele Entwickler stolpern über Batch-OCR, wenn sie mit gescannten Dokumenten arbeiten. In diesem Tutorial führen wir Sie durch eine praxisnahe Lösung, die **Text aus TIFF**‑Dateien mit Aspose.OCR extrahiert, und das parallel, sodass große Ordner in Sekunden fertig sind. + +Wir gehen auch auf bewährte Methoden der **Batch-Bild‑zu‑Text-Konvertierung** ein, sodass Sie am Ende ein wiederverwendbares Snippet haben, das ein ganzes Verzeichnis gescannter Bilder in ordentliche *.txt*-Dateien verwandelt – ideal für Indexierung, Suche oder die Weiterverarbeitung in nachgelagerten Analysen. + +## Was Sie benötigen + +- **.NET 6.0** oder höher (der Code lässt sich auch auf .NET Framework kompilieren) +- **Aspose.OCR for .NET** NuGet‑Paket (`Install-Package Aspose.OCR`) +- Ein Ordner, der eine oder mehrere *.tif*-Dateien enthält (das klassische TIFF‑Scan‑Format) +- Ihre bevorzugte IDE (Visual Studio, VS Code, Rider – was Sie auch immer mögen) + +Das war’s. Keine externen Dienste, keine API‑Schlüssel, nur reines C# und Aspose. + +![Screenshot einer verarbeiteten TIFF‑Datei und der resultierenden Textdatei](/images/ocr-result.png "OCR‑Ergebnis, das die konvertierte TIFF‑zu‑Text‑Ausgabe zeigt") + +*(Alt‑Text: Screenshot, der die konvertierte TIFF‑zu‑Text‑Ausgabe auf dem Bildschirm zeigt)* + +## Schritt 1: OCR‑Engine einrichten – TIFF in Text konvertieren + +Zuerst benötigen wir eine `OcrEngine`‑Instanz, die weiß, dass sie englische Zeichen lesen soll. Die Engine ist das Herz der Konvertierung; ihre korrekte Konfiguration sorgt für zuverlässige Ergebnisse. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Warum das wichtig ist:* +Aspose.OCR unterstützt Dutzende von Sprachen. Wenn Sie mit mehrsprachigen Scans arbeiten, ändern Sie einfach `OcrLanguage.English` in den passenden Enum‑Wert. Wird die Sprache nicht festgelegt, schaltet die Engine in den Auto‑Detect‑Modus, was langsamer und weniger genau sein kann. + +## Schritt 2: Alle TIFF‑Dateien sammeln – Text aus TIFF effizient extrahieren + +Als Nächstes holen wir jede *.tif*-Datei aus einem von Ihnen angegebenen Ordner. Mit `Directory.GetFiles` erhalten wir ein sauberes Array, das wir dem Batch‑Prozessor übergeben können. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro‑Tipp:* Das Flag `SearchOption.AllDirectories` kann verwendet werden, wenn Ihre Scans in Unterordnern verschachtelt sind. Denken Sie jedoch daran, dass tiefere Rekursion den Speicherverbrauch während des Batch‑Schritts erhöhen kann. + +## Schritt 3: Parallel‑OCR ausführen – Batch‑Bild‑zu‑Text‑Konvertierung + +Jetzt kommt der spaßige Teil. Aspose.OCR liefert einen statischen Helfer `BatchOcr.RecognizeAll`, der ein Array von Dateipfaden, eine Engine und einen `parallelism`‑Hinweis akzeptiert. Wir starten vier Threads, was auf einem modernen Quad‑Core‑Laptop nahezu lineare Beschleunigung liefert. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Warum Parallelität?* +Das Scannen eines Batches hochauflösender TIFFs kann CPU‑intensiv sein. Durch die Verteilung der Arbeit auf mehrere Threads halten wir alle Kerne beschäftigt, wodurch die Gesamtlaufzeit drastisch verkürzt wird. Wenn Sie dies auf einem Server mit mehr Kernen ausführen, erhöhen Sie den `parallelism`‑Wert entsprechend. + +## Schritt 4: Ausgabe schreiben – Scannte Bild‑TXT‑Dateien konvertieren + +Abschließend iterieren wir über das Dictionary und schreiben jeden Textabschnitt in eine *.txt*-Datei, die den ursprünglichen Basisnamen teilt. Das ist der Moment, in dem **convert scanned images txt** zur Realität wird. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Was der Code macht, einfach erklärt + +1. **Erstellen** Sie eine OCR‑Engine, die auf Englisch eingestellt ist. +2. **Sammeln** Sie jede TIFF‑Datei aus dem Zielordner. +3. **Führen** Sie `BatchOcr.RecognizeAll` mit vier Threads aus, wobei jedes Bild in einen String umgewandelt wird. +4. **Durchlaufen** Sie die Ergebnisse, ersetzen die `.tif`‑Erweiterung durch `.txt` und schreiben den String auf die Festplatte. + +Das ist der gesamte **convert TIFF to text**‑Arbeitsablauf in weniger als 50 Codezeilen. + +## Umgang mit Sonderfällen – Wenn Dinge nicht reibungslos laufen + +- **Fehlende oder beschädigte TIFFs** – `BatchOcr` wirft eine `OcrException`. Wickeln Sie den Aufruf in ein `try / catch`, wenn Sie eine sanfte Degradierung benötigen. +- **Nicht‑englische Dokumente** – ändern Sie `OcrLanguage.English` zu `OcrLanguage.Spanish`, `OcrLanguage.French` usw., oder verwenden Sie `OcrLanguage.AutoDetect`. +- **Sehr große Bilder** – erwägen Sie, die DPI vor dem OCR zu reduzieren (`ocrEngine.ImagePreprocessing.Dpi = 200`), um Speicher zu sparen, wobei jedoch etwas Genauigkeit verloren gehen kann. +- **Ausgabe‑Kodierung** – wenn Sie eine bestimmte Codepage benötigen (z. B. Windows‑1252), übergeben Sie sie an `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Pro‑Tipps für robuste Batch‑Konvertierungen + +- **Fehler protokollieren**: Erstellen Sie eine `List failedFiles` und fügen Sie jede Datei hinzu, die eine Ausnahme wirft; schreiben Sie die Liste nach der Schleife in ein Log. +- **Engine wiederverwenden**: dieselbe `OcrEngine`‑Instanz kann für viele Dateien wiederverwendet werden; instanziieren Sie sie nicht innerhalb der Schleife. +- **Ergebnis validieren**: ein kurzer `if (string.IsNullOrWhiteSpace(extractedText))` kann Scans markieren, die leer oder unlesbar waren. +- **Mit PDF kombinieren**: Wenn Ihre Quelle ein mehrseitiges PDF ist, konvertieren Sie zuerst jede Seite zu TIFF (Aspose.PDF erledigt das) und führen dann diesen Batch aus. + +## Nächste Schritte – Über die einfache Konvertierung hinaus + +Jetzt, da Sie **Text aus TIFF**‑Dateien in großen Mengen extrahieren können, möchten Sie vielleicht: + +- Die *.txt*-Dateien in einen Suchindex einspeisen (Elasticsearch, Azure Cognitive Search). +- Eine Spracherkennung für jedes Ergebnis ausführen, um Dokumente zu lokalspezifischen Pipelines zu leiten. +- Durchsuchbare PDFs erzeugen, indem Sie den OCR‑Text wieder über die Originalbilder legen (wieder Aspose.PDF). + +All diese Szenarien basieren auf derselben Kernidee: **batch image to text conversion** ist ein Baustein für größere Dokumenten‑Verarbeitungssysteme. + +--- + +### Fazit + +Sie haben gerade gelernt, wie man **TIFF in Text** mit Aspose.OCR konvertiert, einen gesamten Ordner parallel verarbeitet und jedes Ergebnis als saubere *.txt*-Datei speichert. Die Lösung ist leichtgewichtig, vollständig konfigurierbar und bereit für die Produktion – egal, ob Sie alte Rechnungen digitalisieren, gescannte Verträge archivieren oder eine Text‑Suchmaschine betreiben. + +Probieren Sie es aus, passen Sie die Parallelität an und füttern Sie die neu erstellten Textdateien in den gewünschten Workflow. Viel Spaß beim OCRen! + +--- + +## Verwandte Tutorials + +- [Text aus Bildern mit OCR‑Operation in Ordnern extrahieren](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Text aus Bild extrahieren – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Bildtext in C# mit Sprachauswahl extrahieren mit 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/german/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..7a71baab9 --- /dev/null +++ b/ocr/german/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Erfahren Sie, wie Sie Text aus einem Bild mit einer minimalen ASP.NET Core‑API + extrahieren. Bild per POST hochladen, Multipart‑Formulardaten lesen und OCR auf + dem Bild durchführen. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: de +og_description: Extrahiere Text aus einem Bild mit einer minimalen ASP.NET Core‑API. + Dieser Leitfaden zeigt, wie man ein Bild per POST hochlädt, Multipart‑Formulardaten + liest und OCR auf dem Bild durchführt. +og_title: Text aus Bild in ASP.NET Core extrahieren – Schritt für Schritt +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Text aus Bild in ASP.NET Core Minimal API extrahieren – Vollständige Anleitung +url: /de/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bild in ASP.NET Core Minimal API extrahieren – Vollständige Anleitung + +Haben Sie sich jemals gefragt, wie man **Text aus Bild** extrahiert, ohne sich mit schweren Frameworks herumzuschlagen? Sie sind nicht allein. Viele Entwickler benötigen eine schnelle Möglichkeit, Benutzern das Hochladen eines Bildes zu ermöglichen und die rohen Zeichen zurückzubekommen, sei es beim Scannen von Quittungen, der Digitalisierung handgeschriebener Notizen oder beim Betreiben eines Suchindex. + +In diesem Tutorial erstellen wir eine kleine ASP.NET Core Minimal API, die **Bild per POST hochlädt**, die *multipart/form‑data* Nutzlast analysiert und dann **OCR auf Bild ausführt** mithilfe einer Singleton‑Instanz `OcrEngine`. Am Ende haben Sie eine vollständig ausführbare Anwendung, die Sie in jedes .NET 8‑Projekt einbinden können und sofort Text aus Bild extrahieren können. + +## Was Sie bauen werden + +- Eine minimale Web‑App, die auf `/ocr` lauscht. +- Ein Endpunkt, der eine Bilddatei akzeptiert, die mit einer `multipart/form-data` POST‑Anfrage gesendet wird. +- Logik, die die hochgeladene Datei liest, sie an die OCR‑Engine übergibt und reine Text‑Ergebnisse zurückgibt. +- Optionaler GPU‑Beschleunigungs‑Snippet (auskommentiert) für Nutzer mit kompatibler Karte. + +**Voraussetzungen** +- .NET 8 SDK (oder neuer). +- Grundlegende Kenntnisse in C# und der Befehlszeile. +- Eine OCR‑Bibliothek, die eine `OcrEngine`‑Klasse bereitstellt (das Beispiel geht von einem hypothetischen NuGet‑Paket aus). + +Wenn Sie das haben, lassen Sie uns eintauchen. + +## Schritt 1: Projekt einrichten und OCR‑Paket hinzufügen + +Zuerst erstellen Sie ein neues Web‑Projekt und binden die OCR‑Bibliothek ein. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro Tipp:** Halten Sie Ihre Abhängigkeiten aktuell. Neuere Versionen bringen oft Leistungsverbesserungen, besonders bei GPU‑beschleunigter Inferenz. + +## Schritt 2: Singleton‑OCR‑Engine registrieren (Primärdienst) + +Wir benötigen eine einzige `OcrEngine`‑Instanz für die gesamte Anwendung – es ist nicht nötig, für jede Anfrage eine neue Engine zu starten. Registrieren Sie sie im Service‑Container des Builders. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Warum ein Singleton?** +Das Erstellen einer OCR‑Engine kann teuer sein – denken Sie an das Laden von neuronalen Netzwerk‑Gewichten in den Speicher. Durch die Wiederverwendung derselben Instanz sparen wir sowohl CPU‑Zyklen als auch RAM, was zu schnelleren Antwortzeiten für jeden `/ocr`‑Aufruf führt. + +## Schritt 3: Anwendung erstellen + +Jetzt materialisieren wir das `WebApplication`‑Objekt. + +```csharp +var app = builder.Build(); +``` + +Diese Zeile wirkt fast magisch, aber im Hintergrund richtet sie Routing, Middleware und den DI‑Container ein, den wir gerade konfiguriert haben. + +## Schritt 4: POST‑Endpunkt definieren – „Bild per POST hochladen“ + +Hier ist das Herzstück des Tutorials: ein Endpunkt, der **Bild per POST hochlädt**, die multipart‑Nutzlast liest und die Daten an die OCR‑Engine übergibt. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Aufschlüsselung der Logik + +| Schritt | Was passiert | Warum es wichtig ist | +|------|--------------|----------------| +| **ReadFormAsync** | Parst die eingehende *multipart/form-data* Anfrage. | Ohne dies können Sie nicht auf die hochgeladenen Dateien zugreifen. | +| **form.Files["image"]** | Ruft die Datei ab, deren Formularfeld‑Name `image` ist. | Garantiert einen vorhersehbaren Vertrag für Aufrufer. | +| **Content‑type check** | Überprüft, ob die Datei ein Bild ist (z. B. `image/png`). | Verhindert, dass die OCR‑Engine bei Nicht‑Bild‑Daten scheitert. | +| **Image.FromStream** | Konvertiert den Roh‑Stream in ein `System.Drawing.Image`. | Die OCR‑Bibliothek erwartet ein `Image`‑Objekt, nicht ein rohes Byte‑Array. | +| **ocr.Recognize(img)** | Ruft die OCR‑Engine auf, um **Text aus Bild zu erkennen**. | Dies ist der zentrale **OCR auf Bild ausführen**‑Schritt. | +| **Results.Text** | Sendet die reine Text‑Antwort zurück. | Ein einfaches, konsumierbares Format für nachgelagerte Dienste. | + +## Schritt 5: API ausführen + +Zum Schluss starten Sie den Web‑Server. + +```csharp +app.Run(); +``` + +Wenn Sie `dotnet run` ausführen, hört die API auf `http://localhost:5000` (oder einem von Ihnen gewählten Port). Sie können sie mit `curl` testen: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Erwartete Ausgabe:** Die Konsole gibt die erkannten Zeichen aus, z. B.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Wenn das Bild unscharf ist oder die Sprache nicht unterstützt wird, gibt die OCR‑Engine einen leeren String oder eine Fehlermeldung zurück – behandeln Sie diese Fälle im Produktionscode. + +## Randfälle & bewährte Methoden + +### 1. Große Dateien + +Das Standard‑Limit für den Anforderungskörper beträgt 30 MB. Für größere Scans müssen Sie möglicherweise anpassen: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynchrones OCR + +Einige OCR‑Bibliotheken stellen asynchrone Methoden bereit (`RecognizeAsync`). Wenn Ihre das tut, ersetzen Sie `ocr.Recognize(img)` durch `await ocr.RecognizeAsync(img)` und markieren Sie das Lambda als `async`. + +### 3. Sicherheitsüberlegungen + +- **Dateigröße validieren** bevor Sie sie in den Speicher laden. +- **Dateinamen bereinigen**, falls Sie ihn jemals auf die Festplatte schreiben. +- **Rate‑Limiting** des Endpunkts, um Denial‑of‑Service‑Angriffe zu vermeiden. + +### 4. GPU‑Beschleunigung + +Wenn Sie die Zeile `engine.GpuDevice = new GpuDevice(0);` auskommentieren und Ihre Hardware CUDA oder DirectML unterstützt, werden Sie einen spürbaren Geschwindigkeitszuwachs sehen, besonders bei hochauflösenden Bildern. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie das vollständige `Program.cs`, das Sie in ein frisches Minimal‑API‑Projekt kopieren können. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Speichern Sie, führen Sie `dotnet run` aus, und Sie sind bereit, **Text aus Bild** bei Bedarf zu extrahieren. + +## Fazit + +Wir haben eine **vollständige End‑zu‑End‑Lösung** zum Extrahieren von Text aus Bild mit ASP.NET Core Minimal API durchlaufen. Beginnend mit dem Projekt‑Scaffolding haben wir **eine Singleton‑OCR‑Engine registriert**, einen Endpunkt gebaut, der **Bild per POST hochlädt**, **multipart‑Formulardaten liest** und schließlich **OCR auf Bild ausführt**, um sauberen Klartext zurückzugeben. + +Von hier aus können Sie: + +- JSON‑Wrapper hinzufügen für umfangreichere Antworten. +- Eine Datenbank einbinden, um den extrahierten Text zu speichern. +- Unterstützung für mehrere Sprachen erweitern (`OcrLanguage.Spanish`, usw.). + +Das Muster skaliert gut – fügen Sie einfach denselben Endpunkt in einen größeren Microservice ein oder stellen Sie ihn hinter einem API‑Gateway bereit. + +Haben Sie Fragen zur Verarbeitung von PDFs, Batch‑Verarbeitung oder GPU‑Optimierung? Hinterlassen Sie einen Kommentar, und happy coding! + +## Verwandte Tutorials + +- [Text aus Bild mit Aspose.OCR .NET extrahieren](/ocr/english/net/image-and-drawing-recognition/) +- [Text aus Bild – OCR‑Optimierung mit Aspose.OCR für .NET](/ocr/english/net/ocr-optimization/) +- [Bildtext in C# mit Sprachauswahl mithilfe von Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/german/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..a38679a95 --- /dev/null +++ b/ocr/german/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,295 @@ +--- +category: general +date: 2026-05-25 +description: Extrahiere Text aus einem Bild mit C# und Aspose OCR. Erfahre, wie du + JPG in Text umwandelst, das Bild für OCR lädst und schnell zuverlässige Ergebnisse + erhältst. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: de +og_description: Extrahiere Text aus Bild mit C#. Dieser Leitfaden zeigt, wie man JPG + in Text umwandelt, ein Bild für OCR lädt und mehrsprachige Inhalte verarbeitet. +og_title: Text aus Bild in C# extrahieren – Aspose OCR‑Tutorial +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Text aus Bild in C# extrahieren – Vollständiger Aspose OCR‑Leitfaden +url: /de/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bild in C# extrahieren – Vollständiger Aspose OCR Leitfaden + +Haben Sie sich jemals gefragt, wie man **extract text from image** mit einfachem C#‑Code extrahiert? Sie sind nicht der Einzige. Egal, ob Sie Belege digitalisieren, Schilder scannen oder einfach nur neugierig auf OCR sind, die Fähigkeit, Zeichen aus einem Bild zu ziehen, ist eine nützliche Fähigkeit. In diesem Tutorial führen wir Sie durch ein vollständiges, ausführbares Beispiel, das genau zeigt, wie man **extract text from image** mit Aspose.OCR durchführt, und wir behandeln außerdem, wie man **convert jpg to text**, **load image for OCR** und die klassische Frage „**how to ocr image**“ ein für alle Mal beantwortet. + +Am Ende dieses Leitfadens haben Sie eine eigenständige Konsolenanwendung, die eine JPEG‑Datei liest, Ukrainisch (oder jede andere unterstützte Sprache) erkennt und das Ergebnis in der Konsole ausgibt. Keine vagen Verweise, keine fehlenden Teile – nur eine komplette Lösung, die Sie kopieren‑einfügen und ausführen können. + +--- + +## Was Sie lernen werden + +* Wie man das Aspose.OCR NuGet‑Paket installiert. +* Der genaue Code, der benötigt wird, um **load image for OCR** in C# zu laden. +* Wie man die Sprache einstellt und tatsächlich **extract text from image**. +* Tricks, um **convert jpg to text** effizient durchzuführen. +* Häufige Fallstricke und wie man sie vermeidet. + +Wenn Sie bereits eine .NET‑Entwicklungsumgebung eingerichtet haben, können Sie sofort loslegen. Andernfalls bringt Sie der untenstehende Abschnitt „Voraussetzungen“ auf den neuesten Stand. + +--- + +## Voraussetzungen + +| Anforderung | Warum es wichtig ist | +|-------------|----------------------| +| .NET 6.0 SDK (oder neuer) | Stellt die Laufzeit für die Konsolenanwendung bereit. | +| Visual Studio 2022 oder VS Code | Erleichtert das Bearbeiten und Debuggen. | +| Internetverbindung (beim ersten Lauf) | NuGet muss Aspose.OCR herunterladen. | +| Ein JPEG‑Bild, das Sie verarbeiten möchten (z. B. `ukrainian_sign.jpg`) | Die Quelldatei für die OCR‑Engine. | + +> **Pro‑Tipp:** Wenn Sie unter Linux oder macOS arbeiten, funktioniert derselbe Code mit der .NET‑CLI (`dotnet new console`), sodass Sie die schwere IDE gern überspringen können. + +## Schritt 1 – Aspose.OCR via NuGet installieren + +Öffnen Sie Ihr Terminal (oder die Package‑Manager‑Konsole) und führen Sie aus: + +```bash +dotnet add package Aspose.OCR +``` + +Diese einzelne Zeile holt die neuesten Aspose.OCR‑Binärdateien und alle transitiven Abhängigkeiten. Kein manuelles DLL‑Handling erforderlich. + +## Schritt 2 – OCR‑Engine erstellen (Das Herz der Extraktion) + +Jetzt, wo die Bibliothek vorhanden ist, können wir eine Instanz von `OcrEngine` erstellen. Dieses Objekt ist für das **extracting text from image**‑Daten verantwortlich. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Warum das wichtig ist:** Die Engine kapselt die OCR‑Algorithmen, Sprachmodelle und Konfigurationsoptionen. Sie einmal zu instanziieren und über mehrere Bilder hinweg wiederzuverwenden ist sowohl speichereffizient als auch schnell. + +## Schritt 3 – Bild für OCR laden (und Sprache festlegen) + +Der nächste Schritt besteht darin, der Engine mitzuteilen, welches Bild gelesen werden soll. Hier kommt der Ausdruck **load image for OCR** zum Einsatz. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Randfall:** Wenn die Datei nicht existiert, wirft `Image.FromFile` eine `FileNotFoundException`. Umschließen Sie den Aufruf in einem try‑catch‑Block für Produktionscode. + +## Schritt 4 – OCR ausführen und Text extrahieren + +Nachdem das Bild geladen wurde, kann die Engine nun **extract text from image**. Die Methode `Recognize` übernimmt die schwere Arbeit. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Wenn alles gut geht, enthält `recognizedText` die reine Textdarstellung von allem, was die OCR‑Engine lesen konnte. + +## Schritt 5 – JPG in Text konvertieren (alles zusammenführen) + +Der Code, den wir bisher gebaut haben, **convert jpg to text** bereits, aber wir packen ihn in eine übersichtliche Methode, die Sie wiederholt aufrufen können. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Jetzt können Sie einfach Folgendes tun: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Erwartete Ausgabe** (gekürzt für Übersicht): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Wenn das Bild englischen Text enthält, ändern Sie `OcrLanguage.English` und Sie sehen die entsprechende Ausgabe. + +## Schritt 6 – Umgang mit häufigen „How to OCR Image“-Fragen + +### 6.1 Kann ich ein PNG oder BMP OCR‑en? + +Absolut. Die Methode `Image.FromFile` unterstützt alle Formate, die System.Drawing erkennt, sodass Sie einfach den Pfad zu einer `.png`‑ oder `.bmp`‑Datei angeben können und der Rest des Codes unverändert bleibt. + +### 6.2 Was, wenn das Bild eine niedrige Auflösung hat? + +Die OCR‑Genauigkeit sinkt dramatisch unter 300 dpi. Eine schnelle Lösung ist, das Bild mit `Graphics` hochzuskalieren, bevor es an die Engine übergeben wird: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Benötige ich eine Lizenz für Aspose.OCR? + +Aspose bietet eine kostenlose Testversion mit Wasserzeichen. Für den Produktionseinsatz kaufen Sie eine Lizenz und fügen Sie hinzu: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +## Voll funktionsfähiges Beispiel + +Unten finden Sie eine vollständige, sofort ausführbare Konsolenanwendung, die **how to OCR image**, **load image for OCR** und **convert jpg to text** in einem kompakten Paket demonstriert. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**So führen Sie es aus** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Sie sollten den extrahierten Text in der Konsole sehen, was bestätigt, dass Sie erfolgreich **extract text from image** mit C# durchgeführt haben. + +## Häufige Stolperfallen & Pro‑Tipps + +| Problem | Warum es passiert | Lösung | +|---------|-------------------|--------| +| Leere Ausgabe | Bild zu dunkel oder niedriger Kontrast. | Vorverarbeitung mit `Bitmap`, um die Helligkeit zu erhöhen. | +| Falsche Sprache | `Language`‑Eigenschaft bleibt auf dem Standard Englisch. | Setzen Sie explizit `ocrEngine.Language = OcrLanguage.Ukrainian;` (oder Ihre Zielsprache). | +| Speicher‑Fehler | Sehr große Bilder werden ohne Freigabe geladen. | Umschließen Sie `Image.FromFile` in einem `using`‑Block (wie gezeigt). | +| Lizenz‑Wasserzeichen | Ausführung einer Testversion ohne Lizenz. | Wenden Sie früh im `Main` eine gekaufte Lizenz an. | + +## Fazit + +Wir haben gerade alles behandelt, was Sie benötigen, um **extract text from image** in C# durchzuführen – von der Installation von Aspose.OCR, **loading image for OCR**, bis zum **convert jpg to text** und dem Umgang mit mehrsprachigen Szenarien. Das vollständige Beispielprogramm verbindet alle Teile und bietet Ihnen eine zuverlässige Grundlage für jedes OCR‑bezogene Projekt. + +Als Nächstes könnten Sie erkunden: + +* **how to OCR image**‑Streams anstelle von Dateien (verwenden Sie `MemoryStream`). +* Hinzufügen von **c# image to text**‑Nachbearbeitung wie Rechtschreibprüfung. +* Integration des OCR‑Schritts in eine größere Pipeline (z. B. Ergebnisse in einer Datenbank speichern). + +Fühlen Sie sich frei, mit verschiedenen Sprachen, Bildformaten und Vorverarbeitungs‑Tricks zu experimentieren. OCR ist ebenso Kunst wie Wissenschaft, und je mehr Sie spielen, desto bessere Ergebnisse erhalten Sie. + +Viel Spaß beim Coden, und mögen Ihre Bilder stets lesbar sein! + +## Verwandte Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/german/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..64eb89167 --- /dev/null +++ b/ocr/german/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-05-25 +description: Wie man OCR in C# verwendet, um Text aus Bilddateien zu extrahieren. + Lernen Sie, chinesische Zeichen aus einer JPG mit Aspose.OCR in wenigen einfachen + Schritten zu erkennen. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: de +og_description: Wie man OCR in C# verwendet, um Text aus Bilddateien zu extrahieren. + Dieser Leitfaden zeigt, wie man chinesische Zeichen aus einer JPG mit Aspose.OCR + erkennt. +og_title: Wie man OCR in C# verwendet – Chinesischen Text aus JPG erkennen +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Wie man OCR in C# verwendet – Chinesischen Text aus JPG erkennen +url: /de/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wie man OCR in C# verwendet – Chinesischen Text aus JPG erkennt + +Haben Sie sich jemals gefragt, **wie man OCR** verwendet, um Wörter aus einem Bild zu extrahieren, das Sie mit Ihrem Handy aufgenommen haben? Sie sind nicht allein. In vielen realen Projekten – denken Sie an Belegscanner, Übersetzungs‑Apps oder automatisierte Dateneingabe – müssen Sie **Text aus Bild**‑Dateien schnell und zuverlässig **extrahieren**. + +In diesem Tutorial führen wir Sie durch ein vollständiges, ausführbares Beispiel, das **Text aus JPG**‑Dateien erkennt und sogar den kniffligen Fall **chinesischer Zeichen erkennen** mithilfe des **OCR Chinese Simplified**‑Sprachpakets behandelt. Am Ende haben Sie eine eigenständige Konsolen‑App, die die erkannte Zeichenkette in der Konsole ausgibt, ohne dass zusätzliche manuelle Downloads erforderlich sind. + +> **Kurzer Hinweis:** Der Code funktioniert mit Aspose.OCR ≥ 23.7, das beim ersten Gebrauch automatisch Sprachressourcen herunterlädt. Wenn Sie eine ältere Version verwenden, müssen Sie die Sprache manuell hinzufügen. + +## Voraussetzungen + +- .NET 6.0 SDK oder neuer (das Beispiel zielt auf .NET 6, aber .NET 5 funktioniert ebenfalls) +- Eine aktuelle Version von Visual Studio 2022 oder VS Code mit der C#‑Erweiterung +- Eine Internetverbindung für den ersten Sprachdownload +- Ein JPG‑Bild, das vereinfachten chinesischen Text enthält (wir nennen es `chinese_sign.jpg`) + +Das war’s – keine schweren OCR‑Engines, kein Herumhantieren mit nativen DLLs. Nur ein paar NuGet‑Befehle und ein paar Code‑Zeilen. + +## Schritt 1: Aspose.OCR über NuGet installieren + +Zuerst benötigen wir die OCR‑Bibliothek. Öffnen Sie ein Terminal in Ihrem Projektordner und führen Sie aus: + +```bash +dotnet add package Aspose.OCR +``` + +Oder, wenn Sie die Visual‑Studio‑Benutzeroberfläche bevorzugen, klicken Sie mit der rechten Maustaste auf **Dependencies → Manage NuGet Packages**, suchen Sie nach „Aspose.OCR“ und klicken Sie auf **Install**. + +> **Profi‑Tipp:** Halten Sie Ihre Pakete aktuell. Neue Sprachpakete und Leistungsverbesserungen erscheinen in jeder Nebenveröffentlichung. + +## Schritt 2: Ein neues Konsolen‑Projekt erstellen (falls Sie noch keines haben) + +Wenn Sie von Grund auf neu beginnen, erstellen Sie eine neue Konsolen‑App: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Jetzt haben Sie eine `Program.cs`‑Datei, die bereit für den OCR‑Code ist. + +## Schritt 3: Den OCR‑Code schreiben – Vereinfachtes Chinesisch aus einem JPG erkennen + +Öffnen Sie `Program.cs` und ersetzen Sie dessen Inhalt durch das Folgende. Jede Zeile ist kommentiert, damit Sie sehen können *warum* wir jeden Schritt ausführen, nicht nur *was* wir tun. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Was passiert im Hintergrund? + +- **`OcrEngine.Language`** gibt Aspose an, welches Wörterbuch verwendet werden soll. Durch die Auswahl von `ChineseSimplified` weisen wir die Engine an, das Sprachpaket für vereinfachtes Chinesisch zu verwenden. +- **Erster Download**: Wenn `Recognize` ausgeführt wird, greift das SDK auf das CDN von Aspose zu, lädt die ≈6 MB‑Sprachdatei herunter, speichert sie lokal im Cache und fährt dann mit dem OCR fort. Nachfolgende Aufrufe sind sofortig. +- **`Image.FromFile`** funktioniert mit jedem Rasterformat, das .NET dekodieren kann – JPG, PNG, BMP – sodass Sie **Text aus Bild**‑Dateien vieler Typen extrahieren können, nicht nur aus JPG. + +## Schritt 4: Anwendung ausführen und Ausgabe überprüfen + +Builden und ausführen: + +```bash +dotnet run +``` + +Sie sollten etwa Folgendes sehen: + +``` +=== Recognized Text === +欢迎光临 +``` + +Wenn die Konsole Kauderwelsch oder eine leere Zeichenkette ausgibt, überprüfen Sie Folgendes: + +1. Das Bild enthält tatsächlich klare, hochkontrastierte chinesische Zeichen. +2. Der Dateipfad ist korrekt (keine überflüssigen Leerzeichen oder fehlende Erweiterungen). +3. Ihr Rechner kann `https://download.aspose.com` für das Sprachpaket erreichen. + +## Schritt 5: Umgang mit Randfällen und häufigen Stolperfallen + +### 5.1 Umgang mit Bildern niedriger Qualität + +Die OCR‑Genauigkeit sinkt, wenn das Quellbild unscharf, verrauscht oder schlecht beleuchtet ist. Eine schnelle Lösung ist die Vorverarbeitung des Bildes: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Ausführen in einer Headless‑Umgebung + +Wenn Sie in einen Linux‑Container ohne GUI bereitstellen, stellen Sie sicher, dass die Bibliothek `libgdiplus` (erforderlich für `System.Drawing`) installiert ist: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Sprachpaket manuell zwischenspeichern + +Sie können die Sprachdatei einmal herunterladen und Aspose über die `License`‑API darauf verweisen, wodurch der einmalige Netzwerkaufruf entfällt. Das ist praktisch für Offline‑Szenarien. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Vollständiges funktionierendes Beispiel (Alles‑in‑einem) + +Unten finden Sie das *vollständige* Programm, das Sie in `Program.cs` kopieren‑und‑einfügen können. Keine versteckten Teile, keine externen Skripte. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Erwartete Ausgabe + +Wenn das JPG die Phrase „欢迎光临“ enthält, gibt die Konsole aus: + +``` +=== Recognized Text === +欢迎光临 +``` + +Sie können das Bild gerne durch ein anderes vereinfachtes chinesisches Schild, Straßennamen oder Produktetikett ersetzen – die Engine wird ihr Bestes geben. + +## Fazit + +Wir haben gerade **wie man OCR** in C# verwendet, um **Text aus Bild**‑Dateien zu **extrahieren**, speziell die Herausforderung **chinesische Zeichen erkennen** in einem **JPG** zu bewältigen. Durch die Nutzung des On‑the‑Fly‑Sprachdownloads von Aspose.OCR können Sie Ihre Bereitstellung leichtgewichtig halten und gleichzeitig **OCR Chinese Simplified** sofort unterstützen. + +Was kommt als Nächstes? Probieren Sie diese Ideen aus: + +- **Batch‑Verarbeitung**: Durchlaufen Sie einen Ordner mit Bildern und schreiben Sie jedes Ergebnis in eine CSV. +- **Kombination mit Übersetzungs‑APIs**: Geben Sie die erkannte Zeichenkette an Azure Translator weiter für Echtzeit‑Mehrsprachen‑Apps. +- **Weitere Sprachen erkunden**: Ersetzen Sie `OcrLanguage.ChineseSimplified` durch `Japanese` oder `Arabic` und sehen Sie, wie sich derselbe Code anpasst. + +Haben Sie Fragen zur Leistungsoptimierung, Lizenzierung oder zur Integration von OCR in einen Web‑Service? Hinterlassen Sie unten einen Kommentar – happy coding! + +--- + +![Screenshot der Konsolenausgabe, die zeigt, wie man OCR in C# verwendet, um chinesischen Text aus einem JPG‑Bild zu erkennen](ocr-chinese-demo.png "wie man OCR Konsolenausgabe verwendet") + + +## Verwandte Tutorials + +- [Bildtext in C# mit Sprachauswahl mittels Aspose.OCR extrahieren](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Text in Bild mit Aspose OCR für mehrere Sprachen erkennen](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Wie man Text aus Bild extrahiert, indem man Rechtecke für OCR vorbereitet](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/german/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/german/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..e86f4511a --- /dev/null +++ b/ocr/german/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Erfahren Sie, wie Sie russischen Text in C# per OCR verarbeiten und Text + aus einem Bild mit Aspose OCR extrahieren. Schritt‑für‑Schritt‑Code, um Bilder schnell + in Text in C# zu konvertieren. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: de +og_description: OCR russischer Text in C# leicht gemacht. Lernen Sie, Text aus einem + Bild zu extrahieren, ein Bild in Text zu konvertieren und ein Bild für OCR mit Aspose + OCR zu laden. +og_title: OCR für russischen Text in C# – Vollständiger Aspose OCR Leitfaden +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR von russischem Text in C# – Vollständiger Leitfaden mit Aspose OCR +url: /de/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR russischen Text in C# – Vollständige Anleitung mit Aspose OCR + +Schon einmal russischen Text in C# per OCR verarbeiten müssen, aber nicht gewusst, welche Bibliothek vertrauenswürdig ist? Sie sind nicht allein. Saubere, lesbare Zeichen aus einem kyrillischen Bild zu erhalten, kann sich anfühlen wie das Entschlüsseln geheimer Botschaften – besonders wenn das richtige Sprachmodell nicht eingestellt ist. + +In diesem Tutorial führen wir Sie durch ein praxisnahes Beispiel, das zeigt, wie man **Text aus Bild**‑Dateien extrahiert, *Image‑to‑Text C#*‑Stil konvertiert und die Feinheiten der russischen Spracherkennung mit Aspose OCR behandelt. Am Ende haben Sie eine sofort ausführbare Konsolen‑App, die ein Bild für OCR lädt, die erkannte Zeichenkette ausgibt und Ihnen eine solide Grundlage für weiterführende Szenarien bietet. + +## Was Sie lernen werden + +- Wie man **Aspose OCR C#** für die Unterstützung der russischen Sprache installiert und konfiguriert. +- Die genauen Schritte, um **Bild für OCR zu laden** und die Engine aufzurufen. +- Tipps zum Umgang mit häufigen Fallstricken wie fehlenden Sprachressourcen oder unscharfen Scans. +- Möglichkeiten, die Lösung zu erweitern, z. B. Stapelverarbeitung mehrerer Dateien oder Anpassen von Vertrauensschwellen. + +Vorkenntnisse mit Aspose sind nicht erforderlich; ein grundlegendes Verständnis von C# und .NET reicht aus, um loszulegen. + +## Voraussetzungen + +Bevor wir starten, stellen Sie sicher, dass Sie Folgendes haben: + +1. **.NET 6.0** (oder neuer) SDK installiert – der Code funktioniert sowohl auf .NET Core als auch auf .NET Framework. +2. **Visual Studio 2022** (oder jede IDE Ihrer Wahl). +3. Ein **Aspose.OCR für .NET** NuGet‑Paket – Sie können einen kostenlosen Testschlüssel von der Aspose‑Website erhalten. +4. Eine **Russisch‑Sprachmodell**‑Datei (`rus.traineddata`) – laden Sie sie von der Aspose‑Ressourcenseite herunter und legen Sie sie in einen Ordner, den Sie später referenzieren. +5. Ein Beispielbild (`russian_doc.png`) mit klar lesbarem kyrillischem Text. + +Alles vorhanden? Großartig – lassen Sie uns beginnen. + +## Schritt 1: Projekt einrichten und Aspose OCR installieren + +Zuerst ein neues Konsolenprojekt erstellen: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Jetzt das Aspose OCR‑Paket hinzufügen: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro‑Tipp:** Wenn Sie eine Testlizenz verwenden, halten Sie die Datei `Aspose.Total.lic` bereit; Sie laden sie im Code, um Wasserzeichen zu vermeiden. + +Nachdem das Paket installiert ist, öffnen Sie `Program.cs`. Sie sehen die Standard‑`Main`‑Methode – ersetzen Sie deren Inhalt durch das Gerüst, das wir erstellen werden. + +## Schritt 2: OCR‑Engine für die russische Sprache konfigurieren + +Das Herzstück der Operation ist das Objekt `OcrEngine`. Wir müssen ihm zwei Dinge mitteilen: welche Sprache erkannt werden soll und wo die Sprachmodell‑Dateien zu finden sind. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Warum das wichtig ist:** Wenn Sie das Setzen von `Language = OcrLanguage.Russian` überspringen, verwendet die Engine standardmäßig Englisch, und kyrillische Zeichen erscheinen als wirre Symbole. Der `ResourceFolder` verweist auf das Verzeichnis, das die Datei `rus.traineddata` enthält; ohne diesen wirft Aspose eine *resource not found*‑Ausnahme. + +## Schritt 3: Bild für OCR laden + +Jetzt müssen wir das **Bild für OCR laden**. Aspose OCR arbeitet mit `System.Drawing.Image`, sodass Sie jedes unterstützte Format (PNG, JPEG, BMP usw.) übergeben können. Stellen Sie sicher, dass der Dateipfad korrekt ist; relative Pfade sind in Ordnung, wenn Sie das Bild neben der ausführbaren Datei ablegen. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Randfall:** Wenn das Bild groß ist (über 5 MB), sollten Sie es zuerst verkleinern. Die OCR‑Genauigkeit sinkt, wenn die DPI zu niedrig ist, aber riesige Dateien können zu Speicherbelastungen führen. Eine schnelle Größenänderung kann bei Bedarf mit `Graphics` durchgeführt werden. + +## Schritt 4: Text erkennen – Von Bild zu Text im C#‑Stil + +Mit der konfigurierten Engine und dem geladenen Bild erfolgt die eigentliche Erkennung mit einem einzigen Aufruf: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Wenn Sie das Programm ausführen (`dotnet run`), sollten Sie etwas Ähnliches sehen: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Wenn die Ausgabe wie Kauderwelsch aussieht, überprüfen Sie Folgendes: + +- Die Datei `rus.traineddata` ist im `ResourceFolder` vorhanden. +- Das Bild ist nicht zu unscharf; erwägen Sie, vor der OCR einen einfachen Binarisierungsfilter anzuwenden. +- Die Spracheinstellung ist tatsächlich `OcrLanguage.Russian`. + +## Schritt 5: Feinabstimmung und häufige Fallstricke + +### Anpassen des Vertrauensschwellenwerts + +Aspose OCR gibt intern für jedes Zeichen einen Vertrauenswert zurück. Obwohl die API ihn nicht direkt bereitstellt, können Sie **detaillierte Ausgabe** aktivieren, um zu sehen, welche Wörter ein geringes Vertrauen haben: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Wenn Sie häufig Fehlinterpretationen bemerken, versuchen Sie: + +- **Vorverarbeitung**: Bild in Graustufen konvertieren, Kontrast erhöhen oder einen Medianfilter anwenden. +- **DPI‑Einstellungen**: Stellen Sie sicher, dass das Bild mindestens 300 DPI für kyrillische Schriften hat. + +### Stapelverarbeitung mehrerer Bilder + +Wenn Sie **Text aus Bild**‑Dateien in großen Mengen extrahieren müssen, kapseln Sie die Erkennungslogik in einer Schleife: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Jetzt erhält jede PNG-Datei ihr eigenes `.txt`‑Gegenstück – praktisch für die Dokumentenarchivierung. + +### Umgang mit Unicode‑Ausgabe + +Kyrillische Zeichen sind Unicode, stellen Sie also sicher, dass Ihre Konsolen‑Kodierung sie darstellen kann: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Platzieren Sie diese Zeile direkt nach dem Beginn der `Main`‑Methode. Ohne sie sehen Sie möglicherweise Fragezeichen (`?`) anstelle russischer Buchstaben. + +## Vollständiges funktionierendes Beispiel + +Unten finden Sie den vollständigen, sofort ausführbaren Code. Kopieren Sie ihn in `Program.cs`, passen Sie die Pfade an, und Sie können loslegen. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Erwartete Ausgabe** (angenommen das Beispielbild enthält „Пример текста на русском языке.“): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Wenn Sie etwas anderes sehen, gehen Sie die Fehlersuch‑Tipps in Schritt 5 erneut durch. + +## Fazit + +Sie haben nun ein solides End‑to‑End‑Beispiel, wie man **russischen Text** in C# mit Aspose OCR per OCR verarbeitet. Von der Installation der Bibliothek, über die Konfiguration des russischen Sprachmodells bis hin zum Laden eines Bildes und der Umwandlung in sauberen Unicode‑Text ist alles abgedeckt. + +Denken Sie daran, dass der Schlüssel zu zuverlässiger OCR gutes Ausgangsmaterial ist: klare Schriftarten, ausreichende DPI und die richtigen Sprachressourcen. Sobald Sie die Grundlagen beherrschen, können Sie zur Stapelverarbeitung übergehen, die Integration mit Cloud‑Speicher vornehmen oder sogar KI‑Nachbearbeitung für Rechtschreibprüfung kombinieren. + +### Was kommt als Nächstes? + +- Erkunden Sie erweiterte Optionen von **aspose ocr c#** wie Layout‑Analyse oder PDF‑Ausgabe. +- Kombinieren Sie dies mit **Text aus Bild extrahieren**‑Workflows in Azure Functions für serverlose Verarbeitung. +- Probieren Sie verschiedene Sprachen aus – wechseln Sie einfach `OcrLanguage.Russian` zu `OcrLanguage.English` oder einem anderen unterstützten Code. + +Haben Sie Fragen oder ein kniffliges Bild, das nicht mitarbeiten will? Hinterlassen Sie unten einen Kommentar, und viel Spaß beim Coden! + +![Beispiel für OCR russischen Text](ocr-russian-example.png){alt="Beispiel für OCR russischen Text"} + +## Verwandte Tutorials + +- [Bildtext in C# mit Sprachauswahl mit Aspose.OCR extrahieren](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Bildtext mit Aspose OCR für mehrere Sprachen erkennen](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Text aus Bild mit Aspose.OCR .NET extrahieren](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/german/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..a7fd2d15e --- /dev/null +++ b/ocr/german/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: Texterkennung aus Bild mit Aspose OCR in C#. Erfahren Sie, wie Sie ein + Bild für OCR laden, die OCR-Sprache festlegen, die OCR-Engine erstellen und Text + aus einer TIFF-Datei extrahieren. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: de +og_description: Texterkennung aus Bild mit Aspose OCR in C#. Dieses Tutorial zeigt, + wie man eine OCR‑Engine erstellt, ein Bild für OCR lädt, die OCR‑Sprache festlegt + und Text aus einer TIFF‑Datei extrahiert. +og_title: Text aus Bild mit Aspose OCR erkennen – Vollständiger C#‑Leitfaden +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Text aus Bild mit Aspose OCR erkennen – Vollständiger C#‑Leitfaden +url: /de/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Text aus Bild mit Aspose OCR erkennen – Vollständiger C# Leitfaden + +Haben Sie schon einmal **Text aus einem Bild** erkennen müssen, waren sich aber nicht sicher, welche Bibliothek sowohl Geschwindigkeit als auch Genauigkeit liefert? Sie sind nicht allein. In vielen Rechnungs‑Verarbeitungs‑ oder Archivierungsprojekten ist das größte Problem, sauberen, durchsuchbaren Text aus TIFF‑Dateien zu erhalten, ohne einen eigenen Parser zu schreiben. + +Der springende Punkt: Aspose OCR für .NET macht diese gesamte Pipeline zu einem Kinderspiel. In diesem Leitfaden gehen wir Schritt für Schritt durch alles, was Sie benötigen — Installation des Pakets, **Erstellung einer OCR‑Engine**, Laden eines TIFF, Festlegen der OCR‑Sprache und schließlich **Extrahieren von Text aus TIFF**. Am Ende haben Sie eine sofort einsatzbereite Konsolen‑App, die **Text aus Bild**‑Dateien im Handumdrehen erkennt. + +## Voraussetzungen + +- .NET 6.0 oder höher (der Code funktioniert auch mit .NET Core und .NET Framework) +- Visual Studio 2022 (oder jede andere IDE Ihrer Wahl) +- Aspose.OCR NuGet‑Paket (GPU‑Unterstützung erfordert das Add‑on `Aspose.OCR.Gpu`) +- Eine GPU mit CUDA‑Unterstützung, wenn Sie die zusätzliche Geschwindigkeit wollen (optional, aber empfohlen) + +> **Pro‑Tipp:** Wenn Sie keine GPU haben, lassen Sie einfach die Zeile `GpuDevice` weg und die Engine wechselt automatisch zurück zur CPU. + +## Schritt 1: Aspose OCR installieren und OCR‑Engine erstellen + +Zuerst fügen Sie die benötigten Pakete via NuGet hinzu: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Jetzt können wir **die OCR‑Engine erstellen**. Dieses Objekt ist das Herzstück des Prozesses; es enthält Konfigurationen wie das Gerät, auf dem ausgeführt wird, und Speicherlimits. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Warum das wichtig ist:** Durch das Binden der Engine an eine GPU reduzieren Sie die Zeit, die zum **Erkennen von Text aus Bild** benötigt wird, drastisch – besonders bei großen Stapeln hochauflösender TIFF‑Dateien. + +## Schritt 2: Bild für OCR laden + +Als Nächstes müssen wir **das Bild für OCR laden**. Aspose.OCR arbeitet mit `System.Drawing.Image`, sodass jedes von GDI+ unterstützte Format (inklusive mehrseitiger TIFF) funktioniert. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Wenn Sie mit einem mehrseitigen TIFF arbeiten, können Sie über die Seiten mit `image.SelectActiveFrame` iterieren, aber für die meisten Szenarien reicht ein einzelner Aufruf aus. + +## Schritt 3: OCR‑Sprache festlegen + +Die Engine weiß nicht von selbst, welche Sprache Sie scannen. **Setzen Sie die OCR‑Sprache**, bevor Sie den Erkenner starten; sonst erhalten Sie ein Durcheinander an Zeichen. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Wussten Sie schon?** Das Wechseln der Sprache zur Laufzeit ist kaum kostenintensiv — Sie können sogar ein Dokument mit gemischten Sprachen verarbeiten, indem Sie diese Eigenschaft zwischen den Seiten ändern. + +## Schritt 4: Erkennung durchführen – Text aus Bild erkennen + +Jetzt kommt der spaßige Teil: tatsächlich **Text aus Bild erkennen**. Die Methode `Recognize` liefert einen einfachen String mit allen erkannten Zeichen. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Falls Sie Vertrauenswerte oder Begrenzungsrahmen benötigen, können Sie die Überladung verwenden, die ein `OcrResult`‑Objekt zurückgibt, aber für die meisten Extraktionsaufgaben reicht der reine String aus. + +## Schritt 5: Text aus TIFF extrahieren (und mehrseitige Dateien verarbeiten) + +Wenn die Quelle ein TIFF mit mehreren Seiten ist, sollten Sie die Schritte 2‑4 für jedes Frame wiederholen. Hier ein kurzer Loop, der **Text aus TIFF** Seite für Seite **extrahiert**: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Der obige Code gibt den extrahierten Text für jede Seite aus, sodass Sie die Ergebnisse mühelos in eine Datenbank oder einen Such‑Index leiten können. + +## Schritt 6: Extrahierten Text anzeigen oder speichern + +Abschließend **zeigen wir den extrahierten Text an** und schreiben ihn optional in eine Datei für die spätere Verarbeitung. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Beim Ausführen des Programms sollten die erkannten Zeichen ausgegeben und die Datei `extracted_text.txt` neben Ihrem Quell‑TIFF erstellt werden. + +--- + +## Häufige Fragen & Sonderfälle + +- **Was, wenn meine GPU nicht erkannt wird?** + Entfernen Sie die Zeile `GpuDevice`; die Engine schaltet automatisch in den CPU‑Modus um. Die Performance ist langsamer, aber die Ergebnisse bleiben genau. + +- **Kann ich PNG‑ oder JPEG‑Dateien verarbeiten?** + Absolut — `Image.FromFile` funktioniert mit jedem Format, das von System.Drawing unterstützt wird, sodass Sie **Bild für OCR laden** können, egal welche Dateierweiterung vorliegt. + +- **Wie gehe ich mit niedrig aufgelösten Scans um?** + Erhöhen Sie `ocrEngine.PreprocessOptions.Dpi`, bevor Sie `Recognize` aufrufen. Ein höherer DPI‑Wert liefert der Engine mehr Pixel zum Arbeiten und verbessert die Genauigkeit. + +- **Gibt es ein Limit für die Größe des TIFF?** + Die Eigenschaft `GpuMemoryLimit` begrenzt den GPU‑Speicherverbrauch. Wenn das Limit erreicht wird, wechselt die Engine für die restlichen Seiten zur CPU. + +--- + +## Fazit + +Sie besitzen jetzt ein vollständiges, produktionsreifes Snippet, das **Text aus Bild**‑Dateien mit Aspose OCR in C# erkennt. Das Tutorial zeigte, wie man **eine OCR‑Engine erstellt**, **ein Bild für OCR lädt**, **die OCR‑Sprache festlegt** und **Text aus TIFF extrahiert** — alles unter Nutzung von GPU‑Beschleunigung für maximale Geschwindigkeit. + +Von hier aus können Sie: + +- Mit verschiedenen Sprachen experimentieren (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` usw.). +- Die Ausgabe in einen durchsuchbaren ElasticSearch‑Index integrieren. +- Nachbearbeitung hinzufügen (Rechtschreibprüfung, Regex‑Bereinigung), um die Datenqualität zu erhöhen. + +Probieren Sie es an Ihrem eigenen Rechnung‑Stapel aus, passen Sie die Speicherlimits an und beobachten Sie, wie die OCR‑Leistung in die Höhe schießt. Viel Spaß beim Coden! + +## Verwandte Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..2e56a5a57 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 με λίστες εύκολα. Αυξήστε την παραγωγικότητα και την εξαγωγή δεδομένων στις εφαρμογές σας. +### [Δημιουργία μηχανής OCR σε C# – Πλήρης Οδηγός](./create-ocr-engine-in-c-complete-guide/) +Μάθετε πώς να δημιουργήσετε και να ρυθμίσετε μια μηχανή OCR σε C# χρησιμοποιώντας το Aspose.OCR, βήμα‑βήμα, με παραδείγματα κώδικα. ### Κοινές Περιπτώσεις Χρήσης - **Εξαγωγή κειμένου από εικόνες** σε σαρωμένα τιμολόγια για αυτοματοποιημένη λογιστική. @@ -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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/greek/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..d653ef9aa --- /dev/null +++ b/ocr/greek/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Δημιουργήστε μηχανή OCR σε C# και μάθετε πώς να ελέγχετε τη λειτουργία + αξιολόγησης και την κατάσταση άδειας χρήσης σε λίγες γραμμές κώδικα. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: el +og_description: Δημιουργήστε μηχανή OCR σε C# και δείτε αμέσως πώς να εντοπίσετε τη + λειτουργία αξιολόγησης και να εμφανίσετε την κατάσταση άδειας. +og_title: Δημιουργία μηχανής OCR σε C# – Οδηγός βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Δημιουργία μηχανής OCR σε C# – Πλήρης οδηγός +url: /el/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Δημιουργία OCR Engine σε C# – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ πώς να **δημιουργήσετε OCR engine** αντικείμενα σε C# χωρίς να ψάχνετε σε ατέλειωτη τεκμηρίωση; Δεν είστε οι μόνοι. Πολλοί προγραμματιστές συναντούν πρόβλημα όταν πρέπει να εκκινήσουν ένα OCR engine, να ελέγξουν αν λειτουργεί σε λειτουργία δοκιμής και να εμφανίσουν την κατάσταση αδειοδότησης στους χρήστες. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα σύντομο, ολοκληρωμένο παράδειγμα που **δημιουργεί ένα OCR engine**, ελέγχει τη **λειτουργία αξιολόγησης του OCR engine** και εκτυπώνει ένα φιλικό μήνυμα σχετικά με την κατάσταση αδειοδότησης. Στο τέλος θα έχετε μια έτοιμη για εκτέλεση εφαρμογή console και ένα σαφές μοντέλο για τη διαχείριση της αδειοδότησης OCR στα δικά σας έργα. + +## Τι θα μάθετε + +- Πώς να δημιουργήσετε ένα στιγμιότυπο `OcrEngine` (ο πυρήνας κάθε ροής OCR). +- Γιατί η ανίχνευση της **λειτουργίας αξιολόγησης** είναι σημαντική για τη συμμόρφωση και την εμπειρία χρήστη. +- Ο καλύτερος τρόπος για να **ελέγξετε την άδεια OCR** και να αντιδράσετε σε απρόσμενες καταστάσεις. +- Συνηθισμένα προβλήματα — αναφορές null, διαχείριση εξαιρέσεων και ασυμφωνίες εκδόσεων. + +Δεν απαιτούνται εξωτερικά εργαλεία πέρα από το OCR SDK που έχετε ήδη εγκαταστήσει. Αν είστε εξοικειωμένοι με τη βασική σύνταξη C#, είστε έτοιμοι. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερη (ο κώδικας μεταγλωττίζεται με .NET Core και .NET Framework). +- Ένα OCR SDK που εκθέτει μια κλάση `OcrEngine` με ιδιότητα `IsEvaluation` (π.χ. το υποθετικό `MyOcrSdk`). +- Ένας επεξεργαστής κειμένου ή IDE (Visual Studio, VS Code, Rider — διαλέξτε **το** αγαπημένο σας). + +Αυτό είναι όλο. Ας βουτήξουμε. + +## Βήμα 1: Δημιουργία Νέου Project Console + +Πρώτα, δημιουργήστε μια νέα εφαρμογή console ώστε να μπορείτε να τρέξετε τον κώδικα απομονωμένα. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Ανοίξτε το παραγόμενο `Program.cs`. Θα αντικαταστήσουμε το περιεχόμενό του με ένα πλήρες παράδειγμα που **δημιουργεί OCR engine** στιγμιότυπα και διαχειρίζεται την αδειοδότηση. + +## Βήμα 2: Εισαγωγή του Namespace του OCR SDK + +Υποθέτοντας ότι το SDK έχει προστεθεί μέσω NuGet (`MyOcrSdk` είναι placeholder), προσθέστε τη δήλωση `using` στην κορυφή του αρχείου. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Αν δεν έχετε προσθέσει το πακέτο ακόμη, εκτελέστε: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Διατηρείτε την έκδοση του SDK ενημερωμένη· οι νεότερες εκδόσεις συχνά βελτιώνουν την ανίχνευση λειτουργίας αξιολόγησης. + +## Βήμα 3: Δημιουργία του Στιγμιότυπου OCR Engine + +Τώρα τελικά **δημιουργούμε OCR engine** αντικείμενα. Αυτό είναι η καρδιά κάθε ροής OCR — σκεφτείτε το ως τον εγκέφαλο που θα διαβάσει τις εικόνες αργότερα. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Γιατί είναι κρίσιμο αυτό το βήμα; Η `OcrEngine` περιλαμβάνει όλες τις ρυθμίσεις, τα πακέτα γλωσσών και τα δεδομένα αδειοδότησης. Χωρίς αυτήν δεν μπορείτε να επεξεργαστείτε εικόνες ή να ελέγξετε τη σημαία αξιολόγησης. + +> **Side note:** Κάποια SDK επιτρέπουν τη μεταβίβαση αντικειμένου ρυθμίσεων στον κατασκευαστή (π.χ. γλώσσα, DPI). Αν χρειάζεστε προσαρμοσμένες ρυθμίσεις, τροποποιήστε τη γραμμή αναλόγως. + +## Βήμα 4: Προσδιορισμός της Λειτουργίας Αξιολόγησης του OCR Engine + +Οι περισσότεροι προμηθευτές OCR παρέχουν μια δοκιμαστική έκδοση που λειτουργεί σε **λειτουργία αξιολόγησης** μέχρι να δοθεί έγκυρο κλειδί άδειας. Η γνώση του αν βρίσκεστε σε δοκιμαστική λειτουργία σας επιτρέπει να εμφανίσετε κατάλληλα UI cues ή να περιορίσετε ορισμένες λειτουργίες. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Η ιδιότητα `IsEvaluation` επιστρέφει `true` όταν η μηχανή δεν είναι αδειοδοτημένη ή χρησιμοποιεί δοκιμαστική άδεια περιορισμένου χρόνου. Είναι ένας γρήγορος, αξιόπιστος τρόπος για να προστατεύσετε τις premium λειτουργίες. + +### Τι γίνεται αν λείπει η ιδιότητα; + +Παλαιότερες εκδόσεις SDK μπορεί να εκθέτουν μέθοδο όπως `GetLicenseInfo()` αντί για αυτήν. Σε αυτήν την περίπτωση, θα εξετάζατε το αντικείμενο που επιστρέφεται για μια σημαία `IsTrial`. Πάντα συμβουλευτείτε το changelog του SDK όταν κάνετε αναβάθμιση. + +## Βήμα 5: Εμφάνιση της Τρέχουσας Κατάστασης Αδειοδότησης + +Τέλος, ας δείξουμε στον χρήστη αν η μηχανή είναι αδειοδοτημένη ή ακόμα σε δοκιμαστική λειτουργία. Μια απλή εντολή `Console.WriteLine` κάνει τη δουλειά, αλλά μπορείτε να την προσαρμόσετε για εφαρμογές GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Ο τελεστής ternary κρατά τον κώδικα καθαρό, και τα μηνύματα είναι αρκετά σαφή για τελικούς χρήστες ή προγραμματιστές που διαβάζουν logs. + +## Πλήρες Παράδειγμα Λειτουργίας + +Συνδυάζοντας όλα τα παραπάνω, εδώ είναι ένα αυτόνομο πρόγραμμα που μπορείτε να αντιγράψετε‑επικολλήσετε στο `Program.cs` και να τρέξετε με `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Αναμενόμενο Αποτέλεσμα + +- **Δοκιμαστική έκδοση:** + `Running in evaluation mode – limited functionality.` + +- **Αδειοδοτημένη έκδοση:** + `Licensed – full OCR capabilities enabled.` + +Αν το SDK ρίξει εξαίρεση (π.χ. λείπει native DLL), το block `catch` θα εκτυπώσει ένα χρήσιμο μήνυμα σφάλματος αντί να **καταρρεύσει ολόκληρη η εφαρμογή**. + +## Διαχείριση Ακραίων Περιπτώσεων και Συνηθισμένων Παγίδων + +### 1. Στιγμιότυπα Engine που Είναι Null + +Αν και ο κατασκευαστής συνήθως επιστρέφει ένα έγκυρο αντικείμενο, κάποια SDK μπορεί να επιστρέψουν `null` αν λείπουν απαιτούμενες native εξαρτήσεις. Προστατέψτε τον κώδικα: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Λήξη Άδειας Κατά τη Διάρκεια Εκτέλεσης + +Μια δοκιμαστική άδεια μπορεί να λήξει κατά τη διάρκεια μιας συνεδρίας. Επανα‑ελέγχετε περιοδικά το `IsEvaluation` αν η εφαρμογή σας παραμένει ενεργή για μεγάλο χρονικό διάστημα. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Διαφορετικά Ονόματα Ιδιοτήτων σε Διαφορετικές Εκδόσεις + +Παλαιότερες εκδόσεις μπορεί να εκθέτουν `engine.EvaluationMode` ή `engine.License.IsTrial`. Όταν κάνετε αναβάθμιση, ψάξτε στις σημειώσεις έκδοσης του SDK για breaking changes. + +### 4. Σενάρια Πολυνηματικότητας + +Αν δημιουργείτε πολλούς OCR workers, δημιουργήστε **ένα OCR engine ανά νήμα** εκτός αν το SDK υποστηρίζει ρητά κοινή χρήση μεταξύ νημάτων. Η κοινή χρήση ενός μόνο engine μπορεί να οδηγήσει σε race conditions και λανθασμένες αναγνώσεις αδειοδότησης. + +## Pro Tips για Παραγωγική Χρήση + +- **Cache την κατάσταση αδειοδότησης** μετά τον πρώτο έλεγχο ώστε να αποφεύγετε περιττές κλήσεις ιδιοτήτων. +- **Καταγράψτε το κλειδί άδειας** (μασκαρισμένο) κατά την εκκίνηση για audit trails — βοηθά τις ομάδες υποστήριξης να διαγνώσουν προβλήματα αδειοδότησης. +- **Παρέχετε ένα UI toggle** που ενημερώνει τους χρήστες ότι βρίσκονται σε δοκιμαστική λειτουργία και προσφέρει κουμπί “Buy License”. +- **Αυτοματοποιήστε την ανανέωση της άδειας** χρησιμοποιώντας το API ενεργοποίησης του SDK, αν υπάρχει, ώστε η εμπειρία χρήστη να παραμένει αδιάσπαστη. + +## Συμπέρασμα + +Μόλις **δημιουργήσαμε OCR engine** αντικείμενα σε λίγες γραμμές, εξετάσαμε τη **λειτουργία αξιολόγησης του OCR engine** και εκτυπώσαμε ένα σαφές μήνυμα **κατάστασης αδειοδότησης OCR**. Το πλήρες παράδειγμα τρέχει αμέσως, διαχειρίζεται σφάλματα με χάρη και εξηγεί το «γιατί» πίσω από κάθε βήμα — ώστε να το προσαρμόσετε σε desktop, web ή server‑side σενάρια. + +Στη συνέχεια, μπορείτε να εξερευνήσετε: + +- Εισαγωγή εικόνων στο `engine.Recognize` και διαχείριση υποστήριξης πολλαπλών γλωσσών. +- Χρήση των APIs **check OCR license** για προγραμματιστική ενεργοποίηση αγορασμένου κλειδιού. +- Ενσωμάτωση με UI frameworks (WinForms, WPF, MAUI) για εμφάνιση ετικετών αδειοδότησης. + +Δοκιμάστε τα και θα έχετε μια ισχυρή βάση OCR έτοιμη για οποιαδήποτε εφαρμογή. Καλό κώδικα! + +## Σχετικά Tutorials + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/ocr-optimization/_index.md b/ocr/greek/net/ocr-optimization/_index.md index afd528c89..90d7b2f59 100644 --- a/ocr/greek/net/ocr-optimization/_index.md +++ b/ocr/greek/net/ocr-optimization/_index.md @@ -70,6 +70,8 @@ weight: 25 Αποκτήστε το πλήρες δυναμικό του Aspose.OCR for .NET με τον ολοκληρωμένο μας οδηγό. Μάθετε βήμα‑βήμα πώς να προετοιμάσετε ορθογώνια για την αναγνώριση εικόνας. Αναβαθμίστε τις .NET εφαρμογές σας με αδιάλειπτη ενσωμάτωση OCR. ### [Preprocessing Filters for Image in OCR Image Recognition](./preprocessing-filters-for-image/) Εξερευνήστε το Aspose.OCR for .NET. Βελτιώστε την ακρίβεια OCR με φίλτρα προεπεξεργασίας. Κατεβάστε τώρα για αδιάλειπτη ενσωμάτωση. +### [Προεπεξεργασία εικόνας για OCR – Πλήρης οδηγός Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Μάθετε πώς να προετοιμάσετε εικόνες για OCR με πλήρη οδηγό σε C# χρησιμοποιώντας Aspose. ### [Result Correction with Spell Checking in OCR Image Recognition](./result-correction-with-spell-checking/) Αυξήστε την ακρίβεια OCR με Aspose.OCR for .NET. Διορθώστε ορθογραφικά λάθη, προσαρμόστε λεξικά και επιτύχετε αναγνώριση κειμένου χωρίς σφάλματα με ευκολία. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) diff --git a/ocr/greek/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/greek/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..dc3b236cf --- /dev/null +++ b/ocr/greek/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Προεπεξεργασία εικόνας για OCR με το Aspose ώστε να βελτιώσετε την ακρίβεια + του OCR και εκτέλεση OCR σε αρχεία JPEG. Μάθετε πώς να εξάγετε κείμενο χρησιμοποιώντας + το Aspose σε έναν σαφή, βήμα‑βήμα οδηγό. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: el +og_description: Προεπεξεργασία εικόνας για OCR με το Aspose για βελτίωση της ακρίβειας + του OCR. Ακολουθήστε αυτόν τον οδηγό για να εκτελέσετε OCR σε JPEG και να εξάγετε + κείμενο χρησιμοποιώντας το Aspose σε C#. +og_title: Προεπεξεργασία εικόνας για OCR – Οδηγός Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Προεπεξεργασία εικόνας για OCR – Πλήρης οδηγός Aspose C# +url: /el/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Προεπεξεργασία Εικόνας για OCR – Πλήρης Οδηγός Aspose C# + +Έχετε αναρωτηθεί ποτέ πώς να **προεπεξεργαστείτε εικόνα για OCR** ώστε το κείμενο να βγαίνει καθαρό κάθε φορά; Δεν είστε μόνοι—οι προγραμματιστές αντιμετωπίζουν συνεχώς θορυβώδεις σκαναρίσματα, JPEG με χαμηλή αντίθεση και απρόβλεπτο φωτισμό. Το καλό νέο; Με μερικές έξυπνες ρυθμίσεις μπορείτε να **βελτιώσετε την ακρίβεια του OCR** δραματικά, και το Aspose το κάνει εύκολο. + +Σε αυτό το tutorial θα περάσουμε από ένα πραγματικό παράδειγμα που δείχνει πώς να **τρέξετε OCR σε JPEG** εικόνες, να εφαρμόσετε μια προσαρμοσμένη αλυσίδα επεξεργασίας εικόνας και τελικά να **εξάγετε κείμενο χρησιμοποιώντας το Aspose**. Στο τέλος θα έχετε ένα έτοιμο κομμάτι κώδικα C# που μπορείτε να ενσωματώσετε σε οποιοδήποτε .NET project. + +## Τι Θα Μάθετε + +- Γιατί η προεπεξεργασία είναι σημαντική και ποια φίλτρα προσφέρουν τη μεγαλύτερη βελτίωση. +- Πώς να ρυθμίσετε το `ImageProcessingOptions` του Aspose.OCR για διόρθωση κλίσης, αποθορυβοποίηση, δυαδικοποίηση και ενίσχυση αντίθεσης. +- Τον ακριβή κώδικα που χρειάζεται για **να τρέξετε OCR σε JPEG** αρχεία και να λάβετε καθαρό κείμενο. +- Συμβουλές και παγίδες που κρατούν την αλυσίδα OCR σας αξιόπιστη σε παραγωγή. + +Δεν απαιτείται προηγούμενη εμπειρία με το Aspose· αρκεί μια βασική γνώση C# και Visual Studio (ή το αγαπημένο σας IDE). Ας ξεκινήσουμε. + +![Παράδειγμα προεπεξεργασίας εικόνας για OCR](preprocess-ocr.png "Προεπεξεργασία εικόνας για OCR") + +## Βήμα 1: Ρύθμιση του Μηχανήματος Aspose.OCR – Προεπεξεργασία Εικόνας για OCR + +Πρώτα απ’ όλα. Χρειαζόμαστε μια παρουσία `OcrEngine` και πρέπει να της πούμε ποια γλώσσα περιμένουμε. Στις περισσότερες περιπτώσεις η προεπιλογή είναι τα Αγγλικά, αλλά μπορείτε να την αλλάξετε σε Γαλλικά, Γερμανικά κ.λπ., τροποποιώντας το enum `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Γιατί είναι σημαντικό:** Η μηχανή είναι η καρδιά της λειτουργίας· χωρίς αυτή δεν μπορείτε να εφαρμόσετε κανένα από τα φίλτρα εικόνας που στην πραγματικότητα **προεπεξεργάζονται την εικόνα για OCR**. Σκεφτείτε τη σαν την κουζίνα όπου αναμιγνύονται όλα τα υλικά. + +## Βήμα 2: Δημιουργία Προσαρμοσμένης Αλυσίδας Επεξεργασίας Εικόνας – Βελτίωση Ακρίβειας OCR + +Τώρα έρχεται το νόστιμο μέρος. Το Aspose σας επιτρέπει να συνδέσετε πολλά φίλτρα μαζί. Παρακάτω ενεργοποιούμε τέσσερα από τα πιο αποτελεσματικά: + +1. **Deskew** – ευθυγραμμίζει κεκλιμένα έγγραφα (μέγιστη κλίση 5° εξ ορισμού). +2. **Denoise** – εξομαλύνει θορυβώδεις φόντους. +3. **Binarize** – μετατρέπει την εικόνα σε ασπρόμαυρη χρησιμοποιώντας ένα κατώφλι. +4. **ContrastBoost** – κάνει τους αδύναμους χαρακτήρες πιο εμφανείς. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** Αν οι πηγές σας είναι ήδη καθαρές, μπορείτε να μειώσετε το `Strength` ή να απενεργοποιήσετε εντελώς ένα φίλτρο. Η υπερβολική επεξεργασία μπορεί μερικές φορές να σβήσει αδύναμους χαρακτήρες, οπότε πειραματιστείτε με πραγματικά δείγματα. + +## Βήμα 3: Φόρτωση του JPEG (ή Οποιασδήποτε Εικόνας) και Εκτέλεση OCR – Εκτέλεση OCR σε JPEG + +Το Aspose υποστηρίζει οποιαδήποτε μορφή εικόνας μπορεί να διαβάσει το .NET—JPEG, PNG, BMP, ό,τι θέλετε. Ακολουθεί ο τρόπος με τον οποίο τροφοδοτείτε ένα αρχείο JPEG στη μηχανή και ξεκινάτε τη διαδικασία αναγνώρισης. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Γιατί JPEG;** Η συμπίεση JPEG συχνά εισάγει τεχνουργήματα που μπερδεύουν το OCR. Η αλυσίδα προεπεξεργασίας μας, ειδικά τα βήματα αποθορυβοποίησης και δυαδικοποίησης, μετριάζουν αυτά τα προβλήματα, επιτρέποντάς σας να **τρέξετε OCR σε JPEG** με σιγουριά. + +## Βήμα 4: Έξοδος του Αναγνωρισμένου Κειμένου – Εξαγωγή Κειμένου Χρησιμοποιώντας το Aspose + +Τέλος, απλώς γράφουμε το κείμενο στην κονσόλα, σε αρχείο ή σε οποιαδήποτε downstream υπηρεσία. Για επίδειξη, η κονσόλα είναι αρκετή. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Όταν τρέξετε το πρόγραμμα, θα δείτε κάτι σαν: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Αν η έξοδος φαίνεται ακατάστατη, επιστρέψτε στο **Βήμα 2** και προσαρμόστε τις ρυθμίσεις των φίλτρων. Μικρές προσαρμογές συχνά αποδίδουν μεγάλες βελτιώσεις στην **βελτίωση της ακρίβειας OCR**. + +## Συνηθισμένες Ακραίες Περιπτώσεις και Πώς να τις Διαχειριστείτε + +| Κατάσταση | Προτεινόμενη Προσαρμογή | +|-----------|------------------------| +| **Πολύ σκοτεινές εικόνες** | Αυξήστε το `ContrastBoost.Level` σε 1.5 ή περισσότερο. | +| **Κλίση > 5°** | Αυξήστε το `DeskewOptions.MaxAngle` (π.χ., 10.0) ή προ-γυρίστε την εικόνα χειροκίνητα. | +| **Χρωματικό κείμενο σε χρωματικό φόντο** | Χρησιμοποιήστε `BinarizeOptions` με προσαρμοσμένο κατώφλι ή μεταβείτε σε `AdaptiveBinarizeOptions`. | +| **Μεγάλα αρχεία ( > 5 MB )** | Φορτώστε την εικόνα σε `MemoryStream` πρώτα για να αποφύγετε προβλήματα κλειδώματος αρχείου. | + +Αυτές οι ρυθμίσεις κρατούν την αλυσίδα σας ευέλικτη και έτοιμη για το μέλλον, ειδικά όταν χρειάζεται να **εξάγετε κείμενο χρησιμοποιώντας το Aspose** από διαφορετικές πηγές. + +## Πλήρες Παράδειγμα – Όλα τα Βήματα σε Ένα Σημείο + +Παρακάτω βρίσκεται το πλήρες, έτοιμο για αντιγραφή‑και‑επικόλληση πρόγραμμα. Συμβαδίζει με .NET 6+ και απαιτεί μόνο το πακέτο NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Αποθηκεύστε το ως `Program.cs`, προσθέστε το πακέτο Aspose.OCR (`dotnet add package Aspose.OCR`) και τρέξτε `dotnet run`. Θα δείτε το καθαρισμένο κείμενο να εμφανίζεται στην κονσόλα. + +## Ανακεφαλαίωση – Γιατί Λειτουργεί Αυτή η Προσέγγιση + +- **Προεπεξεργασία εικόνας για OCR**: Η αλυσίδα αφαιρεί τις πιο κοινές πηγές σφάλματος (κλίση, θόρυβος, χαμηλή αντίθεση). +- **Βελτίωση ακρίβειας OCR**: Κάθε φίλτρο ρυθμίζεται ώστε να αυξάνει το σήμα‑προς‑θόρυβο που βλέπει η μηχανή. +- **Εκτέλεση OCR σε JPEG**: Ακόμη και οι συμπιεσμένες εικόνες γίνονται αναγνώσιμες μετά τη διόρθωση κλίσης και τη δυαδικοποίηση. +- **Εξαγωγή κειμένου χρησιμοποιώντας το Aspose**: Η μέθοδος `Recognize` επιστρέφει μια απλή συμβολοσειρά, έτοιμη για οποιαδήποτε downstream λογική. + +Συνδυαστικά, αυτά τα βήματα σας παρέχουν μια αξιόπιστη, παραγωγική λύση OCR με λίγες μόνο γραμμές κώδικα. + +## Επόμενα Βήματα και Σχετικά Θέματα + +- **Batch processing** – Επανάληψη πάνω σε φάκελο εικόνων και αποθήκευση κάθε αποτελέσματος σε αρχείο `.txt`. +- **Language packs** – Αντικαταστήστε το `OcrLanguage.English` με `OcrLanguage.Spanish` ή προσθέστε προσαρμοσμένα λεξικά. +- **PDF extraction** – Συνδυάστε Aspose.OCR με Aspose.PDF για άμεση εξαγωγή κειμένου από σαρωμένα PDF. +- **Performance tuning** – Εκτελέστε τη μηχανή παράλληλα με `Parallel.ForEach` για μεγάλα φορτία εργασίας. + +Μη διστάσετε να πειραματιστείτε με τις τιμές των φίλτρων, να δοκιμάσετε διαφορετικές μορφές εικόνας ή να προσθέσετε επιπλέον φίλτρα Aspose όπως `SharpnessOptions`. Ο ουρανός είναι το όριο μόλις κυριαρχήσετε τα βασικά. + +--- + +*Καλό κώδικα! Αν αντιμετωπίσετε προβλήματα, αφήστε ένα σχόλιο παρακάτω και θα τα λύσουμε μαζί.* + +## Σχετικά Tutorials + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/greek/net/text-recognition/_index.md b/ocr/greek/net/text-recognition/_index.md index 7c0b04e8c..487eaee55 100644 --- a/ocr/greek/net/text-recognition/_index.md +++ b/ocr/greek/net/text-recognition/_index.md @@ -55,9 +55,24 @@ url: /el/net/text-recognition/ Ξεκλειδώστε τις δυνατότητες του OCR στο .NET με το Aspose.OCR. Εξαγωγή κειμένου από αρχεία PDF χωρίς κόπο. Κάντε λήψη τώρα για μια απρόσκοπτη εμπειρία ενσωμάτωσης. ### [Αναγνώριση πίνακα στην Αναγνώριση εικόνας OCR](./recognize-table/) Ξεκλειδώστε τις δυνατότητες του Aspose.OCR για .NET με τον ολοκληρωμένο οδηγό μας για την αναγνώριση πινάκων στην αναγνώριση εικόνας OCR. +### [Αναγνώριση κειμένου από εικόνα με Aspose OCR – Πλήρης Οδηγός C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Ανακαλύψτε πώς να αναγνωρίζετε κείμενο από εικόνες χρησιμοποιώντας Aspose OCR σε πλήρη οδηγό C#. +### [Πώς να χρησιμοποιήσετε OCR σε C# – Αναγνώριση Κινέζικου κειμένου από JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Μάθετε πώς να εφαρμόσετε το Aspose.OCR σε C# για την αναγνώριση κινεζικού κειμένου από αρχεία JPG, βήμα προς βήμα. +### [OCR Ρωσικού κειμένου σε C# – Πλήρης Οδηγός με Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Μάθετε πώς να αναγνωρίζετε ρωσικό κείμενο σε εικόνες με Aspose OCR σε C#. Ακολουθήστε τον βήμα‑βήμα οδηγό για ακριβή αποτελέσματα. +### [Εξαγωγή κειμένου από εικόνα σε C# – Πλήρης οδηγός Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Μάθετε πώς να εξάγετε κείμενο από εικόνες χρησιμοποιώντας Aspose OCR σε C# με πλήρη βήμα‑βήμα οδηγό. +### [Εξαγωγή κειμένου από εικόνα σε ASP.NET Core Minimal API – Πλήρης Οδηγός](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Μάθετε πώς να εξάγετε κείμενο από εικόνες χρησιμοποιώντας Aspose OCR σε ASP.NET Core Minimal API με πλήρη βήμα‑βήμα οδηγό. +### [c# OCR σεμινάριο: Εξαγωγή κειμένου από αποδείξεις PNG με Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Μάθετε πώς να εξάγετε κείμενο από αποδείξεις PNG χρησιμοποιώντας Aspose OCR σε C# με βήμα‑βήμα οδηγίες. +### [Μετατροπή TIFF σε κείμενο σε C# – Πλήρης Οδηγός Batch OCR](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Μάθετε πώς να μετατρέπετε αρχεία TIFF σε κείμενο με 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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/greek/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..4594749b4 --- /dev/null +++ b/ocr/greek/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR tutorial που δείχνει πώς να φορτώσετε αρχείο εικόνας c# και να + αναγνωρίσετε κείμενο png από απόδειξη χρησιμοποιώντας το Aspose OCR – βήμα‑βήμα + οδηγός. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: el +og_description: c# OCR tutorial που σας καθοδηγεί στη φόρτωση αρχείου εικόνας c# και + στην αναγνώριση κειμένου png από απόδειξη χρησιμοποιώντας το Aspose OCR. +og_title: c# OCR οδηγός – Εξαγωγή κειμένου από αποδείξεις PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR tutorial: Εξαγωγή κειμένου από αποδείξεις PNG με Aspose' +url: /el/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Εξαγωγή Κειμένου από Αποδείξεις PNG με Aspose + +Έχετε ποτέ χρειαστεί ένα **c# OCR tutorial** που πραγματικά ολοκληρώνει τη δουλειά χωρίς ατέλειωτη αναζήτηση στο Google; Βρίσκεστε στο σωστό μέρος. Σε αυτόν τον οδηγό θα **load image file c#**, **recognize png text**, και **read receipt OCR** αποτελέσματα, όλα ενώ σας δείχνουμε πώς να **perform OCR image** επεξεργασία με το Aspose OCR. + +Θα ξεκινήσουμε εγκαθιστώντας το απαιτούμενο πακέτο NuGet, θα περάσουμε γραμμή-γραμμή τον κώδικα, και θα τελειώσουμε με ένα καθαρό JSON dump που μπορείτε να μεταβιβάσετε απευθείας στην επόμενη διαδρομή δεδομένων σας. Χωρίς περιττά, μόνο μια πρακτική, έτοιμη‑για‑εκτέλεση λύση. + +## Τι Θα Μάθετε + +- Πώς να ρυθμίσετε το Aspose OCR σε ένα έργο .NET 6 (ή νεότερο). +- Τα ακριβή βήματα για **load an image file c#** και να το παραδώσετε στη μηχανή. +- Πώς να **recognize png text** από μια εικόνα απόδειξης και να καταγράψετε το αποτέλεσμα. +- Τρόποι για **read receipt OCR** έξοδο ως ωραία μορφοποιημένο JSON. +- Συμβουλές για **perform OCR image** λειτουργίες σε διαφορετικούς τύπους αρχείων και διαχείριση κοινών προβλημάτων. + +**Απαιτούμενα** +- Visual Studio 2022 (ή οποιοδήποτε IDE προτιμάτε). +- .NET 6 SDK ή νεότερο. +- Μια εικόνα απόδειξης PNG διαθέσιμη (θα την ονομάσουμε `receipt.png`). + +Αν τα έχετε αυτά, ας ξεκινήσουμε. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR Tutorial – Ρύθμιση του Μηχανήματος Aspose OCR + +Πρώτα απ' όλα, χρειαζόμαστε τη βιβλιοθήκη Aspose OCR. Ανοίξτε το τερματικό σας στον φάκελο της λύσης και εκτελέστε: + +```bash +dotnet add package Aspose.OCR +``` + +Αυτή η εντολή φέρνει όλα τα απαραίτητα, συμπεριλαμβανομένων των εγγενών δυαδικών αρχείων για την αποκωδικοποίηση εικόνας. Μόλις εγκατασταθεί, δημιουργήστε ένα νέο έργο κονσόλας ή προσθέστε τον κώδικα σε ένα υπάρχον. + +### Why Aspose? + +Το Aspose OCR υποστηρίζει πάνω από 30 γλώσσες, λειτουργεί εκτός σύνδεσης και επιστρέφει ένα πλούσιο αντικείμενο `OcrResult`—ιδανικό για εργασίες **perform OCR image** όπου χρειάζεστε περισσότερα από απλό κείμενο. + +## Load image file c# και Προετοιμασία της Απόδειξης + +Τώρα που η βιβλιοθήκη είναι έτοιμη, ας **load image file c#**. Η κλάση `System.Drawing.Image` κάνει το σκληρό έργο, αλλά μπορείτε επίσης να χρησιμοποιήσετε το `SkiaSharp` αν προτιμάτε μια εναλλακτική δια‑πλατφόρμα. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** Τυλίξτε το `Image` σε μια δήλωση `using` (όπως φαίνεται) για να ελευθερώσετε άμεσα τους εγγενείς πόρους—ιδιαίτερα σημαντικό όταν **perform OCR image** σε πολλά αρχεία σε βρόχο. + +## Recognize PNG text with Aspose + +Με την εικόνα στη μνήμη, η μηχανή μπορεί τώρα να **recognize png text**. Το Aspose επιστρέφει ένα `OcrResult` που περιέχει τόσο τη ακατέργαστη συμβολοσειρά όσο και λεπτομερή δεδομένα για κάθε αναγνωρισμένη λέξη. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Γιατί να καλέσετε το `RecognizeWithResult` αντί για το πιο απλό `Recognize`; Το πρώτο σας δίνει πρόσβαση σε βαθμολογίες εμπιστοσύνης, περιοριστικά πλαίσια και αλλαγές γραμμής—χρήσιμο αν αργότερα χρειαστείτε **read receipt OCR** για εξαγωγή στοιχείων γραμμής. + +## Read receipt OCR Result ως JSON + +Τα περισσότερα downstream συστήματα αγαπούν το JSON, οπότε ας σειριοποιήσουμε το `OcrResult`. Ο σειριοποιητής `System.Text.Json` διαχειρίζεται πολύπλοκα αντικείμενα άψογα, και θα ενεργοποιήσουμε την εσοχή για ευανάγνωστη μορφή. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Το παραγόμενο JSON φαίνεται κάπως έτσι (κομμένο για συντομία): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Τώρα μπορείτε να μεταβιβάσετε το `jsonResult` σε μια βάση δεδομένων, μια ουρά μηνυμάτων, ή απλώς να το καταγράψετε για εντοπισμό σφαλμάτων. + +## Perform OCR Image Processing και Εμφάνιση Αποτελέσματος + +Τέλος, εξάγετε το JSON στην κονσόλα. Σε μια πραγματική εφαρμογή πιθανότατα θα το γράφατε σε αρχείο ή θα το στέλνατε μέσω HTTP, αλλά η κονσόλα το κάνει εύκολο για να επαληθεύσετε ότι όλα λειτούργησαν. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Εκτελέστε το πρόγραμμα (`dotnet run`) και θα πρέπει να δείτε το ωραία μορφοποιημένο JSON εκτυπωμένο. Αν η εικόνα της απόδειξης είναι καθαρή, το κείμενο θα είναι ακριβές· αν όχι, σκεφτείτε να αυξήσετε την ανάλυση της εικόνας ή να εφαρμόσετε ένα φίλτρο προεπεξεργασίας (π.χ., γκρι κλίμακα, ενίσχυση αντίθεσης) πριν το δώσετε στη μηχανή. + +### Διαχείριση Συνηθισμένων Περιπτώσεων Άκρων + +| Situation | What to do | +|-----------|------------| +| **Η εικόνα είναι θολή** | Προεπεξεργαστείτε με `System.Drawing` για να ενισχύσετε την ευκρίνεια ή να αυξήσετε το DPI. | +| **Η απόδειξη περιέχει πολλές γλώσσες** | Ορίστε `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Μεγάλη επεξεργασία παρτίδας** | Ξαναχρησιμοποιήστε ένα μόνο αντικείμενο `OcrEngine`; αλλάξτε μόνο το `Image` σε κάθε επανάληψη. | +| **Πίεση μνήμης** | Αποδεσμεύστε άμεσα τα αντικείμενα `Image` και σκεφτείτε `await Task.Run` για ασύγχρονες διαδρόμους. | + +Αυτές οι προσαρμογές διατηρούν τη ροή εργασίας **perform OCR image** ανθεκτική ακόμη και όταν η είσοδος δεν είναι τέλεια. + +## Συμπέρασμα + +Συγχαρητήρια—μόλις ολοκληρώσατε ένα **c# OCR tutorial** που φορτώνει μια εικόνα, **recognizes png text**, και **reads receipt OCR** έξοδο ως καθαρό JSON. Τα βασικά βήματα (ρύθμιση μηχανής, φόρτωση εικόνας, εκτέλεση OCR, σειριοποίηση και εμφάνιση) αποτελούν μια σταθερή βάση που μπορείτε να επεκτείνετε σε τιμολόγια, διαβατήρια ή οποιοδήποτε άλλο σαρωμένο έγγραφο. + +### Τι Έρχεται Στη Σειρά; + +- Πειραματιστείτε με **load image file c#** χρησιμοποιώντας `SkiaSharp` για αληθινή δια‑πλατφορμική υποστήριξη. +- Βυθιστείτε περισσότερο στο `OcrResult.Words` για να εξάγετε στοιχεία γραμμής, τιμές και ημερομηνίες—ιδανικό για εφαρμογές παρακολούθησης εξόδων. +- Συνδυάστε αυτόν τον οδηγό με Azure Functions ή AWS Lambda για να δημιουργήσετε ένα serverless API επεξεργασίας αποδείξεων. + +Νιώστε ελεύθεροι να τροποποιήσετε τον κώδικα, να προσθέσετε περισσότερες εικόνες, ή ακόμη και να αλλάξετε σε διαφορετικό πακέτο γλώσσας. Ο κόσμος του OCR είναι γεμάτος εκπλήξεις, και τώρα έχετε τα εργαλεία για να τις εξερευνήσετε. + +Καλό προγραμματισμό, και εύχομαι οι αποδείξεις σας πάντα να είναι αναγνώσιμες! + +## Σχετικά Μαθήματα + +- [Εξαγωγή κειμένου εικόνας C# με επιλογή γλώσσας χρησιμοποιώντας Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Εξαγωγή κειμένου από εικόνα – Βελτιστοποίηση OCR με Aspose.OCR για .NET](/ocr/english/net/ocr-optimization/) +- [Πώς να χρησιμοποιήσετε OCR - Αναγνώριση εικόνας χωρίς ανίχνευση περιοχής κειμένου](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/greek/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..60d9b0242 --- /dev/null +++ b/ocr/greek/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-05-25 +description: Μετατρέψτε TIFF σε κείμενο χρησιμοποιώντας το Aspose.OCR σε C#. Μάθετε + τη μαζική μετατροπή εικόνας σε κείμενο και εξάγετε κείμενο από αρχεία TIFF αποδοτικά. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: el +og_description: Μετατρέψτε TIFF σε κείμενο με το Aspose.OCR. Αυτός ο οδηγός δείχνει + τη μαζική μετατροπή εικόνας σε κείμενο και πώς να εξάγετε κείμενο από αρχεία TIFF + σε λίγες γραμμές C#. +og_title: Μετατροπή TIFF σε κείμενο με C# – Πλήρης οδηγός Batch OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Μετατροπή TIFF σε Κείμενο με C# – Πλήρης Οδηγός Batch OCR +url: /el/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convert TIFF to Text in C# – Complete Batch OCR Guide + +Έχετε χρειαστεί ποτέ να **μετατρέψετε TIFF σε κείμενο** αλλά δεν ήξερες από πού να ξεκινήσεις; Δεν είστε μόνοι—πολλοί προγραμματιστές αντιμετωπίζουν δυσκολίες με το batch OCR όταν δουλεύουν με σαρωμένα έγγραφα. Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από μια πρακτική λύση που **εξάγει κείμενο από αρχεία TIFF** χρησιμοποιώντας το Aspose.OCR, και θα το κάνουμε παράλληλα ώστε μεγάλοι φάκελοι να ολοκληρώνονται σε δευτερόλεπτα. + +Θα αγγίξουμε επίσης τις βέλτιστες πρακτικές για **batch image to text conversion**, ώστε στο τέλος να έχετε ένα επαναχρησιμοποιήσιμο snippet που μετατρέπει ολόκληρο έναν κατάλογο σαρωμένων εικόνων σε καθαρά *.txt* αρχεία—ιδανικό για ευρετηρίαση, αναζήτηση ή τροφοδότηση σε downstream analytics. + +## What You’ll Need + +- **.NET 6.0** ή νεότερο (ο κώδικας μεταγλωττίζεται και σε .NET Framework) +- **Aspose.OCR for .NET** πακέτο NuGet (`Install-Package Aspose.OCR`) +- Ένας φάκελος που περιέχει ένα ή περισσότερα *.tif* αρχεία (η κλασική μορφή σάρωσης TIFF) +- Το αγαπημένο σας IDE (Visual Studio, VS Code, Rider—ό,τι προτιμάτε) + +Αυτό είναι όλο. Χωρίς εξωτερικές υπηρεσίες, χωρίς API keys, μόνο καθαρό C# και Aspose. + +![Screenshot of a TIFF file being processed and the resulting text file](/images/ocr-result.png "OCR result showing converted TIFF to text output") + +*(Alt text: Screenshot showing converted TIFF to text output on screen)* + +## Step 1: Set Up the OCR Engine – Convert TIFF to Text + +Πρώτα απ’ όλα, χρειαζόμαστε μια παρουσία `OcrEngine` που να γνωρίζει ότι πρέπει να διαβάσει αγγλικούς χαρακτήρες. Η μηχανή είναι η καρδιά της μετατροπής· η σωστή ρύθμιση της εξασφαλίζει αξιόπιστα αποτελέσματα. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Why this matters:* +Το Aspose.OCR υποστηρίζει δεκάδες γλώσσες. Αν εργάζεστε με πολυγλωσσικά scans, απλώς αλλάξτε το `OcrLanguage.English` στην κατάλληλη τιμή του enum. Η παράλειψη ορισμού γλώσσας ωθεί τη μηχανή σε λειτουργία auto‑detect, η οποία μπορεί να είναι πιο αργή και λιγότερο ακριβής. + +## Step 2: Gather All TIFF Files – Extract Text from TIFF Efficiently + +Στη συνέχεια συλλέγουμε κάθε αρχείο *.tif* από έναν φάκελο που καθορίζετε. Η χρήση του `Directory.GetFiles` μας δίνει έναν καθαρό πίνακα που μπορούμε να περάσουμε στον batch processor. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro tip:* Η σημαία `SearchOption.AllDirectories` μπορεί να χρησιμοποιηθεί αν τα scans σας είναι τοποθετημένα σε υπο‑φακέλους. Θυμηθείτε ότι η βαθύτερη αναδρομή μπορεί να αυξήσει τη χρήση μνήμης κατά το batch βήμα. + +## Step 3: Perform Parallel OCR – Batch Image to Text Conversion + +Τώρα το διασκεδαστικό μέρος. Το Aspose.OCR παρέχει έναν στατικό βοηθό `BatchOcr.RecognizeAll` που δέχεται έναν πίνακα διαδρομών αρχείων, μια μηχανή, και μια υπόδειξη `parallelism`. Θα δημιουργήσουμε τέσσερα νήματα, που σε ένα σύγχρονο quad‑core laptop προσφέρει σχεδόν γραμμική επιτάχυνση. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Why parallelism?* +Η επεξεργασία ενός batch υψηλής ανάλυσης TIFF μπορεί να είναι απαιτητική για την CPU. Με το να διανείμουμε τη δουλειά σε πολλαπλά νήματα κρατάμε όλους τους πυρήνες απασχολημένους, μειώνοντας δραστικά το συνολικό χρόνο εκτέλεσης. Αν τρέχετε αυτόν τον κώδικα σε server με περισσότερους πυρήνες, αυξήστε την τιμή του `parallelism` ανάλογα. + +## Step 4: Write the Output – Convert Scanned Images TXT Files + +Τέλος, διατρέχουμε το λεξικό και γράφουμε κάθε κομμάτι κειμένου σε ένα αρχείο *.txt* που μοιράζεται το αρχικό όνομα βάσης. Αυτή είναι η στιγμή που το **convert scanned images txt** γίνεται πραγματικότητα. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### What the code does, in plain English + +1. **Create** an OCR engine set for English. +2. **Collect** every TIFF file from the target folder. +3. **Run** `BatchOcr.RecognizeAll` with four threads, turning each image into a string. +4. **Loop** over the results, swapping the `.tif` extension for `.txt` and writing the string to disk. + +Αυτή είναι η πλήρης ροή **convert TIFF to text** σε λιγότερο από 50 γραμμές κώδικα. + +## Handling Edge Cases – When Things Don’t Go Smoothly + +- **Missing or corrupted TIFFs** – `BatchOcr` will throw an `OcrException`. Wrap the call in a `try / catch` if you need graceful degradation. +- **Non‑English documents** – change `OcrLanguage.English` to `OcrLanguage.Spanish`, `OcrLanguage.French`, etc., or use `OcrLanguage.AutoDetect`. +- **Very large images** – consider lowering the DPI before OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) to save memory, though you may lose some accuracy. +- **Output encoding** – if you need a specific code page (e.g., Windows‑1252), pass it to `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Pro Tips for Robust Batch Conversions + +- **Log failures**: create a `List failedFiles` and append any file that throws; write the list to a log after the loop. +- **Reuse the engine**: the same `OcrEngine` instance can be reused across many files; don’t instantiate inside the loop. +- **Validate the result**: a quick `if (string.IsNullOrWhiteSpace(extractedText))` can flag scans that were blank or unreadable. +- **Combine with PDF**: if your source is a multi‑page PDF, convert each page to TIFF first (Aspose.PDF does that) and then run this batch. + +## Next Steps – Going Beyond Simple Conversion + +Now that you can **extract text from TIFF** files in bulk, you might want to: + +- Feed the *.txt* files into a search index (Elasticsearch, Azure Cognitive Search). +- Run language detection on each result to route documents to locale‑specific pipelines. +- Generate searchable PDFs by overlaying the OCR text back onto the original images (Aspose.PDF again). + +All of those scenarios build on the same core idea: **batch image to text conversion** is a building block for larger document‑processing systems. + +--- + +### Conclusion + +You’ve just learned how to **convert TIFF to text** using Aspose.OCR, process an entire folder in parallel, and save each result as a clean *.txt* file. The solution is lightweight, fully configurable, and ready for production—whether you’re digitizing legacy invoices, archiving scanned contracts, or powering a text‑search engine. + +Give it a spin, tweak the parallelism, and start feeding those newly minted text files into whatever workflow you need. Happy OCRing! + +--- + + +## Related Tutorials + +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/greek/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..b1f641e3e --- /dev/null +++ b/ocr/greek/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Μάθετε πώς να εξάγετε κείμενο από εικόνα με ένα ελάχιστο API ASP.NET + Core. Ανεβάστε την εικόνα μέσω POST, διαβάστε τα multipart form data και εκτελέστε + OCR στην εικόνα. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: el +og_description: Εξάγετε κείμενο από εικόνα χρησιμοποιώντας ένα ελαφρύ API ASP.NET + Core. Αυτός ο οδηγός δείχνει πώς να ανεβάσετε εικόνα μέσω POST, να διαβάσετε δεδομένα + multipart form και να εκτελέσετε OCR στην εικόνα. +og_title: Εξαγωγή κειμένου από εικόνα σε ASP.NET Core – Βήμα‑προς‑βήμα +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Εξαγωγή κειμένου από εικόνα σε ASP.NET Core Minimal API – Πλήρης οδηγός +url: /el/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εξαγωγή Κειμένου από Εικόνα σε ASP.NET Core Minimal API – Πλήρης Οδηγός + +Έχετε αναρωτηθεί ποτέ πώς να **εξάγετε κείμενο από εικόνα** χωρίς να παλεύετε με βαριές πλατφόρμες; Δεν είστε μόνοι. Πολλοί προγραμματιστές χρειάζονται έναν γρήγορο τρόπο για να επιτρέπουν στους χρήστες να ανεβάζουν μια φωτογραφία και να λαμβάνουν πίσω τους ακατέργαστους χαρακτήρες, είτε πρόκειται για σάρωση αποδείξεων, ψηφιοποίηση χειρόγραφων σημειώσεων, είτε για τροφοδοσία ενός ευρετηρίου αναζήτησης. + +Σε αυτό το tutorial θα δημιουργήσουμε ένα μικρό ASP.NET Core Minimal API που **ανεβάζει εικόνα μέσω POST**, αναλύει το φορτίο *multipart/form‑data* και στη συνέχεια **εκτελεί OCR στην εικόνα** χρησιμοποιώντας ένα singleton `OcrEngine`. Στο τέλος θα έχετε μια πλήρως εκτελέσιμη εφαρμογή που μπορείτε να ενσωματώσετε σε οποιοδήποτε έργο .NET 8 και να αρχίσετε αμέσως να εξάγετε κείμενο από εικόνα. + +## Τι Θα Δημιουργήσετε + +- Μια ελαφριά web εφαρμογή που ακούει στο `/ocr`. +- Ένα endpoint που δέχεται αρχείο εικόνας αποσταλμένο με αίτημα POST τύπου `multipart/form-data`. +- Λογική που διαβάζει το ανεβασμένο αρχείο, το περνά στη μηχανή OCR και επιστρέφει αποτελέσματα σε απλό κείμενο. +- Προαιρετικό απόσπασμα επιτάχυνσης GPU (σχολιασμένο) για όσους διαθέτουν συμβατή κάρτα. + +**Προαπαιτούμενα** +- .NET 8 SDK (ή νεότερο). +- Βασική εξοικείωση με C# και τη γραμμή εντολών. +- Μια βιβλιοθήκη OCR που εκθέτει μια κλάση `OcrEngine` (το παράδειγμα υποθέτει ένα υποθετικό πακέτο NuGet). + +Αν τα έχετε, ας βουτήξουμε. + +## Βήμα 1: Ρύθμιση του Έργου και Προσθήκη του Πακέτου OCR + +First, create a new web project and pull in the OCR library. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Συμβουλή επαγγελματία:** Διατηρήστε τις εξαρτήσεις σας ενημερωμένες. Οι νεότερες εκδόσεις συχνά προσφέρουν βελτιώσεις απόδοσης, ειδικά για GPU‑επιταχυμένη εκτίμηση. + +## Βήμα 2: Καταχώρηση ενός Singleton OCR Engine (Κύρια Υπηρεσία) + +We want a single `OcrEngine` instance for the whole app—no need to spin up a new engine per request. Register it in the builder’s service container. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Γιατί singleton;** +Η δημιουργία μιας μηχανής OCR μπορεί να είναι δαπανηρή—σκεφτείτε τη φόρτωση βαρών νευρωνικού δικτύου στη μνήμη. Με την επαναχρησιμοποίηση της ίδιας παρουσίας εξοικονομούμε τόσο κύκλους CPU όσο και RAM, κάτι που μεταφράζεται σε ταχύτερους χρόνους απόκρισης για κάθε κλήση `/ocr`. + +## Βήμα 3: Κατασκευή της Εφαρμογής + +Now we materialize the `WebApplication` object. + +```csharp +var app = builder.Build(); +``` + +Αυτή η γραμμή φαίνεται σχεδόν μαγική, αλλά στο παρασκήνιο ρυθμίζει το routing, το middleware και το DI container που μόλις διαμορφώσαμε. + +## Βήμα 4: Ορισμός του POST Endpoint – “Ανέβασμα Εικόνας μέσω POST” + +Here’s the heart of the tutorial: an endpoint that **upload image via POST**, reads the multipart payload, and hands the data to the OCR engine. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Ανάλυση της Λογικής + +| Βήμα | Τι Συμβαίνει | Γιατί Είναι Σημαντικό | +|------|--------------|------------------------| +| **ReadFormAsync** | Αναλύει το εισερχόμενο αίτημα *multipart/form-data*. | Χωρίς αυτό, δεν μπορείτε να έχετε πρόσβαση στα ανεβασμένα αρχεία. | +| **form.Files["image"]** | Ανακτά το αρχείο του οποίου το όνομα πεδίου φόρμας είναι `image`. | Εγγυάται ένα προβλέψιμο συμβόλαιο για τους καλούντες. | +| **Content‑type check** | Επικυρώνει ότι το αρχείο είναι εικόνα (π.χ., `image/png`). | Αποτρέπει τη μηχανή OCR από το να «πνίγει» με δεδομένα που δεν είναι εικόνα. | +| **Image.FromStream** | Μετατρέπει το ακατέργαστο stream σε ένα `System.Drawing.Image`. | Η βιβλιοθήκη OCR αναμένει ένα αντικείμενο `Image`, όχι έναν ακατέργαστο πίνακα bytes. | +| **ocr.Recognize(img)** | Καλεί τη μηχανή OCR για **πώς να αναγνωρίσει κείμενο από εικόνα**. | Αυτό είναι το βασικό βήμα **εκτέλεσης OCR στην εικόνα**. | +| **Results.Text** | Επιστρέφει την απάντηση σε απλό κείμενο. | Μια απλή, καταναλώσιμη μορφή για τις επόμενες υπηρεσίες. | + +## Βήμα 5: Εκτέλεση του API + +Finally, start the web server. + +```csharp +app.Run(); +``` + +When you execute `dotnet run`, the API will listen on `http://localhost:5000` (or a port of your choosing). You can test it with `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Αναμενόμενη έξοδος:** Η κονσόλα θα εκτυπώσει τους αναγνωρισμένους χαρακτήρες, π.χ.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Αν η εικόνα είναι θολή ή η γλώσσα δεν υποστηρίζεται, η μηχανή OCR θα επιστρέψει μια κενή συμβολοσειρά ή ένα μήνυμα σφάλματος—χειριστείτε αυτές τις περιπτώσεις σε κώδικα παραγωγής. + +## Περιπτώσεις Άκρων & Καλές Πρακτικές + +### 1. Μεγάλα Αρχεία + +The default request body limit is 30 MB. For larger scans you might need to adjust: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Ασύγχρονο OCR + +Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the lambda as `async`. + +### 3. Θεωρήσεις Ασφάλειας + +- **Επικύρωση μεγέθους αρχείου** πριν το φορτώσετε στη μνήμη. +- **Καθαρισμός του ονόματος αρχείου** εάν ποτέ το γράψετε στο δίσκο. +- **Περιορισμός ρυθμού** του endpoint για αποφυγή επιθέσεων άρνησης υπηρεσίας. + +### 4. Επιτάχυνση GPU + +Αν αποσχολιάσετε τη γραμμή `engine.GpuDevice = new GpuDevice(0);` και το υλικό σας υποστηρίζει CUDA ή DirectML, θα δείτε μια αξιοσημείωτη αύξηση ταχύτητας, ειδικά σε εικόνες υψηλής ανάλυσης. + +## Πλήρες Παράδειγμα Λειτουργίας + +Below is the complete `Program.cs` you can copy‑paste into a fresh Minimal API project. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Αποθηκεύστε, τρέξτε `dotnet run`, και είστε έτοιμοι να **εξάγετε κείμενο από εικόνα** κατόπιν ζήτησης. + +## Συμπέρασμα + +Διασχίσαμε μια **πλήρη, από άκρη σε άκρη λύση** για την εξαγωγή κειμένου από εικόνα χρησιμοποιώντας ASP.NET Core Minimal API. Ξεκινώντας από τη δημιουργία του έργου, **καταχωρήσαμε ένα singleton OCR engine**, χτίσαμε ένα endpoint που **ανεβάζει εικόνα μέσω POST**, **διαβάζει multipart form data**, και τελικά **εκτελεί OCR στην εικόνα** για να επιστρέψει καθαρό απλό κείμενο. + +Από εδώ μπορείτε: + +- Να προσθέσετε JSON wrappers για πιο πλούσιες απαντήσεις. +- Να ενσωματώσετε μια βάση δεδομένων για αποθήκευση του εξαγόμενου κειμένου. +- Να επεκτείνετε την υποστήριξη σε πολλές γλώσσες (`OcrLanguage.Spanish`, κλπ). + +Το πρότυπο κλιμακώνεται άψογα—απλώς ενσωματώστε το ίδιο endpoint σε μια μεγαλύτερη μικροϋπηρεσία ή εκθέστε το πίσω από ένα API gateway. + +Έχετε ερωτήσεις σχετικά με την επεξεργασία PDF, την επεξεργασία παρτίδων ή τη βελτιστοποίηση GPU; Αφήστε ένα σχόλιο, και καλή προγραμματιστική! + +## Σχετικά Μαθήματα + +- [Εξαγωγή Κειμένου από Εικόνα Χρησιμοποιώντας 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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/greek/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..c77fca8ec --- /dev/null +++ b/ocr/greek/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,313 @@ +--- +category: general +date: 2026-05-25 +description: Εξάγετε κείμενο από εικόνα χρησιμοποιώντας C# και Aspose OCR. Μάθετε + πώς να μετατρέπετε jpg σε κείμενο, να φορτώνετε εικόνα για OCR και να λαμβάνετε + αξιόπιστα αποτελέσματα γρήγορα. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: el +og_description: Εξαγωγή κειμένου από εικόνα με C#. Αυτός ο οδηγός δείχνει πώς να μετατρέψετε + jpg σε κείμενο, να φορτώσετε εικόνα για OCR και να διαχειριστείτε πολυγλωσσικό περιεχόμενο. +og_title: Εξαγωγή κειμένου από εικόνα σε C# – Εκπαίδευση Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Εξαγωγή κειμένου από εικόνα σε C# – Πλήρης οδηγός Aspose OCR +url: /el/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Εξαγωγή Κειμένου από Εικόνα σε C# – Πλήρης Οδηγός Aspose OCR + +Έχετε αναρωτηθεί ποτέ πώς να **εξάγετε κείμενο από εικόνα** χρησιμοποιώντας απλό κώδικα C#; Δεν είστε οι μόνοι. Είτε ψηφιοποιείτε αποδείξεις, είτε σκανάρετε πινακίδες, είτε απλώς ενδιαφέρεστε για OCR, η δυνατότητα να αντλήσετε χαρακτήρες από μια φωτογραφία είναι μια χρήσιμη δεξιότητα. Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πλήρες, εκτελέσιμο παράδειγμα που δείχνει ακριβώς πώς να **εξάγετε κείμενο από εικόνα** με το Aspose.OCR, και θα καλύψουμε επίσης πώς να **μετατρέψετε jpg σε κείμενο**, **φορτώσετε εικόνα για OCR**, και θα απαντήσουμε στην κλασική ερώτηση “**πώς να κάνετε OCR σε εικόνα**” μια για πάντα. + +Στο τέλος αυτού του οδηγού θα έχετε μια αυτόνομη εφαρμογή console που διαβάζει ένα αρχείο JPEG, αναγνωρίζει ουκρανικά (ή οποιαδήποτε άλλη υποστηριζόμενη γλώσσα) και εκτυπώνει το αποτέλεσμα στην κονσόλα. Χωρίς ασαφείς αναφορές, χωρίς ελλείψεις—απλώς μια πλήρης λύση που μπορείτε να αντιγράψετε‑επικολλήσετε και να τρέξετε. + +--- + +## Τι Θα Μάθετε + +* Πώς να εγκαταστήσετε το πακέτο NuGet Aspose.OCR. +* Τον ακριβή κώδικα που απαιτείται για **φόρτωση εικόνας για OCR** σε C#. +* Πώς να ορίσετε τη γλώσσα και πραγματικά **εξάγετε κείμενο από εικόνα**. +* Τεχνικές για **μετατροπή jpg σε κείμενο** αποδοτικά. +* Συνηθισμένα προβλήματα και πώς να τα αποφύγετε. + +Αν έχετε ήδη ρυθμίσει περιβάλλον ανάπτυξης .NET, είστε έτοιμοι να ξεκινήσετε. Διαφορετικά, η ενότητα προαπαιτήσεων παρακάτω θα σας φέρει στο σωστό δρόμο. + +--- + +## Προαπαιτήσεις + +| Απαίτηση | Γιατί είναι σημαντική | +|----------|-----------------------| +| .NET 6.0 SDK (ή νεότερο) | Παρέχει το runtime για την εφαρμογή console. | +| Visual Studio 2022 ή VS Code | Διευκολύνει την επεξεργασία και τον εντοπισμό σφαλμάτων. | +| Σύνδεση στο Internet (στην πρώτη εκτέλεση) | Το NuGet χρειάζεται να κατεβάσει το Aspose.OCR. | +| Μια εικόνα JPEG που θέλετε να επεξεργαστείτε (π.χ., `ukrainian_sign.jpg`) | Το αρχείο πηγής για τη μηχανή OCR. | + +> **Συμβουλή:** Αν χρησιμοποιείτε Linux ή macOS, ο ίδιος κώδικας λειτουργεί με τη γραμμή εντολών .NET (`dotnet new console`), οπότε μπορείτε να παραλείψετε το βαρέα IDE. + +--- + +## Βήμα 1 – Εγκατάσταση Aspose.OCR μέσω NuGet + +Ανοίξτε το τερματικό σας (ή το Package Manager Console) και εκτελέστε: + +```bash +dotnet add package Aspose.OCR +``` + +Αυτή η μοναδική γραμμή κατεβάζει τα πιο πρόσφατα binaries του Aspose.OCR και όλες τις εξαρτήσεις τους. Δεν απαιτείται χειροκίνητη διαχείριση DLL. + +--- + +## Βήμα 2 – Δημιουργία του OCR Engine (Η Καρδιά της Εξαγωγής) + +Τώρα που η βιβλιοθήκη είναι στη θέση της, μπορούμε να δημιουργήσουμε μια παρουσία του `OcrEngine`. Αυτό το αντικείμενο είναι υπεύθυνο για **εξαγωγή κειμένου από εικόνα**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Γιατί είναι σημαντικό:** Η μηχανή περιλαμβάνει τους αλγόριθμους OCR, τα μοντέλα γλώσσας και τις επιλογές διαμόρφωσης. Η δημιουργία της μία φορά και η επαναχρησιμοποίησή της σε πολλαπλές εικόνες είναι τόσο αποδοτική μνήμη όσο και γρήγορη. + +--- + +## Βήμα 3 – Φόρτωση Εικόνας για OCR (Και Ορισμός Γλώσσας) + +Το επόμενο βήμα είναι να πείτε στη μηχανή ποια εικόνα πρέπει να διαβάσει. Εδώ έρχεται η φράση **φόρτωση εικόνας για OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Ακραία περίπτωση:** Αν το αρχείο δεν υπάρχει, το `Image.FromFile` ρίχνει `FileNotFoundException`. Τυλίξτε την κλήση σε μπλοκ try‑catch για κώδικα παραγωγής. + +--- + +## Βήμα 4 – Εκτέλεση OCR και Εξαγωγή Κειμένου + +Με την εικόνα φορτωμένη, η μηχανή μπορεί τώρα **να εξάγει κείμενο από εικόνα**. Η μέθοδος `Recognize` κάνει το σκληρό έργο. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Αν όλα πάνε καλά, το `recognizedText` θα περιέχει την απλή κειμενική αναπαράσταση όλων όσων η μηχανή OCR μπόρεσε να διαβάσει. + +--- + +## Βήμα 5 – Μετατροπή JPG σε Κείμενο (Συνδυάζοντας Όλα) + +Ο κώδικας που έχουμε χτίσει μέχρι τώρα ήδη **μετατρέπει jpg σε κείμενο**, αλλά ας τον τυλίξουμε σε μια κομψή μέθοδο που μπορείτε να καλείτε επανειλημμένα. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Τώρα μπορείτε απλώς να κάνετε: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Αναμενόμενη έξοδος** (συντομευμένη για συντομία): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Αν η εικόνα περιέχει αγγλικό κείμενο, αλλάξτε σε `OcrLanguage.English` και θα δείτε το αντίστοιχο αποτέλεσμα. + +--- + +## Βήμα 6 – Αντιμετώπιση Συνηθισμένων Ερωτήσεων «Πώς να κάνω OCR σε εικόνα» + +### 6.1 Μπορώ να κάνω OCR σε PNG ή BMP; + +Απολύτως. Η μέθοδος `Image.FromFile` υποστηρίζει όλες τις μορφές που αναγνωρίζει το System.Drawing, οπότε απλώς δείξτε το μονοπάτι σε αρχείο `.png` ή `.bmp` και ο υπόλοιπος κώδικας παραμένει ίδιος. + +### 6.2 Τι γίνεται αν η εικόνα είναι χαμηλής ανάλυσης; + +Η ακρίβεια του OCR πέφτει δραματικά κάτω από 300 dpi. Μια γρήγορη λύση είναι να αυξήσετε το μέγεθος της εικόνας με `Graphics` πριν τη δώσετε στη μηχανή: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Χρειάζομαι άδεια χρήσης για το Aspose.OCR; + +Το Aspose προσφέρει δωρεάν δοκιμή με υδατογράφημα. Για παραγωγική χρήση, αγοράστε άδεια και προσθέστε: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Πλήρες Παράδειγμα Εργασίας + +Παρακάτω βρίσκεται μια πλήρης, έτοιμη‑για‑εκτέλεση εφαρμογή console που δείχνει **πώς να κάνετε OCR σε εικόνα**, **να φορτώσετε εικόνα για OCR**, και **να μετατρέψετε jpg σε κείμενο** σε ένα κομψό πακέτο. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Πώς να το τρέξετε** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Θα πρέπει να δείτε το εξαγόμενο κείμενο να εκτυπώνεται στην κονσόλα, επιβεβαιώνοντας ότι έχετε εξαγάγει επιτυχώς **κείμενο από εικόνα** χρησιμοποιώντας C#. + +--- + +## Συνηθισμένα Πιθανά Προβλήματα & Συμβουλές Επαγγελματία + +| Πρόβλημα | Γιατί συμβαίνει | Διόρθωση | +|----------|----------------|----------| +| Κενή έξοδος | Η εικόνα είναι πολύ σκοτεινή ή χαμηλής αντίθεσης. | Προεπεξεργασία με `Bitmap` για αύξηση φωτεινότητας. | +| Λάθος γλώσσα | Η ιδιότητα `Language` παραμένει στην προεπιλογή Αγγλικά. | Ορίστε ρητά `ocrEngine.Language = OcrLanguage.Ukrainian;` (ή τη δική σας). | +| Σφάλμα μνήμης | Πολύ μεγάλες εικόνες φορτώνονται χωρίς απελευθέρωση. | Τυλίξτε το `Image.FromFile` σε `using` block (όπως φαίνεται). | +| Υδατογράφημα άδειας | Εκτέλεση σε δοκιμαστική έκδοση χωρίς άδεια. | Εφαρμόστε την αγορασμένη άδεια νωρίς στο `Main`. | + +--- + +## Συμπέρασμα + +Καλύψαμε όλα όσα χρειάζεστε για να **εξάγετε κείμενο από εικόνα** σε C#—από την εγκατάσταση του Aspose.OCR, **τη φόρτωση εικόνας για OCR**, μέχρι τη **μετατροπή jpg σε κείμενο** και τη διαχείριση πολυγλωσσικών σεναρίων. Το πλήρες δείγμα προγράμματος ενώνει όλα τα κομμάτια, προσφέροντάς σας μια αξιόπιστη βάση για οποιοδήποτε έργο σχετικό με OCR. + +Επόμενα βήματα, μπορείτε να εξερευνήσετε: + +* **Πώς να κάνετε OCR σε image streams** αντί για αρχεία (χρησιμοποιήστε `MemoryStream`). +* Προσθήκη **c# image to text** μετα-επεξεργασίας όπως ορθογραφικός έλεγχος. +* Ενσωμάτωση του βήματος OCR σε μεγαλύτερο pipeline (π.χ., αποθήκευση αποτελεσμάτων σε βάση δεδομένων). + +Πειραματιστείτε με διαφορετικές γλώσσες, μορφές εικόνας και τεχνικές προεπεξεργασίας. Το OCR είναι τόσο τέχνη όσο και επιστήμη, και όσο περισσότερο παίζετε, τόσο καλύτερα θα είναι τα αποτελέσματα. + +Καλό κώδικα, και εύχομαι οι εικόνες σας να είναι πάντα αναγνώσιμες! + +## Σχετικά Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/greek/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..28b4524c7 --- /dev/null +++ b/ocr/greek/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-05-25 +description: Πώς να χρησιμοποιήσετε το OCR σε C# για την εξαγωγή κειμένου από αρχεία + εικόνας. Μάθετε πώς να αναγνωρίζετε κινέζικους χαρακτήρες από ένα JPG χρησιμοποιώντας + το Aspose.OCR σε λίγα απλά βήματα. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: el +og_description: Πώς να χρησιμοποιήσετε OCR σε C# για την εξαγωγή κειμένου από αρχεία + εικόνας. Αυτός ο οδηγός σας δείχνει πώς να αναγνωρίζετε κινεζικούς χαρακτήρες από + ένα JPG χρησιμοποιώντας το Aspose.OCR. +og_title: Πώς να χρησιμοποιήσετε OCR σε C# – Αναγνώριση κινεζικού κειμένου από JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Πώς να χρησιμοποιήσετε OCR σε C# – Αναγνώριση Κινέζικου κειμένου από JPG +url: /el/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Πώς να Χρησιμοποιήσετε OCR σε C# – Αναγνώριση Κινέζου Κειμένου από JPG + +Έχετε αναρωτηθεί ποτέ **πώς να χρησιμοποιήσετε OCR** για να εξάγετε λέξεις από μια φωτογραφία που τραβήξατε με το τηλέφωνό σας; Δεν είστε μόνοι. Σε πολλά πραγματικά έργα—σκεφτείτε σαρωτές αποδείξεων, εφαρμογές μετάφρασης ή αυτοματοποιημένη εισαγωγή δεδομένων—θα χρειαστεί να **εξάγετε κείμενο από εικόνα** αρχεία γρήγορα και αξιόπιστα. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα ένα πλήρες, εκτελέσιμο παράδειγμα που **αναγνωρίζει κείμενο από αρχεία JPG** και ακόμη χειρίζεται την δύσκολη περίπτωση **αναγνώρισης Κινέζων χαρακτήρων** χρησιμοποιώντας το γλωσσικό πακέτο **OCR Chinese Simplified**. Στο τέλος, θα έχετε μια αυτόνομη εφαρμογή κονσόλας που εκτυπώνει τη ανιχνευμένη συμβολοσειρά στην κονσόλα, χωρίς επιπλέον χειροκίνητες λήψεις. + +> **Σύντομη σημείωση:** Ο κώδικας λειτουργεί με Aspose.OCR ≥ 23.7, το οποίο αυτόματα κατεβάζει τους γλωσσικούς πόρους στην πρώτη χρήση. Εάν χρησιμοποιείτε παλαιότερη έκδοση, θα πρέπει να προσθέσετε τη γλώσσα χειροκίνητα. + +## Προαπαιτούμενα + +- .NET 6.0 SDK ή νεότερο (το παράδειγμα στοχεύει στο .NET 6, αλλά το .NET 5 λειτουργεί επίσης) +- Μια πρόσφατη έκδοση του Visual Studio 2022 ή VS Code με την επέκταση C# +- Σύνδεση στο διαδίκτυο για τη πρώτη λήψη γλώσσας +- Μια εικόνα JPG που περιέχει κείμενο Simplified Chinese (θα την ονομάσουμε `chinese_sign.jpg`) + +Αυτό είναι όλο—χωρίς βαριά μηχανήματα OCR, χωρίς χειρισμό εγγενών DLL. Μόνο μερικές εντολές NuGet και μερικές γραμμές κώδικα. + +## Βήμα 1: Εγκατάσταση Aspose.OCR μέσω NuGet + +Πρώτα απ' όλα: χρειαζόμαστε τη βιβλιοθήκη OCR. Ανοίξτε ένα τερματικό στο φάκελο του έργου σας και εκτελέστε: + +```bash +dotnet add package Aspose.OCR +``` + +Ή, αν προτιμάτε το UI του Visual Studio, κάντε δεξί‑κλικ στο **Dependencies → Manage NuGet Packages**, αναζητήστε το “Aspose.OCR” και κάντε κλικ στο **Install**. + +> **Συμβουλή:** Διατηρήστε τα πακέτα σας ενημερωμένα. Νέα γλωσσικά πακέτα και βελτιώσεις απόδοσης κυκλοφορούν σε κάθε μικρή έκδοση. + +## Βήμα 2: Δημιουργία Νέου Console Project (Αν Δεν Το Έχετε Ήδη) + +Αν ξεκινάτε από το μηδέν, δημιουργήστε μια νέα εφαρμογή console: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Τώρα έχετε ένα αρχείο `Program.cs` έτοιμο για τον κώδικα OCR. + +## Βήμα 3: Γράψτε τον Κώδικα OCR – Αναγνώριση Simplified Chinese από JPG + +Ανοίξτε το `Program.cs` και αντικαταστήστε το περιεχόμενό του με το παρακάτω. Κάθε γραμμή είναι σχολιασμένη ώστε να βλέπετε *γιατί* κάνουμε κάθε βήμα, όχι μόνο *τι* κάνουμε. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Τι συμβαίνει υπό το καπό; + +- **`OcrEngine.Language`** λέει στο Aspose ποιο λεξικό να χρησιμοποιήσει. Επιλέγοντας το `ChineseSimplified`, καθοδηγούμε τη μηχανή να ψάξει για το γλωσσικό πακέτο Simplified Chinese. +- **Πρώτη λήψη**: Όταν εκτελείται το `Recognize`, το SDK επικοινωνεί με το CDN της Aspose, κατεβάζει το αρχείο γλώσσας ≈6 MB, το αποθηκεύει στην τοπική cache και στη συνέχεια προχωρά στην OCR. Οι επόμενες κλήσεις είναι άμεσες. +- **`Image.FromFile`** λειτουργεί με οποιαδήποτε μορφή raster που μπορεί να αποκωδικοποιήσει το .NET—JPG, PNG, BMP—οπότε μπορείτε να **εξάγετε κείμενο από εικόνα** αρχεία πολλών τύπων, όχι μόνο JPG. + +## Βήμα 4: Εκτελέστε την Εφαρμογή και Επαληθεύστε το Αποτέλεσμα + +Δομήστε και εκτελέστε: + +```bash +dotnet run +``` + +Θα πρέπει να δείτε κάτι όπως: + +``` +=== Recognized Text === +欢迎光临 +``` + +Αν η κονσόλα εμφανίζει ακατανόητο κείμενο ή κενή συμβολοσειρά, ελέγξτε ξανά ότι: + +1. Η εικόνα περιέχει πράγματι καθαρούς, υψηλής αντίθεσης κινέζους χαρακτήρες. +2. Η διαδρομή του αρχείου είναι σωστή (χωρίς περιττά κενά ή λείποντες τύπους αρχείων). +3. Η μηχανή σας μπορεί να φτάσει στο `https://download.aspose.com` για το γλωσσικό πακέτο. + +## Βήμα 5: Διαχείριση Ακραίων Περιστατικών και Συνηθισμένων Παγίδων + +### 5.1 Αντιμετώπιση Εικόνων Χαμηλής Ποιότητας + +Η ακρίβεια του OCR μειώνεται όταν η πηγή εικόνας είναι θολή, θορυβώδης ή έχει φτωχή φωτισμό. Μια γρήγορη λύση είναι η προεπεξεργασία της εικόνας: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Εκτέλεση σε Περιβάλλον Χωρίς GUI + +Αν αναπτύσσετε σε κοντέινερ Linux χωρίς GUI, βεβαιωθείτε ότι η βιβλιοθήκη `libgdiplus` (απαιτούμενη για `System.Drawing`) είναι εγκατεστημένη: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Εγκατάσταση του Γλωσσικού Πακέτου με Χειροκίνητο Cache + +Μπορείτε να κατεβάσετε το αρχείο γλώσσας μία φορά και να το δείξετε στο Aspose μέσω του API `License`, το οποίο εξαλείφει την εφάπαξ κλήση δικτύου. Αυτό είναι χρήσιμο για σενάρια εκτός σύνδεσης. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Πλήρες Παράδειγμα Εργασίας (All‑In‑One) + +Παρακάτω είναι το *πλήρες* πρόγραμμα που μπορείτε να αντιγράψετε‑και‑επικολλήσετε στο `Program.cs`. Χωρίς κρυφά κομμάτια, χωρίς εξωτερικά scripts. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Αναμενόμενο Αποτέλεσμα + +Αν το JPG περιέχει τη φράση “欢迎光临”, η κονσόλα θα εκτυπώσει: + +``` +=== Recognized Text === +欢迎光临 +``` + +Μπορείτε ελεύθερα να αντικαταστήσετε την εικόνα με οποιοδήποτε άλλο σήμα Simplified Chinese, οδικό όνομα ή ετικέτα προϊόντος—η μηχανή θα κάνει το καλύτερο δυνατό. + +## Συμπέρασμα + +Μόλις καλύψαμε **πώς να χρησιμοποιήσετε OCR** σε C# για **εξαγωγή κειμένου από εικόνα** αρχεία, αντιμετωπίζοντας συγκεκριμένα την πρόκληση της **αναγνώρισης Κινέζων χαρακτήρων** σε **JPG**. Χρησιμοποιώντας τη δυνατότητα λήψης γλώσσας εν κινήσει του Aspose.OCR, μπορείτε να διατηρήσετε την ανάπτυξή σας ελαφριά ενώ υποστηρίζετε το **OCR Chinese Simplified** έτοιμο προς χρήση. + +Τι ακολουθεί; Δοκιμάστε αυτές τις ιδέες: + +- **Batch processing**: Επανάληψη σε φάκελο εικόνων και εγγραφή κάθε αποτελέσματος σε CSV. +- **Συνδυασμός με APIs μετάφρασης**: Στείλτε τη αναγνωρισμένη συμβολοσειρά στο Azure Translator για εφαρμογές πολυγλωσσικής πραγματικού χρόνου. +- **Εξερευνήστε άλλες γλώσσες**: Αντικαταστήστε το `OcrLanguage.ChineseSimplified` με `Japanese` ή `Arabic` και δείτε πώς προσαρμόζεται ο ίδιος κώδικας. + +Έχετε ερωτήσεις σχετικά με τη βελτιστοποίηση απόδοσης, την άδεια χρήσης ή την ενσωμάτωση OCR σε web service; Αφήστε ένα σχόλιο παρακάτω—καλή προγραμματιστική! + +--- + +![Στιγμιότυπο οθόνης της εξόδου της κονσόλας που δείχνει πώς να χρησιμοποιήσετε OCR σε C# για την αναγνώριση Κινέζου κειμένου από εικόνα JPG](ocr-chinese-demo.png "πώς να χρησιμοποιήσετε την έξοδο της κονσόλας OCR") + +## Σχετικά Μαθήματα + +- [Εξαγωγή κειμένου εικόνας 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](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/greek/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/greek/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..d39605b3f --- /dev/null +++ b/ocr/greek/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Μάθετε πώς να κάνετε OCR ρωσικού κειμένου σε C# και να εξάγετε κείμενο + από εικόνα με το Aspose OCR. Βήμα‑βήμα κώδικας για γρήγορη μετατροπή εικόνας σε + κείμενο C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: el +og_description: Η OCR ρωσικού κειμένου σε C# γίνεται εύκολη. Μάθετε πώς να εξάγετε + κείμενο από εικόνα, να μετατρέπετε εικόνα σε κείμενο C# και να φορτώνετε εικόνα + για OCR με το Aspose OCR. +og_title: OCR ρωσικού κειμένου σε C# – Πλήρης οδηγός Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR ρωσικού κειμένου σε C# – Πλήρης οδηγός με χρήση Aspose OCR +url: /el/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR ρωσικού κειμένου σε C# – Πλήρης Οδηγός με χρήση Aspose OCR + +Έχετε χρειαστεί ποτέ να κάνετε OCR ρωσικού κειμένου σε C# αλλά δεν ήξερατε ποια βιβλιοθήκη να εμπιστευτείτε; Δεν είστε μόνοι. Η λήψη καθαρών, αναγνώσιμων χαρακτήρων από μια κυριλλική εικόνα μπορεί να μοιάζει με αποκρυπτογράφηση μυστικών μηνυμάτων—ιδιαίτερα αν δεν έχετε ορίσει το σωστό μοντέλο γλώσσας. + +Σε αυτό το tutorial θα περάσουμε βήμα‑βήμα από ένα πρακτικό παράδειγμα που δείχνει πώς να **εξάγετε κείμενο από εικόνα**, να μετατρέψετε *image to text C#* και να αντιμετωπίσετε τις ιδιαιτερότητες της αναγνώρισης ρωσικής γλώσσας με το Aspose OCR. Στο τέλος θα έχετε μια έτοιμη για εκτέλεση εφαρμογή console που φορτώνει μια εικόνα για OCR, εκτυπώνει το αναγνωρισμένο κείμενο και σας παρέχει μια σταθερή βάση για πιο προχωρημένα σενάρια. + +## Τι Θα Μάθετε + +- Πώς να εγκαταστήσετε και να ρυθμίσετε το **Aspose OCR C#** για υποστήριξη ρωσικής γλώσσας. +- Τα ακριβή βήματα για **φόρτωση εικόνας για OCR** και κλήση της μηχανής. +- Συμβουλές για την αντιμετώπιση κοινών προβλημάτων όπως ελλιπείς πόροι γλώσσας ή θολές σαρώσεις. +- Τρόπους επέκτασης της λύσης, όπως επεξεργασία πολλαπλών αρχείων ή ρύθμιση ορίων εμπιστοσύνης. + +Δεν απαιτείται προηγούμενη εμπειρία με το Aspose· απλώς μια βασική εξοικείωση με C# και .NET αρκεί για να ξεκινήσετε. + +## Προαπαιτούμενα + +Πριν προχωρήσουμε, βεβαιωθείτε ότι διαθέτετε τα εξής: + +1. **.NET 6.0** (ή νεότερο) SDK εγκατεστημένο – ο κώδικας λειτουργεί τόσο σε .NET Core όσο και σε .NET Framework. +2. **Visual Studio 2022** (ή οποιοδήποτε IDE προτιμάτε). +3. Ένα πακέτο **Aspose.OCR for .NET** από το NuGet – μπορείτε να πάρετε ένα δωρεάν κλειδί δοκιμής από την ιστοσελίδα της Aspose. +4. Ένα **αρχείο μοντέλου ρωσικής γλώσσας** (`rus.traineddata`) – κατεβάστε το από τη σελίδα πόρων της Aspose και τοποθετήστε το σε φάκελο που θα αναφέρετε αργότερα. +5. Μια δείγμα εικόνας (`russian_doc.png`) που περιέχει καθαρό κυριλλικό κείμενο. + +Τα έχετε όλα; Τέλεια—ας ξεκινήσουμε. + +## Βήμα 1: Δημιουργία Έργου και Εγκατάσταση Aspose OCR + +Πρώτα, δημιουργήστε ένα νέο project console: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Τώρα προσθέστε το πακέτο Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Αν χρησιμοποιείτε άδεια δοκιμής, κρατήστε το αρχείο `Aspose.Total.lic` κοντά· θα το φορτώσετε στον κώδικα για να αποφύγετε τα υδατογραφήματα. + +Αφού εγκατασταθεί το πακέτο, ανοίξτε το `Program.cs`. Θα δείτε τη προεπιλεγμένη μέθοδο `Main`—αντικαταστήστε το περιεχόμενό της με το σκελετό που θα χτίσουμε. + +## Βήμα 2: Ρύθμιση του OCR Engine για Ρωσική Γλώσσα + +Η καρδιά της λειτουργίας είναι το αντικείμενο `OcrEngine`. Πρέπει να του πούμε δύο πράγματα: ποια γλώσσα να αναγνωρίσει και πού να βρει τα αρχεία μοντέλων γλώσσας. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Γιατί είναι σημαντικό:** Αν παραλείψετε το `Language = OcrLanguage.Russian`, η μηχανή προεπιλέγει τα αγγλικά και οποιοιδήποτε κυριλλικοί χαρακτήρες θα εμφανιστούν ως ακατανόητα σύμβολα. Το `ResourceFolder` δείχνει στον φάκελο που περιέχει το αρχείο `rus.traineddata`; χωρίς αυτό, το Aspose ρίχνει εξαίρεση *resource not found*. + +## Βήμα 3: Φόρτωση της Εικόνας για OCR + +Τώρα πρέπει να **φορτώσουμε εικόνα για OCR**. Το Aspose OCR δουλεύει με `System.Drawing.Image`, οπότε μπορείτε να περάσετε οποιαδήποτε υποστηριζόμενη μορφή (PNG, JPEG, BMP κ.λπ.). Βεβαιωθείτε ότι η διαδρομή του αρχείου είναι σωστή· οι σχετικές διαδρομές λειτουργούν αν κρατήσετε την εικόνα δίπλα στο εκτελέσιμο. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** Αν η εικόνα είναι μεγάλη (πάνω από 5 MB) ίσως θελήσετε πρώτα να τη μειώσετε σε μέγεθος. Η ακρίβεια του OCR πέφτει όταν το DPI είναι πολύ χαμηλό, αλλά τα τεράστια αρχεία μπορούν να προκαλέσουν πίεση μνήμης. Μια γρήγορη αλλαγή μεγέθους μπορεί να γίνει με `Graphics` αν χρειαστεί. + +## Βήμα 4: Αναγνώριση Κειμένου – Από Εικόνα σε Κείμενο C# Style + +Με τη μηχανή ρυθμισμένη και την εικόνα φορτωμένη, η πραγματική αναγνώριση είναι μια μόνο κλήση: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Όταν τρέξετε το πρόγραμμα (`dotnet run`), θα πρέπει να δείτε κάτι σαν: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Αν η έξοδος φαίνεται ακατανόητη, ελέγξτε ξανά ότι: + +- Το αρχείο `rus.traineddata` υπάρχει στο `ResourceFolder`. +- Η εικόνα δεν είναι πολύ θολή· σκεφτείτε να εφαρμόσετε ένα απλό φίλτρο δυαδικοποίησης πριν το OCR. +- Η ρύθμιση γλώσσας είναι πράγματι `OcrLanguage.Russian`. + +## Βήμα 5: Λεπτομερής Ρύθμιση και Συχνά Προβλήματα + +### Προσαρμογή Κατωφλίου Εμπιστοσύνης + +Το Aspose OCR επιστρέφει μια τιμή εμπιστοσύνης ανά χαρακτήρα εσωτερικά. Αν και το API δεν την εκθέτει άμεσα, μπορείτε να ενεργοποιήσετε **λεπτομερή έξοδο** για να δείτε ποιες λέξεις είχαν χαμηλή εμπιστοσύνη: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Αν παρατηρήσετε συχνές λανθασμένες αναγνώσεις, δοκιμάστε: + +- **Προεπεξεργασία**: Μετατρέψτε την εικόνα σε γκρι, αυξήστε την αντίθεση ή εφαρμόστε φίλτρο μέσου όρου. +- **Ρυθμίσεις DPI**: Βεβαιωθείτε ότι η εικόνα είναι τουλάχιστον 300 DPI για κυριλλικά σενάρια. + +### Επεξεργασία Πολλαπλών Εικόνων (Batch) + +Αν χρειάζεται να **εξάγετε κείμενο από εικόνα** σε μαζική κλίμακα, τυλίξτε τη λογική αναγνώρισης μέσα σε βρόχο: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Τώρα κάθε PNG θα δημιουργεί το αντίστοιχο αρχείο `.txt`—χρήσιμο για αρχειοθέτηση εγγράφων. + +### Διαχείριση Unicode Εξόδου + +Οι κυριλλικοί χαρακτήρες είναι Unicode, οπότε βεβαιωθείτε ότι η κωδικοποίηση του console σας μπορεί να τους εμφανίσει: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Τοποθετήστε αυτή τη γραμμή αμέσως μετά την έναρξη της μεθόδου `Main`. Χωρίς αυτήν, μπορεί να δείτε ερωτηματικά (`?`) αντί για ρωσικά γράμματα. + +## Πλήρες Παράδειγμα Λειτουργικού Κώδικα + +Παρακάτω είναι ο πλήρης, έτοιμος για εκτέλεση κώδικας. Αντιγράψτε‑και‑επικολλήστε το στο `Program.cs`, προσαρμόστε τις διαδρομές και είστε έτοιμοι. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Αναμενόμενη έξοδος** (υποθέτοντας ότι η δείγμα εικόνα λέει “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Αν δείτε κάτι διαφορετικό, επανεξετάστε τις συμβουλές αντιμετώπισης προβλημάτων στο Βήμα 5. + +## Συμπέρασμα + +Τώρα έχετε ένα ολοκληρωμένο παράδειγμα από άκρο‑σε‑άκρο για το πώς να **ocr russian text** σε C# χρησιμοποιώντας το Aspose OCR. Από την εγκατάσταση της βιβλιοθήκης, τη ρύθμιση του μοντέλου ρωσικής γλώσσας, τη φόρτωση μιας εικόνας και τη μετατροπή της σε καθαρό Unicode κείμενο, καλύπτεται κάθε βήμα. + +Θυμηθείτε, το κλειδί για αξιόπιστο OCR είναι το καλό υλικό: καθαρά γραφικά, επαρκές DPI και οι σωστοί πόροι γλώσσας. Μόλις κυριαρχήσετε τα βασικά, μπορείτε να επεκτείνετε σε batch processing, να ενσωματώσετε αποθήκευση στο cloud ή ακόμη και να συνδυάσετε με AI για ορθογραφικό έλεγχο. + +### Τι Ακολουθεί; + +- Εξερευνήστε τις **aspose ocr c#** προχωρημένες επιλογές όπως ανάλυση διάταξης ή εξαγωγή PDF. +- Συνδυάστε το με **extract text from image** ροές εργασίας σε Azure Functions για serverless επεξεργασία. +- Δοκιμάστε διαφορετικές γλώσσες—απλώς αλλάξτε το `OcrLanguage.Russian` σε `OcrLanguage.English` ή σε κάποιον άλλο υποστηριζόμενο κωδικό. + +Έχετε ερωτήσεις ή μια δύσκολη εικόνα που δεν συνεργάζεται; Αφήστε ένα σχόλιο παρακάτω, και καλή προγραμματιστική! + +![ocr russian text example](ocr-russian-example.png){alt="παράδειγμα κειμένου OCR στα ρωσικά"} + +## Σχετικά Tutorials + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/greek/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..eecd4af81 --- /dev/null +++ b/ocr/greek/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: αναγνωρίστε κείμενο από εικόνα χρησιμοποιώντας Aspose OCR σε C#. Μάθετε + πώς να φορτώνετε εικόνα για OCR, να ορίζετε τη γλώσσα OCR, να δημιουργείτε μηχανή + OCR και να εξάγετε κείμενο από TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: el +og_description: Αναγνώριση κειμένου από εικόνα χρησιμοποιώντας Aspose OCR σε C#. Αυτό + το σεμινάριο δείχνει πώς να δημιουργήσετε μηχανή OCR, να φορτώσετε εικόνα για OCR, + να ορίσετε τη γλώσσα OCR και να εξάγετε κείμενο από TIFF. +og_title: Αναγνώριση κειμένου από εικόνα με Aspose OCR – Πλήρης Οδηγός C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Αναγνώριση κειμένου από εικόνα με Aspose OCR – Πλήρης οδηγός C# +url: /el/net/text-recognition/recognize-text-from-image-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 – Πλήρης Οδηγός C# + +Ποτέ χρειάστηκε να **αναγνωρίσετε κείμενο από εικόνα** αλλά δεν ήσασταν σίγουροι ποια βιβλιοθήκη θα σας προσφέρει ταχύτητα και ακρίβεια; Δεν είστε μόνοι. Σε πολλά έργα επεξεργασίας τιμολογίων ή αρχειοθέτησης, το μεγαλύτερο πρόβλημα είναι η εξαγωγή καθαρού, αναζητήσιμου κειμένου από αρχεία TIFF χωρίς να γράψετε έναν προσαρμοσμένο parser. + +Το ζήτημα είναι το εξής: το Aspose OCR για .NET κάνει όλη αυτή τη διαδικασία παιχνιδάκι. Σε αυτόν τον οδηγό θα περάσουμε από όλα όσα χρειάζεστε — εγκατάσταση του πακέτου, **δημιουργία μηχανής OCR**, φόρτωση ενός TIFF, ορισμός της γλώσσας OCR, και τέλος **εξαγωγή κειμένου από TIFF**. Στο τέλος θα έχετε μια έτοιμη εφαρμογή console που μπορεί να **αναγνωρίσει κείμενο από εικόνα** σε ελάχιστο χρόνο. + +## Προαπαιτούμενα + +- .NET 6.0 ή νεότερο (ο κώδικας λειτουργεί και με .NET Core και .NET Framework) +- Visual Studio 2022 (ή οποιοδήποτε IDE προτιμάτε) +- Πακέτο NuGet Aspose.OCR (η υποστήριξη GPU απαιτεί το πρόσθετο `Aspose.OCR.Gpu`) +- Μια GPU με υποστήριξη CUDA αν θέλετε την επιπλέον ταχύτητα (προαιρετικό αλλά συνιστάται) + +> **Συμβουλή:** Αν δεν έχετε GPU, απλώς παραλείψτε τη γραμμή `GpuDevice` και η μηχανή θα επιστρέψει αυτόματα στη CPU. + +## Βήμα 1: Εγκατάσταση Aspose OCR και Δημιουργία Μηχανής OCR + +Πρώτα, προσθέστε τα απαραίτητα πακέτα μέσω NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Τώρα μπορούμε να **δημιουργήσουμε μηχανή OCR**. Αυτό το αντικείμενο είναι η καρδιά της διαδικασίας· κρατά τις ρυθμίσεις όπως η συσκευή εκτέλεσης και τα όρια μνήμης. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Γιατί είναι σημαντικό:** Συνδέοντας τη μηχανή με μια GPU μειώνετε δραστικά το χρόνο που χρειάζεται για **αναγνώριση κειμένου από εικόνα**, ειδικά για μεγάλες παρτίδες υψηλής ανάλυσης TIFF. + +## Βήμα 2: Φόρτωση Εικόνας για OCR + +Στη συνέχεια, πρέπει να **φορτώσετε εικόνα για OCR**. Το Aspose.OCR λειτουργεί με `System.Drawing.Image`, οπότε οποιαδήποτε μορφή υποστηρίζεται από το GDI+ (συμπεριλαμβανομένου του multi‑page TIFF) είναι αποδεκτή. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Αν εργάζεστε με multi‑page TIFF, μπορείτε να κάνετε βρόχο στις σελίδες χρησιμοποιώντας `image.SelectActiveFrame`, αλλά για τις περισσότερες περιπτώσεις μια ενιαία κλήση αρκεί. + +## Βήμα 3: Ορισμός Γλώσσας OCR + +Η μηχανή δεν ξέρει μαγικά ποια γλώσσα σκανάρετε. **Ορίστε τη γλώσσα OCR** πριν τρέξετε τον αναγνώστη· διαφορετικά θα λάβετε ακατάστατο αποτέλεσμα. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Το ήξερες;** Η αλλαγή γλώσσας κατά την εκτέλεση είναι φθηνή· μπορείτε ακόμη να επεξεργαστείτε ένα έγγραφο με μεικτές γλώσσες αλλάζοντας αυτήν την ιδιότητα μεταξύ των σελίδων. + +## Βήμα 4: Εκτέλεση Αναγνώρισης – Αναγνώριση Κειμένου από Εικόνα + +Τώρα το διασκεδαστικό μέρος: πραγματικά **αναγνωρίστε κείμενο από εικόνα**. Η μέθοδος `Recognize` επιστρέφει μια απλή συμβολοσειρά με όλους τους ανιχνευμένους χαρακτήρες. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Αν χρειάζεστε βαθμολογίες εμπιστοσύνης ή περιοριστικά πλαίσια, μπορείτε να χρησιμοποιήσετε την υπερφόρτωση που επιστρέφει ένα αντικείμενο `OcrResult`, αλλά για τις περισσότερες εργασίες εξαγωγής η απλή συμβολοσειρά είναι επαρκής. + +## Βήμα 5: Εξαγωγή Κειμένου από TIFF (και διαχείριση multi‑page αρχείων) + +Όταν η πηγή είναι ένα TIFF που περιέχει πολλές σελίδες, θα θέλετε να επαναλάβετε τα βήματα 2‑4 για κάθε καρέ. Ακολουθεί ένας γρήγορος βρόχος που **εξάγει κείμενο από TIFF** σελίδα προς σελίδα: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Ο παραπάνω κώδικας εκτυπώνει το εξαγόμενο κείμενο για κάθε σελίδα, καθιστώντας εύκολο το άμεσο πέρασμα των αποτελεσμάτων σε βάση δεδομένων ή ευρετήριο αναζήτησης. + +## Βήμα 6: Εμφάνιση ή Αποθήκευση του Εξαγόμενου Κειμένου + +Τέλος, ας **εμφανίσουμε το εξαγόμενο κείμενο** και προαιρετικά να το γράψουμε σε αρχείο για μεταγενέστερη επεξεργασία. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Η εκτέλεση του προγράμματος θα πρέπει να εμφανίσει τους αναγνωρισμένους χαρακτήρες και να δημιουργήσει το `extracted_text.txt` δίπλα στο πηγαίο TIFF. + +--- + +## Συχνές Ερωτήσεις & Ακραίες Περιπτώσεις + +- **Τι γίνεται αν η GPU μου δεν εντοπιστεί;** + Αφαιρέστε τη γραμμή `GpuDevice`; η μηχανή θα μεταβεί αυτόματα σε λειτουργία CPU. Η απόδοση θα είναι πιο αργή, αλλά τα αποτελέσματα παραμένουν ακριβή. + +- **Μπορώ να επεξεργαστώ αρχεία PNG ή JPEG;** + Απόλυτα—`Image.FromFile` λειτουργεί με οποιαδήποτε μορφή υποστηρίζεται από το System.Drawing, οπότε μπορείτε να **φορτώσετε εικόνα για OCR** ανεξαρτήτως επέκτασης. + +- **Πώς να αντιμετωπίσω σαρώσεις χαμηλής ανάλυσης;** + Αυξήστε το `ocrEngine.PreprocessOptions.Dpi` πριν καλέσετε το `Recognize`. Υψηλότερο DPI δίνει στη μηχανή περισσότερα pixel για εργασία, βελτιώνοντας την ακρίβεια. + +- **Υπάρχει όριο στο μέγεθος του TIFF;** + Η ιδιότητα `GpuMemoryLimit` περιορίζει τη χρήση GPU. Αν φτάσετε το όριο, η μηχανή θα μεταβεί σε CPU για τις υπόλοιπες σελίδες. + +--- + +## Συμπέρασμα + +Τώρα έχετε ένα πλήρες, έτοιμο για παραγωγή απόσπασμα κώδικα που **αναγνωρίζει κείμενο από εικόνα** χρησιμοποιώντας το Aspose OCR σε C#. Ο οδηγός κάλυψε πώς να **δημιουργήσετε μηχανή OCR**, **φορτώσετε εικόνα για OCR**, **ορίσετε γλώσσα OCR**, και **εξάγετε κείμενο από TIFF**—όλα ενώ αξιοποιείτε την επιτάχυνση GPU για ταχύτητα. + +Από εδώ μπορείτε: + +- Να πειραματιστείτε με διαφορετικές γλώσσες (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, κ.λπ.). +- Να ενσωματώσετε το αποτέλεσμα σε ένα αναζητήσιμο ευρετήριο ElasticSearch. +- Να προσθέσετε μεταεπεξεργασία (ορθογραφικό έλεγχο, καθαρισμό με regex) για βελτίωση της ποιότητας των δεδομένων. + +Δοκιμάστε το σε δική σας παρτίδα τιμολογίων, ρυθμίστε τα όρια μνήμης, και παρακολουθήστε την απόδοση του OCR να απογειώνεται. Καλό προγραμματισμό! + +## Σχετικά Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..e02af973c 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# में OCR इंजन बनाएं – पूर्ण गाइड](./create-ocr-engine-in-c-complete-guide/) +C# में Aspose.OCR का उपयोग करके 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/hindi/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..2866f358e --- /dev/null +++ b/ocr/hindi/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: C# में OCR इंजन बनाएं और कुछ लाइनों के कोड में इसके इवैल्यूएशन मोड और + लाइसेंसिंग स्थिति की जाँच करना सीखें। +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: hi +og_description: C# में OCR इंजन बनाएं और तुरंत देखें कि मूल्यांकन मोड कैसे पता करें + और लाइसेंस स्थिति कैसे प्रदर्शित करें। +og_title: C# में OCR इंजन बनाएं – चरण‑दर‑चरण गाइड +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: C# में OCR इंजन बनाएं – पूर्ण मार्गदर्शिका +url: /hi/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में OCR इंजन बनाएं – पूर्ण गाइड + +क्या आप कभी सोचते रहे हैं कि **create OCR engine** ऑब्जेक्ट्स को C# में अनंत दस्तावेज़ों के बीच खोजे बिना कैसे बनाएं? आप अकेले नहीं हैं। कई डेवलपर्स को तब रुकावट आती है जब उन्हें OCR इंजन को शुरू करना, यह जांचना कि वह ट्रायल मोड में चल रहा है या नहीं, और उपयोगकर्ताओं को लाइसेंसिंग स्थिति दिखानी होती है। + +इस ट्यूटोरियल में हम एक संक्षिप्त, एंड‑टू‑एंड उदाहरण के माध्यम से चलेंगे जिसमें **OCR इंजन बनाते** हैं, उसकी **OCR engine evaluation mode** जाँचते हैं, और लाइसेंसिंग स्थिति के बारे में एक मित्रवत संदेश प्रिंट करते हैं। अंत तक आपके पास एक तैयार‑चलाने योग्य कंसोल ऐप और अपने प्रोजेक्ट्स में OCR लाइसेंसिंग को संभालने के लिए स्पष्ट मानसिक मॉडल होगा। + +## आप क्या सीखेंगे + +- `OcrEngine` को इंस्टैंशिएट करने का तरीका (किसी भी OCR वर्कफ़्लो का कोर)। +- **evaluation mode** का पता लगाना क्यों महत्वपूर्ण है, अनुपालन और उपयोगकर्ता अनुभव के लिए। +- **OCR लाइसेंस** स्थिति की जाँच करने और अप्रत्याशित स्थितियों पर प्रतिक्रिया देने का सबसे अच्छा तरीका। +- सामान्य जाल—null रेफ़रेंसेज़, एक्सेप्शन हैंडलिंग, और संस्करण असंगतियां। + +बाहरी टूल्स की आवश्यकता नहीं है, बस वह OCR SDK जो आपने पहले से इंस्टॉल किया है। यदि आप बेसिक C# सिंटैक्स से परिचित हैं, तो आप तैयार हैं। + +## पूर्वापेक्षाएँ + +- .NET 6.0 या बाद का (कोड .NET Core और .NET Framework दोनों के साथ कम्पाइल होता है)। +- एक OCR SDK जो `OcrEngine` क्लास को `IsEvaluation` प्रॉपर्टी के साथ एक्सपोज़ करता है (उदाहरण के लिए, काल्पनिक `MyOcrSdk`)। +- एक टेक्स्ट एडिटर या IDE (Visual Studio, VS Code, Rider—जो भी आपका पसंदीदा हो)। + +बस इतना ही। चलिए शुरू करते हैं। + +## चरण 1: नया कंसोल प्रोजेक्ट सेट अप करें + +पहले, एक नया कंसोल ऐप बनाएं ताकि आप कोड को अलग‑थलग चलाने में सक्षम हों। + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +जनरेटेड `Program.cs` खोलें। हम इसकी सामग्री को एक पूर्ण उदाहरण से बदल देंगे जो **OCR इंजन बनाता** है और लाइसेंसिंग को संभालता है। + +## चरण 2: OCR SDK नेमस्पेस इम्पोर्ट करें + +मान लेते हैं कि SDK को NuGet के माध्यम से रेफ़रेंस किया गया है (`MyOcrSdk` एक प्लेसहोल्डर है), फ़ाइल के शीर्ष पर using डायरेक्टिव जोड़ें। + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +यदि आपने अभी तक पैकेज नहीं जोड़ा है, तो चलाएँ: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** अपना SDK संस्करण अपडेट रखिए; नए रिलीज़ अक्सर evaluation‑mode डिटेक्शन को बेहतर बनाते हैं। + +## चरण 3: OCR इंजन इंस्टेंस बनाएं + +अब हम अंततः **OCR इंजन बनाते** हैं। यह किसी भी OCR वर्कफ़्लो का दिल है—इसे वह दिमाग समझिए जो बाद में इमेज पढ़ेगा। + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +यह कदम क्यों महत्वपूर्ण है? `OcrEngine` सभी कॉन्फ़िगरेशन, भाषा पैक्स, और लाइसेंसिंग डेटा को एन्कैप्सुलेट करता है। इसके बिना आप इमेज प्रोसेस नहीं कर सकते या evaluation फ़्लैग क्वेरी नहीं कर सकते। + +> **Side note:** कुछ SDK आपको कंस्ट्रक्टर में एक कॉन्फ़िगरेशन ऑब्जेक्ट पास करने की अनुमति देते हैं (जैसे भाषा, DPI)। यदि आपको कस्टम सेटिंग्स चाहिए, तो लाइन को उसी अनुसार संशोधित करें। + +## चरण 4: OCR इंजन की Evaluation Mode निर्धारित करें + +अधिकांश OCR विक्रेता एक ट्रायल संस्करण प्रदान करते हैं जो **evaluation mode** में चलता है जब तक वैध लाइसेंस की नहीं दी जाती। यह जानना कि आप ट्रायल मोड में हैं या नहीं, आपको उचित UI संकेत दिखाने या कुछ फीचर्स को प्रतिबंधित करने में मदद करता है। + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation` प्रॉपर्टी `true` रिटर्न करती है जब इंजन अनलाइसेंस्ड हो या टाइम‑लिमिटेड ट्रायल पर हो। यह प्रीमियम फीचर्स को सुरक्षित रखने का एक तेज़, भरोसेमंद तरीका है। + +### अगर प्रॉपर्टी मौजूद नहीं है तो क्या करें? + +पुराने SDK संस्करणों में `GetLicenseInfo()` जैसा मेथड हो सकता है। उस स्थिति में, रिटर्नेड ऑब्जेक्ट में `IsTrial` फ़्लैग देखेंगे। अपग्रेड करते समय हमेशा SDK चेंजलॉग देखें। + +## चरण 5: वर्तमान लाइसेंसिंग स्थिति प्रदर्शित करें + +अंत में, उपयोगकर्ता को दिखाएँ कि इंजन लाइसेंस्ड है या अभी भी ट्रायल में है। एक साधारण `Console.WriteLine` इस काम को कर देता है, लेकिन आप इसे GUI ऐप्स के लिए भी अनुकूलित कर सकते हैं। + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +टेर्नरी ऑपरेटर कोड को साफ़ रखता है, और संदेश एन्ड‑यूज़र्स या लॉग पढ़ने वाले डेवलपर्स दोनों के लिए स्पष्ट होते हैं। + +## पूर्ण कार्यशील उदाहरण + +सब कुछ एक साथ मिलाकर, यहाँ एक स्व-समाहित प्रोग्राम है जिसे आप `Program.cs` में कॉपी‑पेस्ट कर `dotnet run` के साथ चला सकते हैं। + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### अपेक्षित आउटपुट + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +यदि SDK कोई एक्सेप्शन थ्रो करता है (जैसे, नेटीव DLL गायब), तो कैच ब्लॉक एक मददगार एरर मैसेज प्रिंट करेगा और पूरी ऐप क्रैश नहीं होगी। + +## एज केस और सामान्य जालों को संभालना + +### 1. Null Engine इंस्टेंस + +हालाँकि कंस्ट्रक्टर आमतौर पर एक वैध ऑब्जेक्ट रिटर्न करता है, कुछ SDK आवश्यक नेटीव डिपेंडेंसीज़ की कमी होने पर `null` रिटर्न कर सकते हैं। इसे रोकने के लिए: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. रनटाइम में लाइसेंस समाप्त होना + +ट्रायल लाइसेंस सत्र के बीच समाप्त हो सकता है। यदि आपका ऐप लंबा चल रहा है, तो समय‑समय पर `IsEvaluation` को पुनः‑क्वेरी करें। + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. विभिन्न संस्करणों में प्रॉपर्टी नाम + +पुराने रिलीज़ में `engine.EvaluationMode` या `engine.License.IsTrial` हो सकता है। अपग्रेड करते समय SDK रिलीज़ नोट्स में ब्रेकिंग चेंजेज़ देखें। + +### 4. मल्टी‑थ्रेडेड परिदृश्य + +यदि आप कई OCR वर्कर स्पिन‑अप करते हैं, तो **प्रति थ्रेड एक OCR इंजन** बनाएं जब तक SDK स्पष्ट रूप से थ्रेड‑सेफ़ शेयरिंग सपोर्ट न करे। एक ही इंजन को शेयर करने से रेस कंडीशन और गलत लाइसेंस रीड्स हो सकते हैं। + +## प्रोडक्शन उपयोग के लिए प्रो टिप्स + +- **पहली जाँच के बाद लाइसेंसिंग स्थिति को कैश** करें ताकि अनावश्यक प्रॉपर्टी कॉल्स से बचा जा सके। +- **स्टार्टअप पर लाइसेंस की (मास्क्ड) लॉग** करें—ऑडिट ट्रेल्स के लिए उपयोगी, जिससे सपोर्ट टीम लाइसेंसिंग समस्याओं का निदान कर सके। +- **एक UI टॉगल** प्रदान करें जो उपयोगकर्ताओं को बताता है कि वे ट्रायल मोड में हैं और “Buy License” बटन ऑफर करता है। +- यदि उपलब्ध हो, तो SDK के एक्टिवेशन API का उपयोग करके **लाइसेंस रिन्यूअल को ऑटोमेट** करें, जिससे यूज़र एक्सपीरियंस स्मूद रहे। + +## निष्कर्ष + +हमने कुछ ही लाइनों में **OCR इंजन बनाना**, **OCR इंजन evaluation mode** की जाँच करना, और स्पष्ट **OCR लाइसेंसिंग स्टेटस** संदेश प्रिंट करना सीखा। पूर्ण उदाहरण बॉक्स से बाहर चलता है, एरर को ग्रेसफ़ुली हैंडल करता है, और प्रत्येक कदम के “क्यों” को उजागर करता है—ताकि आप इसे डेस्कटॉप, वेब, या सर्विस‑साइड परिदृश्यों में अनुकूलित कर सकें। + +आगे आप खोज सकते हैं: + +- इमेज को `engine.Recognize` में फीड करना और मल्टी‑लैंग्वेज सपोर्ट को हैंडल करना। +- **check OCR license** API का उपयोग करके खरीदी गई कुंजी को प्रोग्रामेटिकली एक्टिवेट करना। +- UI फ्रेमवर्क (WinForms, WPF, MAUI) के साथ इंटीग्रेट करना ताकि लाइसेंसिंग बैज दिखाए जा सकें। + +इनको आज़माएँ, और आपके पास किसी भी एप्लिकेशन के लिए एक मजबूत OCR फाउंडेशन तैयार होगा। हैप्पी कोडिंग! + +## संबंधित ट्यूटोरियल + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/ocr-optimization/_index.md b/ocr/hindi/net/ocr-optimization/_index.md index 741ae28e9..6f449055d 100644 --- a/ocr/hindi/net/ocr-optimization/_index.md +++ b/ocr/hindi/net/ocr-optimization/_index.md @@ -74,6 +74,8 @@ Aspose.OCR for .NET के साथ OCR सटीकता बढ़ाएँ ### [OCR इमेज रिकग्निशन में मल्टी‑पेज परिणाम को दस्तावेज़ के रूप में सहेजें](./save-multipage-result-as-document/) Aspose.OCR for .NET की क्षमता को अनलॉक करें। इस व्यापक चरण‑दर‑चरण गाइड के साथ मल्टी‑पेज OCR परिणामों को दस्तावेज़ों के रूप में आसानी से सहेजें। +### [OCR के लिए छवि पूर्व‑प्रसंस्करण – पूर्ण Aspose C# गाइड](./preprocess-image-for-ocr-complete-aspose-c-guide/) + ## अक्सर पूछे जाने वाले प्रश्न **Q:** क्या मैं कई भाषाओं वाली छवि फ़ाइलों से पाठ निकाल सकता हूँ? diff --git a/ocr/hindi/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/hindi/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..2dc8f5cb1 --- /dev/null +++ b/ocr/hindi/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Aspose के साथ OCR के लिए छवि को पूर्व‑प्रसंस्करण करके OCR की सटीकता बढ़ाएँ + और JPEG फ़ाइलों पर OCR चलाएँ। स्पष्ट, चरण‑दर‑चरण ट्यूटोरियल में Aspose का उपयोग + करके टेक्स्ट निकालना सीखें। +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: hi +og_description: ऑसीआर की सटीकता बढ़ाने के लिए Aspose के साथ छवि को पूर्व-प्रसंस्करण + करें। JPEG पर OCR चलाने और Aspose का उपयोग करके C# में टेक्स्ट निकालने के लिए इस + गाइड का पालन करें। +og_title: OCR के लिए छवि का पूर्व-प्रसंस्करण – Aspose C# ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: OCR के लिए छवि का पूर्व‑प्रसंस्करण – पूर्ण Aspose C# गाइड +url: /hi/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR के लिए इमेज प्रीप्रोसेस – पूर्ण Aspose C# गाइड + +क्या आप कभी सोचते थे कि **OCR के लिए इमेज प्रीप्रोसेस** कैसे करें ताकि टेक्स्ट हर बार साफ़ निकले? आप अकेले नहीं हैं—डेवलपर्स लगातार शोरयुक्त स्कैन, कम‑कॉन्ट्रास्ट JPEG, और अप्रत्याशित लाइटिंग से जूझते रहते हैं। अच्छी खबर? कुछ स्मार्ट बदलावों से आप **OCR की सटीकता** को नाटकीय रूप से बढ़ा सकते हैं, और Aspose इसे आसान बनाता है। + +इस ट्यूटोरियल में हम एक वास्तविक उदाहरण के माध्यम से दिखाएंगे कि **JPEG पर OCR चलाएँ** कैसे, एक कस्टम इमेज‑प्रोसेसिंग पाइपलाइन लागू करें, और अंत में **Aspose का उपयोग करके टेक्स्ट निकालें**। अंत तक आपके पास एक तैयार‑से‑पेस्ट C# स्निपेट होगा जिसे आप किसी भी .NET प्रोजेक्ट में डाल सकते हैं। + +## आप क्या सीखेंगे + +- प्रीप्रोसेसिंग क्यों महत्वपूर्ण है और कौन से फ़िल्टर सबसे बड़ा लाभ देते हैं। +- Aspose.OCR के `ImageProcessingOptions` को डेस्क्यूइंग, डेनॉइज़िंग, बाइनराइज़ेशन, और कॉन्ट्रास्ट बूस्टिंग के लिए कैसे कॉन्फ़िगर करें। +- **JPEG पर OCR चलाने** के लिए आवश्यक सटीक कोड और साफ़ टेक्स्ट प्राप्त करना। +- प्रोडक्शन में आपके OCR पाइपलाइन को मजबूत रखने के टिप्स और संभावित समस्याएँ। + +Aspose का कोई पूर्व अनुभव आवश्यक नहीं है; बस बुनियादी C# पृष्ठभूमि और Visual Studio (या आपका पसंदीदा IDE) चाहिए। चलिए शुरू करते हैं। + +![OCR के लिए इमेज प्रीप्रोसेस उदाहरण](preprocess-ocr.png "OCR के लिए इमेज प्रीप्रोसेस") + +## चरण 1: Aspose.OCR इंजन सेट अप करें – OCR के लिए इमेज प्रीप्रोसेस + +सबसे पहले हमें एक `OcrEngine` इंस्टेंस चाहिए और हमें उसे बताना होगा कि हम कौन सी भाषा अपेक्षित कर रहे हैं। अधिकांश मामलों में English डिफ़ॉल्ट है, लेकिन आप `OcrLanguage` एनेम बदलकर French, German आदि भी उपयोग कर सकते हैं। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Why this matters:** इंजन ऑपरेशन का दिल है; इसके बिना आप उन इमेज फ़िल्टरों को लागू नहीं कर सकते जो वास्तव में **OCR के लिए इमेज प्रीप्रोसेस** करते हैं। इसे ऐसे समझें जैसे रसोई जहाँ सभी सामग्री मिलती‑जुलती हैं। + +## चरण 2: कस्टम इमेज‑प्रोसेसिंग पाइपलाइन बनाएं – OCR की सटीकता सुधारें + +अब आता है मज़ेदार हिस्सा। Aspose आपको कई फ़िल्टरों को चेन करने देता है। नीचे हम चार सबसे प्रभावी फ़िल्टर सक्षम करते हैं: + +1. **Deskew** – झुके हुए दस्तावेज़ों को सीधा करता है (डिफ़ॉल्ट अधिकतम 5°)। +2. **Denoise** – ग्रेनी बैकग्राउंड को स्मूद करता है। +3. **Binarize** – थ्रेशोल्ड का उपयोग करके इमेज को ब्लैक‑एंड‑व्हाइट में बदलता है। +4. **ContrastBoost** – हल्के अक्षरों को उभारा जाता है। + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** यदि आपके स्रोत इमेज पहले से ही स्पष्ट हैं, तो आप `Strength` को कम कर सकते हैं या फ़िल्टर को पूरी तरह बंद कर सकते हैं। अधिक प्रोसेसिंग कभी‑कभी हल्के अक्षरों को मिटा देती है, इसलिए वास्तविक नमूनों के साथ प्रयोग करें। + +## चरण 3: JPEG (या कोई भी इमेज) लोड करें और OCR चलाएँ – JPEG पर OCR चलाएँ + +Aspose किसी भी इमेज फ़ॉर्मेट के साथ काम करता है जिसे .NET पढ़ सकता है—JPEG, PNG, BMP, आप नाम ले लीजिए। यहाँ दिखाया गया है कि JPEG फ़ाइल को इंजन में कैसे फीड करें और पहचान प्रक्रिया को कैसे शुरू करें। + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Why JPEG?** JPEG कंप्रेशन अक्सर ऐसे आर्टिफैक्ट लाता है जो OCR को भ्रमित कर देते हैं। हमारा प्रीप्रोसेसिंग पाइपलाइन, विशेष रूप से डेनॉइज़ और बाइनराइज़ चरण, इन समस्याओं को कम करता है, जिससे आप **JPEG पर OCR चलाएँ** में भरोसा रख सकते हैं। + +## चरण 4: पहचाना गया टेक्स्ट आउटपुट करें – Aspose से टेक्स्ट निकालें + +अंत में, हम बस टेक्स्ट को कंसोल, फ़ाइल, या किसी भी डाउनस्ट्रीम सर्विस में लिखते हैं। डेमो के लिए कंसोल ही पर्याप्त है। + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +जब आप प्रोग्राम चलाएँगे, तो आपको कुछ इस तरह दिखना चाहिए: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +यदि आउटपुट गड़बड़ दिखे, तो **चरण 2** पर वापस जाएँ और फ़िल्टर सेटिंग्स को समायोजित करें। छोटे समायोजन अक्सर **OCR की सटीकता सुधारें** में बड़े लाभ देते हैं। + +## सामान्य किनारे के मामलों और उन्हें कैसे संभालें + +| स्थिति | सुझाया गया समायोजन | +|-----------|----------------------| +| **बहुत डार्क इमेजेज** | `ContrastBoost.Level` को 1.5 या उससे अधिक बढ़ाएँ। | +| **Skew > 5°** | `DeskewOptions.MaxAngle` को बढ़ाएँ (जैसे, 10.0) या इमेज को मैन्युअली पहले से घुमाएँ। | +| **रंगीन टेक्स्ट पर रंगीन बैकग्राउंड** | कस्टम थ्रेशोल्ड के साथ `BinarizeOptions` उपयोग करें या `AdaptiveBinarizeOptions` पर स्विच करें। | +| **बड़ी फाइलें ( > 5 MB )** | फाइल‑लॉक समस्याओं से बचने के लिए इमेज को पहले `MemoryStream` में लोड करें। | + +ये समायोजन आपके पाइपलाइन को लचीला और भविष्य‑सुरक्षित बनाते हैं, विशेष रूप से जब आपको विविध स्रोतों से **Aspose का उपयोग करके टेक्स्ट निकालें** की आवश्यकता हो। + +## पूर्ण कार्यशील उदाहरण – सभी चरण एक जगह + +नीचे पूरा, कॉपी‑एंड‑पेस्ट‑तैयार प्रोग्राम दिया गया है। यह .NET 6+ के साथ कम्पाइल होता है और केवल `Aspose.OCR` NuGet पैकेज की आवश्यकता होती है। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +इसे `Program.cs` के रूप में सेव करें, Aspose.OCR पैकेज जोड़ें (`dotnet add package Aspose.OCR`), और `dotnet run` चलाएँ। आपको कंसोल में साफ़ किया गया टेक्स्ट प्रिंट होता दिखेगा। + +## पुनरावलोकन – यह तरीका क्यों काम करता है + +- **OCR के लिए इमेज प्रीप्रोसेस**: पाइपलाइन सबसे सामान्य त्रुटियों (स्क्यू, शोर, कम कॉन्ट्रास्ट) को हटाती है। +- **OCR की सटीकता सुधारें**: प्रत्येक फ़िल्टर सिग्नल‑टू‑नॉइज़ रेशियो को बढ़ाने के लिए ट्यून किया गया है। +- **JPEG पर OCR चलाएँ**: डेस्क्यूइंग और बाइनराइज़ेशन के बाद संकुचित इमेज भी पठनीय हो जाती हैं। +- **Aspose का उपयोग करके टेक्स्ट निकालें**: `Recognize` मेथड एक साधारण स्ट्रिंग लौटाता है, जो किसी भी डाउनस्ट्रीम लॉजिक के लिए तैयार है। + +इन चरणों के साथ आप केवल कुछ लाइनों में एक भरोसेमंद, प्रोडक्शन‑ग्रेड OCR समाधान प्राप्त कर लेते हैं। + +## अगले कदम और संबंधित विषय + +- **बैच प्रोसेसिंग** – इमेज फ़ोल्डर पर लूप चलाएँ और प्रत्येक परिणाम को `.txt` फ़ाइल में लिखें। +- **भाषा पैक** – `OcrLanguage.English` को `OcrLanguage.Spanish` से बदलें या कस्टम डिक्शनरी जोड़ें। +- **PDF एक्सट्रैक्शन** – स्कैन किए गए PDF से सीधे टेक्स्ट निकालने के लिए Aspose.OCR को Aspose.PDF के साथ मिलाएँ। +- **परफ़ॉर्मेंस ट्यूनिंग** – बड़े वर्कलोड के लिए `Parallel.ForEach` का उपयोग करके इंजन को पैरलल चलाएँ। + +फ़िल्टर मानों के साथ प्रयोग करने, विभिन्न इमेज फ़ॉर्मेट आज़माने, या `SharpnessOptions` जैसे अतिरिक्त Aspose फ़िल्टर जोड़ने में संकोच न करें। बुनियादी बातों में महारत हासिल करने के बाद संभावनाएँ असीमित हैं। + +--- + +*हैप्पी कोडिंग! यदि आपको कोई समस्या आती है, तो नीचे टिप्पणी करें और हम साथ मिलकर समाधान निकालेंगे।* + +## संबंधित ट्यूटोरियल + +- [.NET के लिए Aspose.OCR फ़िल्टर के साथ इमेज OCR प्रीप्रोसेस](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [इमेज से टेक्स्ट निकालें – .NET के लिए Aspose.OCR के साथ 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/text-recognition/_index.md b/ocr/hindi/net/text-recognition/_index.md index 0512ee10e..ea27b48c4 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 की मजबूत विशेषताओं और उद्योग-अग्रणी तकनीक के साथ अपने एप्लिकेशन की दक्षता बढ़ाएँ। ## ओसीआर छवि पहचान में ओसीआर डिटेक्ट एरिया मोड @@ -39,25 +39,51 @@ Aspose.OCR के साथ .NET में OCR की क्षमता को ## ओसीआर छवि पहचान में तालिका को पहचानें -.NET के लिए Aspose.OCR के साथ OCR छवि पहचान में तालिकाओं को पहचानने की जटिलताओं पर नेविगेट करें। हमारी व्यापक मार्गदर्शिका आपको Aspose.OCR की पूरी क्षमता को अनलॉक करने का अधिकार देती है, जिससे आपके अनुप्रयोगों में सटीक और कुशल तालिका पहचान सुनिश्चित होती है। उद्योग-अग्रणी ओसीआर समाधान के साथ अपनी परियोजनाओं को उन्नत करें। +.NET के लिए Aspose.OCR के साथ OCR छवि पहचान में तालिकाओं को पहचानने की जटिलताओं पर नेविगेट करें। हमारी व्यापक मार्गदर्शिका आपको Aspose.OCR की पूरी क्षमता को अनलॉक करने का अधिकार देती है, जिससे आपके अनुप्रयोगों में सटीक और कुशल तालिका पहचान सुनिश्चित होती है। उद्योग-अग्रणी OCR समाधान के साथ अपनी परियोजनाओं को उन्नत करें। -क्या आप अपने .NET अनुप्रयोगों में क्रांति लाने के लिए तैयार हैं? हमारे टेक्स्ट रिकग्निशन ट्यूटोरियल्स में गोता लगाएँ और छवियों में सटीक और कुशल टेक्स्ट पहचान के लिए Aspose.OCR की शक्ति का उपयोग करें। अभी डाउनलोड करें और उन्नत ओसीआर क्षमताओं की यात्रा पर निकलें। +क्या आप अपने .NET अनुप्रयोगों में क्रांति लाने के लिए तैयार हैं? हमारे टेक्स्ट रिकग्निशन ट्यूटोरियल्स में गोता लगाएँ और छवियों में सटीक और कुशल टेक्स्ट पहचान के लिए Aspose.OCR की शक्ति का उपयोग करें। अभी डाउनलोड करें और उन्नत 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 की क्षमता को अनलॉक करें। पीडीएफ़ से आसानी से टेक्स्ट निकालें। सहज एकीकरण अनुभव के लिए अभी डाउनलोड करें। + ### [ओसीआर छवि पहचान में तालिका को पहचानें](./recognize-table/) OCR छवि पहचान में तालिकाओं को पहचानने पर हमारे व्यापक गाइड के साथ .NET के लिए Aspose.OCR की क्षमता को अनलॉक करें। + +### [Aspose OCR के साथ छवि से टेक्स्ट पहचानें – पूर्ण C# गाइड](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Aspose OCR का उपयोग करके C# में छवि से टेक्स्ट निकालने की पूरी प्रक्रिया सीखें। चरण-दर-स्टेप मार्गदर्शिका। + +### [C# में OCR का उपयोग कैसे करें – JPG से चीनी टेक्स्ट पहचानें](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +C# में Aspose.OCR का उपयोग करके JPG फ़ाइल से चीनी भाषा का टेक्स्ट निकालने की चरण-दर-स्टेप गाइड। + +### [C# में रूसी टेक्स्ट OCR – Aspose OCR का उपयोग करके पूर्ण गाइड](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Aspose OCR के साथ C# में रूसी टेक्स्ट को पहचानने की पूरी प्रक्रिया सीखें। चरण-दर-स्टेप मार्गदर्शिका। + +### [C# में छवि से टेक्स्ट निकालें – पूर्ण Aspose OCR गाइड](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Aspose OCR का उपयोग करके C# में छवि से टेक्स्ट निकालने की पूरी प्रक्रिया सीखें। चरण-दर-चरण मार्गदर्शिका। + +### [ASP.NET कोर मिनिमल API में छवि से टेक्स्ट निकालें – पूर्ण गाइड](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +ASP.NET कोर मिनिमल API का उपयोग करके छवि से टेक्स्ट निकालने की पूरी प्रक्रिया सीखें। चरण-दर-चरण मार्गदर्शिका। + +### [c# OCR ट्यूटोरियल: Aspose के साथ PNG रसीदों से टेक्स्ट निकालें](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) + +### [C# में TIFF को टेक्स्ट में परिवर्तित करें – पूर्ण बैच OCR गाइड](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +C# में Aspose.OCR का उपयोग करके TIFF फ़ाइलों को टेक्स्ट में बदलने की पूरी चरण-दर-स्टेप बैच गाइड। + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/hindi/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..abdf52d26 --- /dev/null +++ b/ocr/hindi/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR ट्यूटोरियल जो दिखाता है कि कैसे इमेज फ़ाइल को c# में लोड करें + और Aspose OCR का उपयोग करके रसीद से PNG टेक्स्ट को पहचानें – चरण‑दर‑चरण गाइड। +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: hi +og_description: c# OCR ट्यूटोरियल जो आपको एक इमेज फ़ाइल c# में लोड करने और Aspose + OCR का उपयोग करके रसीद से PNG टेक्स्ट पहचानने के माध्यम से ले जाता है। +og_title: c# OCR ट्यूटोरियल – PNG रसीदों से टेक्स्ट निकालें +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR ट्यूटोरियल: Aspose के साथ PNG रसीदों से टेक्स्ट निकालें' +url: /hi/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR ट्यूटोरियल – PNG रसीदों से टेक्स्ट निकालें Aspose के साथ + +क्या आपको कभी एक **c# OCR ट्यूटोरियल** चाहिए था जो वास्तव में काम करे और अनंत गूगलिंग से बचाए? आप सही जगह पर हैं। इस गाइड में हम **load image file c#**, **recognize png text**, और **read receipt OCR** परिणाम दिखाएंगे, साथ ही आपको **perform OCR image** प्रोसेसिंग Aspose OCR के साथ कैसे करें, दिखाएंगे। + +हम आवश्यक NuGet पैकेज को इंस्टॉल करके शुरू करेंगे, कोड की प्रत्येक पंक्ति को समझेंगे, और एक साफ़ JSON डम्प के साथ समाप्त करेंगे जिसे आप सीधे अपने अगले डेटा‑पाइपलाइन में पाइप कर सकते हैं। कोई फालतू नहीं, सिर्फ एक व्यावहारिक, तैयार‑चलाने योग्य समाधान। + +## आप क्या सीखेंगे + +- Aspose OCR को .NET 6 (या बाद के) प्रोजेक्ट में कैसे सेटअप करें। +- **load an image file c#** करने के सटीक चरण और इसे इंजन को सौंपना। +- रसीद की छवि से **recognize png text** करने और परिणाम को कैप्चर करने का तरीका। +- **read receipt OCR** आउटपुट को सुंदर फ़ॉर्मेटेड JSON के रूप में प्राप्त करने के तरीके। +- विभिन्न फ़ाइल प्रकारों पर **perform OCR image** ऑपरेशन्स और सामान्य समस्याओं को संभालने के टिप्स। + +**Prerequisites** +- Visual Studio 2022 (या कोई भी IDE जो आप पसंद करें)। +- .NET 6 SDK या नया। +- एक PNG रसीद छवि तैयार रखें (हम इसे `receipt.png` कहेंगे)। + +यदि आपके पास ये हैं, तो चलिए शुरू करते हैं। + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR ट्यूटोरियल – Aspose OCR इंजन सेटअप + +सबसे पहले, हमें Aspose OCR लाइब्रेरी चाहिए। समाधान फ़ोल्डर में अपना टर्मिनल खोलें और चलाएँ: + +```bash +dotnet add package Aspose.OCR +``` + +यह एकल कमांड सभी आवश्यक चीज़ें लाता है, जिसमें इमेज डिकोडिंग के लिए नेटिव बाइनरी भी शामिल हैं। इंस्टॉल होने के बाद, एक नया कंसोल प्रोजेक्ट बनाएं या कोड को मौजूदा में जोड़ें। + +### क्यों Aspose? + +Aspose OCR 30 से अधिक भाषाओं का समर्थन करता है, ऑफ़लाइन काम करता है, और एक समृद्ध `OcrResult` ऑब्जेक्ट लौटाता है—जो **perform OCR image** कार्यों के लिए उपयुक्त है जहाँ आपको साधारण टेक्स्ट से अधिक चाहिए। + +## Load image file c# और रसीद तैयार करें + +अब लाइब्रेरी तैयार है, चलिए **load image file c#** करते हैं। `System.Drawing.Image` क्लास भारी काम करती है, लेकिन यदि आप क्रॉस‑प्लेटफ़ॉर्म विकल्प चाहते हैं तो `SkiaSharp` भी उपयोग कर सकते हैं। + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** `Image` को `using` स्टेटमेंट में लपेटें (जैसा दिखाया गया है) ताकि नेटिव रिसोर्सेज़ तुरंत मुक्त हो जाएँ—विशेषकर जब आप लूप में कई फ़ाइलों पर **perform OCR image** करते हैं। + +## Aspose के साथ PNG टेक्स्ट पहचानें + +इमेज मेमोरी में होने के बाद, इंजन अब **recognize png text** कर सकता है। Aspose एक `OcrResult` लौटाता है जिसमें कच्चा स्ट्रिंग और प्रत्येक पहचाने गए शब्द के बारे में विस्तृत डेटा दोनों होते हैं। + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +क्यों `Recognize` की बजाय `RecognizeWithResult` को कॉल करें? पहला आपको कॉन्फिडेंस स्कोर, बाउंडिंग बॉक्स, और लाइन ब्रेक्स तक पहुँच देता है—जो तब उपयोगी है जब आपको बाद में **read receipt OCR** करके लाइन‑आइटम निकालना हो। + +## receipt OCR परिणाम को JSON के रूप में पढ़ें + +अधिकांश डाउनस्ट्रीम सिस्टम JSON को पसंद करते हैं, इसलिए चलिए `OcrResult` को सीरियलाइज़ करते हैं। `System.Text.Json` सीरियलाइज़र जटिल ऑब्जेक्ट्स को सहजता से संभालता है, और हम पठनीयता के लिए इंडेंटेशन सक्षम करेंगे। + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +परिणामी JSON कुछ इस तरह दिखता है (संक्षिप्तता के लिए छोटा किया गया): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +अब आप `jsonResult` को डेटाबेस, मैसेज क्यू में पाइप कर सकते हैं, या डिबगिंग के लिए सरलता से लॉग कर सकते हैं। + +## OCR इमेज प्रोसेसिंग करें और आउटपुट दिखाएँ + +अंत में, JSON को कंसोल पर आउटपुट करें। वास्तविक एप्लिकेशन में आप इसे फ़ाइल में लिखेंगे या HTTP के माध्यम से भेजेंगे, लेकिन कंसोल से यह सत्यापित करना आसान होता है कि सब काम किया। + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +प्रोग्राम चलाएँ (`dotnet run`) और आपको सुंदर फ़ॉर्मेटेड JSON प्रिंट होता दिखेगा। यदि रसीद की छवि स्पष्ट है, तो टेक्स्ट बिल्कुल सही होगा; यदि नहीं, तो इमेज रिज़ॉल्यूशन बढ़ाने या प्री‑प्रोसेसिंग फ़िल्टर (जैसे ग्रेस्केल, कॉन्ट्रास्ट बूस्ट) लागू करने पर विचार करें, इससे पहले कि आप इसे इंजन को दें। + +### सामान्य किनारे मामलों को संभालना + +| Situation | What to do | +|-----------|------------| +| **Image धुंधली है** | `System.Drawing` के साथ प्री‑प्रोसेस करें ताकि शार्पन हो या DPI बढ़े। | +| **Receipt में कई भाषाएँ हैं** | Set `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **बड़ी बैच प्रोसेसिंग** | `OcrEngine` की एक ही इंस्टेंस को पुन: उपयोग करें; प्रत्येक इटरेशन में केवल `Image` बदलें। | +| **Memory दबाव** | `Image` ऑब्जेक्ट्स को तुरंत डिस्पोज़ करें और async पाइपलाइन के लिए `await Task.Run` पर विचार करें। | + +ये बदलाव आपके **perform OCR image** वर्कफ़्लो को मजबूत बनाते हैं, भले ही इनपुट परिपूर्ण न हो। + +## समापन + +बधाई हो—आपने अभी एक **c# OCR ट्यूटोरियल** पूरा किया है जो एक इमेज लोड करता है, **recognizes png text**, और **reads receipt OCR** आउटपुट को साफ़ JSON के रूप में देता है। मुख्य चरण (इंजन सेटअप, इमेज लोडिंग, OCR निष्पादन, सीरियलाइज़ेशन, और डिस्प्ले) एक ठोस आधार बनाते हैं जिसे आप इनवॉइस, पासपोर्ट, या किसी भी स्कैन किए दस्तावेज़ तक विस्तारित कर सकते हैं। + +### आगे क्या? + +- `SkiaSharp` का उपयोग करके **load image file c#** के साथ प्रयोग करें ताकि वास्तविक क्रॉस‑प्लेटफ़ॉर्म समर्थन मिले। +- `OcrResult.Words` में गहराई से जाएँ ताकि लाइन आइटम, कीमतें, और तिथियाँ निकाल सकें—जो expense‑tracking ऐप्स के लिए उपयुक्त है। +- इस ट्यूटोरियल को Azure Functions या AWS Lambda के साथ मिलाकर एक सर्वरलेस receipt‑processing API बनाएँ। + +कोड को बदलने, अधिक इमेज़ जोड़ने, या यहाँ तक कि अलग भाषा पैक में स्विच करने में संकोच न करें। OCR की दुनिया आश्चर्यों से भरी है, और अब आपके पास उन्हें खोजने के उपकरण हैं। + +कोडिंग का आनंद लें, और आपकी रसीदें हमेशा पढ़ने योग्य रहें! + +## संबंधित ट्यूटोरियल + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ इमेज टेक्स्ट निकालें C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [इमेज से टेक्स्ट निकालें – .NET के लिए Aspose.OCR के साथ OCR ऑप्टिमाइज़ेशन](/ocr/english/net/ocr-optimization/) +- [OCR कैसे उपयोग करें - टेक्स्ट एरिया डिटेक्शन के बिना इमेज पहचानें](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/hindi/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..ce320083c --- /dev/null +++ b/ocr/hindi/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Aspose.OCR का उपयोग करके C# में TIFF को टेक्स्ट में बदलें। बैच इमेज‑टू‑टेक्स्ट + रूपांतरण सीखें और TIFF फ़ाइलों से प्रभावी ढंग से टेक्स्ट निकालें। +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: hi +og_description: Aspose.OCR के साथ TIFF को टेक्स्ट में बदलें। यह गाइड बैच इमेज‑से‑टेक्स्ट + रूपांतरण और कुछ ही C# लाइनों में TIFF फ़ाइलों से टेक्स्ट निकालने का तरीका दिखाता + है। +og_title: C# में TIFF को टेक्स्ट में बदलें – पूर्ण बैच OCR गाइड +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: C# में TIFF को टेक्स्ट में परिवर्तित करें – पूर्ण बैच OCR गाइड +url: /hi/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में TIFF को टेक्स्ट में बदलें – पूर्ण बैच OCR गाइड + +क्या आपको कभी **TIFF को टेक्स्ट में बदलने** की ज़रूरत पड़ी है लेकिन आप नहीं जानते थे कि कहाँ से शुरू करें? आप अकेले नहीं हैं—कई डेवलपर्स स्कैन किए गए दस्तावेज़ों के साथ काम करते समय बैच OCR में फंस जाते हैं। इस ट्यूटोरियल में हम एक व्यावहारिक समाधान के माध्यम से चलेंगे जो Aspose.OCR का उपयोग करके **TIFF फ़ाइलों से टेक्स्ट निकालता** है, और हम इसे समानांतर (parallel) करेंगे ताकि बड़े फ़ोल्डर सेकंडों में समाप्त हो जाएँ। + +हम **बैच इमेज टू टेक्स्ट कन्वर्ज़न** की सर्वोत्तम प्रथाओं को भी छूएँगे, इसलिए अंत तक आपके पास एक पुन: उपयोग योग्य स्निपेट होगा जो स्कैन की गई इमेजों की पूरी डायरेक्टरी को साफ़ *.txt* फ़ाइलों में बदल देता है—इंडेक्सिंग, सर्चिंग, या डाउनस्ट्रीम एनालिटिक्स में फ़ीड करने के लिए एकदम उपयुक्त। + +## आपको क्या चाहिए + +- **.NET 6.0** या बाद का संस्करण (कोड .NET Framework पर भी कंपाइल होता है) +- **Aspose.OCR for .NET** NuGet पैकेज (`Install-Package Aspose.OCR`) +- एक फ़ोल्डर जिसमें एक या अधिक *.tif* फ़ाइलें हों (क्लासिक TIFF स्कैन फ़ॉर्मेट) +- आपका पसंदीदा IDE (Visual Studio, VS Code, Rider—जो भी आपको पसंद हो) + +बस इतना ही। कोई बाहरी सेवाएँ नहीं, कोई API कुंजी नहीं, सिर्फ शुद्ध C# और Aspose। + +![एक TIFF फ़ाइल को प्रोसेस किया जा रहा है और परिणामी टेक्स्ट फ़ाइल का स्क्रीनशॉट](/images/ocr-result.png "OCR परिणाम दिखा रहा है कि TIFF को टेक्स्ट आउटपुट में बदला गया") + +*(Alt text: स्क्रीन पर दिखाए गए परिवर्तित TIFF से टेक्स्ट आउटपुट का स्क्रीनशॉट)* + +## चरण 1: OCR इंजन सेट अप करें – TIFF को टेक्स्ट में बदलें + +सबसे पहले, हमें एक `OcrEngine` इंस्टेंस चाहिए जो जानता हो कि उसे अंग्रेज़ी अक्षर पढ़ने चाहिए। इंजन परिवर्तन का दिल है; इसे सही ढंग से कॉन्फ़िगर करने से विश्वसनीय परिणाम सुनिश्चित होते हैं। + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*यह क्यों महत्वपूर्ण है:* +Aspose.OCR कई भाषाओं का समर्थन करता है। यदि आप बहुभाषी स्कैन से निपट रहे हैं, तो बस `OcrLanguage.English` को उपयुक्त enum मान में बदल दें। भाषा को अनिर्धारित छोड़ने से इंजन ऑटो‑डिटेक्ट मोड में चला जाता है, जो धीमा और कम सटीक हो सकता है। + +## चरण 2: सभी TIFF फ़ाइलें इकट्ठा करें – TIFF से टेक्स्ट कुशलतापूर्वक निकालें + +अगला हम आपके द्वारा निर्दिष्ट फ़ोल्डर से हर *.tif* फ़ाइल को खींचते हैं। `Directory.GetFiles` का उपयोग करने से हमें एक साफ़ एरे मिलता है जिसे हम बैच प्रोसेसर में फीड कर सकते हैं। + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*प्रो टिप:* यदि आपके स्कैन उप‑फ़ोल्डरों में नेस्टेड हैं तो `SearchOption.AllDirectories` फ़्लैग का उपयोग किया जा सकता है। बस याद रखें कि गहरी पुनरावृत्ति बैच चरण के दौरान मेमोरी उपयोग को बढ़ा सकती है। + +## चरण 3: समानांतर OCR निष्पादित करें – बैच इमेज टू टेक्स्ट कन्वर्ज़न + +अब मज़ेदार हिस्सा। Aspose.OCR एक स्थैतिक हेल्पर `BatchOcr.RecognizeAll` के साथ आता है जो फ़ाइल पाथों की एरे, एक इंजन, और एक `parallelism` संकेत स्वीकार करता है। हम चार थ्रेड्स शुरू करेंगे, जो एक आधुनिक क्वाड‑कोर लैपटॉप पर लगभग रैखिक गति‑वृद्धि देता है। + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*समानांतरता क्यों?* +उच्च‑रिज़ॉल्यूशन TIFFs के बैच को स्कैन करना CPU‑गहन हो सकता है। कार्य को कई थ्रेड्स में बाँटकर हम सभी कोर को व्यस्त रखते हैं, जिससे कुल रनटाइम में उल्लेखनीय कमी आती है। यदि आप इसे अधिक कोर वाले सर्वर पर चलाते हैं, तो `parallelism` मान को उसी अनुसार बढ़ाएँ। + +## चरण 4: आउटपुट लिखें – स्कैन की गई इमेजों को TXT फ़ाइलों में बदलें + +अंत में हम डिक्शनरी पर लूप लगाते हैं और प्रत्येक टेक्स्ट को एक *.txt* फ़ाइल में लिखते हैं जिसका बेस नाम मूल फ़ाइल के समान हो। यही वह क्षण है जब **convert scanned images txt** वास्तविकता बन जाता है। + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### कोड क्या करता है, साधारण अंग्रेज़ी में + +1. **Create** एक OCR इंजन जो अंग्रेज़ी के लिए सेट हो। +2. **Collect** लक्ष्य फ़ोल्डर से हर TIFF फ़ाइल। +3. **Run** `BatchOcr.RecognizeAll` चार थ्रेड्स के साथ, प्रत्येक इमेज को स्ट्रिंग में बदलते हुए। +4. **Loop** परिणामों पर, `.tif` एक्सटेंशन को `.txt` से बदलें और स्ट्रिंग को डिस्क पर लिखें। + +यह पूरी **convert TIFF to text** वर्कफ़्लो है, जो 50 लाइनों से कम कोड में पूरी होती है। + +## किनारे के मामलों को संभालना – जब चीज़ें सुचारू नहीं चलतीं + +- **Missing or corrupted TIFFs** – `BatchOcr` एक `OcrException` फेंकेगा। यदि आपको सुगम गिरावट चाहिए तो कॉल को `try / catch` में रैप करें। +- **Non‑English documents** – `OcrLanguage.English` को `OcrLanguage.Spanish`, `OcrLanguage.French` आदि में बदलें, या `OcrLanguage.AutoDetect` का उपयोग करें। +- **Very large images** – OCR से पहले DPI को कम करने पर विचार करें (`ocrEngine.ImagePreprocessing.Dpi = 200`) ताकि मेमोरी बचे, हालांकि इससे कुछ सटीकता खो सकती है। +- **Output encoding** – यदि आपको एक विशिष्ट कोड पेज चाहिए (जैसे, Windows‑1252), तो इसे `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))` में पास करें। + +## मजबूत बैच कन्वर्ज़न के लिए प्रो टिप्स + +- **Log failures**: एक `List failedFiles` बनाएँ और किसी भी फाइल को जो एक्सेप्शन फेंके, उसमें जोड़ें; लूप के बाद सूची को लॉग में लिखें। +- **Reuse the engine**: वही `OcrEngine` इंस्टेंस कई फ़ाइलों में पुन: उपयोग किया जा सकता है; लूप के अंदर इसे इंस्टैंशिएट न करें। +- **Validate the result**: एक त्वरित `if (string.IsNullOrWhiteSpace(extractedText))` स्कैन को फ़्लैग कर सकता है जो खाली या अपठनीय थे। +- **Combine with PDF**: यदि आपका स्रोत एक मल्टी‑पेज PDF है, तो पहले प्रत्येक पेज को TIFF में बदलें (Aspose.PDF यह करता है) और फिर इस बैच को चलाएँ। + +## अगले कदम – साधारण कन्वर्ज़न से आगे बढ़ना + +अब जब आप बल्क में **TIFF से टेक्स्ट निकाल** सकते हैं, तो आप चाह सकते हैं: + +- *.txt* फ़ाइलों को एक सर्च इंडेक्स में फ़ीड करें (Elasticsearch, Azure Cognitive Search)। +- प्रत्येक परिणाम पर भाषा पहचान चलाएँ ताकि दस्तावेज़ों को स्थानीय‑विशिष्ट पाइपलाइन में रूट किया जा सके। +- OCR टेक्स्ट को मूल इमेजों पर ओवरले करके सर्चेबल PDFs बनाएँ (फिर से Aspose.PDF)। + +इन सभी परिदृश्यों का आधार वही मुख्य विचार है: **batch image to text conversion** बड़े दस्तावेज़‑प्रोसेसिंग सिस्टमों के लिए एक बिल्डिंग ब्लॉक है। + +--- + +### निष्कर्ष + +आपने अभी-अभी सीखा है कि Aspose.OCR का उपयोग करके **TIFF को टेक्स्ट में कैसे बदलें**, एक पूरे फ़ोल्डर को समानांतर रूप से प्रोसेस करें, और प्रत्येक परिणाम को एक साफ़ *.txt* फ़ाइल के रूप में सहेजें। समाधान हल्का, पूरी तरह कॉन्फ़िगर करने योग्य, और प्रोडक्शन के लिए तैयार है—चाहे आप लेगेसी इनवॉइसेज़ को डिजिटल बना रहे हों, स्कैन किए गए कॉन्ट्रैक्ट्स को आर्काइव कर रहे हों, या टेक्स्ट‑सर्च इंजन को शक्ति दे रहे हों। + +इसे चलाएँ, समानांतरता को समायोजित करें, और उन नई बनी टेक्स्ट फ़ाइलों को अपने आवश्यक वर्कफ़्लो में फ़ीड करना शुरू करें। खुशहाल OCRing! + +--- + +## संबंधित ट्यूटोरियल + +- [फ़ोल्डर्स पर OCR ऑपरेशन का उपयोग करके इमेज से टेक्स्ट निकालें](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [इमेज से टेक्स्ट निकालें – .NET के लिए Aspose.OCR के साथ 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/hindi/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..b2a710005 --- /dev/null +++ b/ocr/hindi/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-05-25 +description: एक न्यूनतम ASP.NET Core API के साथ छवि से टेक्स्ट निकालना सीखें। POST + के माध्यम से छवि अपलोड करें, मल्टीपार्ट फ़ॉर्म डेटा पढ़ें और छवि पर OCR करें। +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: hi +og_description: एक न्यूनतम ASP.NET Core API का उपयोग करके छवि से टेक्स्ट निकालें। + यह गाइड दिखाता है कि POST के माध्यम से छवि कैसे अपलोड करें, मल्टीपार्ट फ़ॉर्म डेटा + पढ़ें, और छवि पर OCR कैसे करें। +og_title: ASP.NET Core में छवि से टेक्स्ट निकालें – चरण‑दर‑चरण +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: ASP.NET Core Minimal API में छवि से पाठ निकालें – पूर्ण मार्गदर्शिका +url: /hi/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + +क्या आपने कभी सोचा है कि **छवि से टेक्स्ट निकालना** बिना भारी फ्रेमवर्क के कैसे किया जाए? आप अकेले नहीं हैं। कई डेवलपर्स को तेज़ तरीका चाहिए जहाँ उपयोगकर्ता एक तस्वीर ड्रॉप कर सके और तुरंत कच्चे अक्षर प्राप्त कर सके, चाहे वह रसीद स्कैन करना हो, हाथ से लिखे नोट्स को डिजिटल बनाना हो, या सर्च इंडेक्स को पावर देना हो। + +इस ट्यूटोरियल में हम एक छोटा ASP.NET Core Minimal API बनाएँगे जो **POST के माध्यम से इमेज अपलोड** करता है, *multipart/form‑data* पेलोड को पार्स करता है, और फिर **इमेज पर OCR** को एक singleton `OcrEngine` की मदद से चलाता है। अंत तक आपके पास एक पूरी तरह चलने योग्य एप्लिकेशन होगा जिसे आप किसी भी .NET 8 प्रोजेक्ट में डाल सकते हैं और तुरंत इमेज से टेक्स्ट निकालना शुरू कर सकते हैं। + +## What You’ll Build + +- एक मिनिमल वेब ऐप जो `/ocr` पर सुनता है। +- एक एंडपॉइंट जो `multipart/form-data` POST अनुरोध के साथ भेजी गई इमेज फ़ाइल को स्वीकार करता है। +- लॉजिक जो अपलोड की गई फ़ाइल को पढ़ता है, उसे OCR इंजन को देता है, और प्लेन‑टेक्स्ट परिणाम लौटाता है। +- वैकल्पिक GPU एक्सेलेरेशन स्निपेट (कमेंटेड) उन लोगों के लिए जिनके पास संगत कार्ड है। + +**Prerequisites** +- .NET 8 SDK (या बाद का संस्करण)। +- C# और कमांड लाइन की बुनियादी जानकारी। +- एक OCR लाइब्रेरी जो `OcrEngine` क्लास प्रदान करती है (सैंपल एक काल्पनिक NuGet पैकेज मानता है)। + +यदि आपके पास ये हैं, तो चलिए शुरू करते हैं। + +## Step 1: Set Up the Project and Add the OCR Package + +पहले, एक नया वेब प्रोजेक्ट बनाइए और OCR लाइब्रेरी जोड़िए। + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro tip:** अपनी डिपेंडेंसीज़ को अपडेटेड रखें। नए वर्ज़न अक्सर परफ़ॉर्मेंस सुधार लाते हैं, विशेषकर GPU‑accelerated inference के लिए। + +## Step 2: Register a Singleton OCR Engine (Primary Service) + +हम चाहते हैं कि पूरे ऐप के लिए एक ही `OcrEngine` इंस्टेंस रहे—प्रत्येक अनुरोध पर नया इंजन बनाने की ज़रूरत नहीं। इसे बिल्डर की सर्विस कंटेनर में रजिस्टर करें। + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Why a singleton?** +OCR इंजन बनाना महंगा हो सकता है—जैसे न्यूरल‑नेटवर्क वज़न को मेमोरी में लोड करना। वही इंस्टेंस दोबारा उपयोग करके हम CPU साइकिल और RAM दोनों बचाते हैं, जिससे हर `/ocr` कॉल के लिए तेज़ रिस्पॉन्स टाइम मिलता है। + +## Step 3: Build the Application + +अब हम `WebApplication` ऑब्जेक्ट को वास्तविक रूप देते हैं। + +```csharp +var app = builder.Build(); +``` + +यह लाइन लगभग जादुई लगती है, लेकिन अंदर से यह रूटिंग, मिडलवेयर, और DI कंटेनर को कॉन्फ़िगर करती है जिसे हमने अभी सेट किया था। + +## Step 4: Define the POST Endpoint – “Upload Image via POST” + +यहाँ ट्यूटोरियल का मुख्य भाग है: एक एंडपॉइंट जो **POST के माध्यम से इमेज अपलोड** करता है, multipart पेलोड पढ़ता है, और डेटा को OCR इंजन को देता है। + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Breaking Down the Logic + +| चरण | क्या होता है | क्यों महत्वपूर्ण है | +|------|--------------|-------------------| +| **ReadFormAsync** | इनकमिंग *multipart/form-data* अनुरोध को पार्स करता है। | इसके बिना आप अपलोड की गई फ़ाइलों तक पहुँच नहीं सकते। | +| **form.Files["image"]** | उस फ़ाइल को प्राप्त करता है जिसका फ़ॉर्म‑फ़ील्ड नाम `image` है। | कॉलर्स के लिए एक पूर्वनिर्धारित कॉन्ट्रैक्ट सुनिश्चित करता है। | +| **Content‑type check** | फ़ाइल का इमेज होना सत्यापित करता है (जैसे `image/png`)। | OCR इंजन को नॉन‑इमेज डेटा पर फेल होने से रोकता है। | +| **Image.FromStream** | रॉ स्ट्रीम को `System.Drawing.Image` में बदलता है। | OCR लाइब्रेरी को `Image` ऑब्जेक्ट चाहिए, न कि रॉ बाइट ऐरे। | +| **ocr.Recognize(img)** | OCR इंजन को **इमेज से टेक्स्ट कैसे पहचानें** को कॉल करता है। | यह मुख्य **इमेज पर OCR** स्टेप है। | +| **Results.Text** | प्लेन‑टेक्स्ट रिस्पॉन्स वापस भेजता है। | डाउनस्ट्रीम सर्विसेज के लिए एक सरल, उपयोगी फ़ॉर्मेट। | + +## Step 5: Run the API + +अंत में, वेब सर्वर को स्टार्ट करें। + +```csharp +app.Run(); +``` + +जब आप `dotnet run` चलाते हैं, API `http://localhost:5000` (या आपकी चुनी हुई पोर्ट) पर सुनना शुरू कर देगा। आप इसे `curl` से टेस्ट कर सकते हैं: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Expected output:** कंसोल में पहचाने गए अक्षर प्रिंट होंगे, उदाहरण के तौर पर: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +यदि इमेज धुंधली है या भाषा समर्थित नहीं है, तो OCR इंजन खाली स्ट्रिंग या एरर मैसेज लौटाएगा—प्रोडक्शन कोड में इन केसों को हैंडल करें। + +## Edge Cases & Best Practices + +### 1. Large Files + +डिफ़ॉल्ट रिक्वेस्ट बॉडी लिमिट 30 MB है। बड़े स्कैन के लिए आपको इसे समायोजित करना पड़ सकता है: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynchronous OCR + +कुछ OCR लाइब्रेरी async मेथड (`RecognizeAsync`) प्रदान करती हैं। यदि आपका ऐसा है, तो `ocr.Recognize(img)` को `await ocr.RecognizeAsync(img)` से बदलें और लैम्ब्डा को `async` मार्क करें। + +### 3. Security Considerations + +- **फ़ाइल साइज वैलिडेट** करें इससे पहले कि उसे मेमोरी में लोड करें। +- **फ़ाइलनाम को सैनिटाइज़** करें यदि आप उसे डिस्क पर लिखते हैं। +- **रेट‑लिमिट** लागू करें ताकि डिनायल‑ऑफ़‑सर्विस अटैक से बचा जा सके। + +### 4. GPU Acceleration + +यदि आप `engine.GpuDevice = new GpuDevice(0);` लाइन को अनकमेंट करते हैं और आपका हार्डवेयर CUDA या DirectML सपोर्ट करता है, तो आप तेज़ प्रोसेसिंग देखेंगे, विशेषकर हाई‑रेज़ोल्यूशन इमेज पर। + +## Full Working Example + +नीचे पूरा `Program.cs` दिया गया है जिसे आप एक नए Minimal API प्रोजेक्ट में कॉपी‑पेस्ट कर सकते हैं। + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +सेव करें, `dotnet run` चलाएँ, और आप **इमेज से टेक्स्ट निकालने** के लिए तैयार हैं। + +## Conclusion + +हमने ASP.NET Core Minimal API का उपयोग करके इमेज से टेक्स्ट निकालने के लिए **पूरा, एंड‑टू‑एंड समाधान** पर काम किया। प्रोजेक्ट सेटअप से लेकर **singleton OCR इंजन रजिस्टर** करने, **POST के माध्यम से इमेज अपलोड** करने, **multipart फ़ॉर्म डेटा पढ़ने**, और अंत में **इमेज पर OCR** करके साफ़ प्लेन‑टेक्स्ट लौटाने तक का सफ़र तय किया। + +अब आप कर सकते हैं: + +- रिचर रिस्पॉन्स के लिए JSON रैपर जोड़ें। +- निकाले गए टेक्स्ट को स्टोर करने के लिए डेटाबेस इंटीग्रेट करें। +- कई भाषाओं (`OcrLanguage.Spanish` आदि) को सपोर्ट करने के लिए विस्तार करें। + +यह पैटर्न आसानी से स्केल करता है—इसे किसी बड़े माइक्रोसर्विस में डालें या API गेटवे के पीछे एक्सपोज़ करें। + +PDF हैंडलिंग, बैच प्रोसेसिंग, या GPU ट्यूनिंग के बारे में सवाल हैं? कमेंट करें, और हैप्पी कोडिंग! + +## Related Tutorials + +- [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/hindi/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/hindi/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..246f0397a --- /dev/null +++ b/ocr/hindi/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-05-25 +description: C# और Aspose OCR का उपयोग करके छवि से टेक्स्ट निकालें। सीखें कि JPG को + टेक्स्ट में कैसे बदलें, OCR के लिए छवि लोड करें, और तेज़ व भरोसेमंद परिणाम प्राप्त + करें। +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: hi +og_description: C# के साथ छवि से टेक्स्ट निकालें। यह गाइड दिखाता है कि JPG को टेक्स्ट + में कैसे बदलें, OCR के लिए छवि लोड करें, और बहुभाषी सामग्री को कैसे संभालें। +og_title: C# में इमेज से टेक्स्ट निकालें – Aspose OCR ट्यूटोरियल +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: C# में छवि से पाठ निकालें – पूर्ण Aspose OCR गाइड +url: /hi/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# इमेज से टेक्स्ट निकालें C# में – पूर्ण Aspose OCR गाइड + +क्या आपने कभी सोचा है कि साधारण C# कोड का उपयोग करके **extract text from image** कैसे किया जाए? आप अकेले नहीं हैं। चाहे आप रसीदें डिजिटल कर रहे हों, साइनबोर्ड स्कैन कर रहे हों, या सिर्फ OCR के बारे में जिज्ञासु हों, तस्वीर से अक्षर निकालने की क्षमता एक उपयोगी कौशल है। इस ट्यूटोरियल में हम एक पूर्ण, चलाने योग्य उदाहरण के माध्यम से दिखाएंगे कि Aspose.OCR के साथ **extract text from image** कैसे किया जाता है, और हम यह भी कवर करेंगे कि **convert jpg to text**, **load image for OCR** कैसे किया जाता है, और क्लासिक “**how to ocr image**” प्रश्न का उत्तर एक बार में देंगे। + +इस गाइड के अंत तक आपके पास एक स्वयं‑संकलित कंसोल एप्लिकेशन होगा जो JPEG फ़ाइल पढ़ता है, यूक्रेनी (या कोई अन्य समर्थित भाषा) को पहचानता है, और परिणाम को कंसोल में प्रिंट करता है। कोई अस्पष्ट संदर्भ नहीं, कोई अधूरी चीज़ नहीं—सिर्फ एक पूर्ण समाधान जिसे आप कॉपी‑पेस्ट करके चला सकते हैं। + +--- + +## आप क्या सीखेंगे + +* Aspose.OCR NuGet पैकेज को कैसे इंस्टॉल करें। +* C# में **load image for OCR** के लिए आवश्यक सटीक कोड। +* भाषा सेट करना और वास्तव में **extract text from image** करना। +* **convert jpg to text** को प्रभावी ढंग से करने के ट्रिक्स। +* सामान्य pitfalls और उन्हें कैसे टालें। + +यदि आपके पास पहले से ही .NET विकास पर्यावरण सेटअप है, तो आप शुरू करने के लिए तैयार हैं। अन्यथा, नीचे दिया गया प्रीरेक्विजिट्स सेक्शन आपको तैयार कर देगा। + +## आवश्यकताएँ + +| आवश्यकता | क्यों महत्वपूर्ण है | +|-------------|----------------| +| .NET 6.0 SDK (या नया) | कंसोल एप्लिकेशन के लिए रनटाइम प्रदान करता है। | +| Visual Studio 2022 या VS Code | एडिटिंग और डिबगिंग को आसान बनाता है। | +| इंटरनेट कनेक्शन (पहली बार चलाने पर) | NuGet को Aspose.OCR डाउनलोड करने की आवश्यकता होती है। | +| एक JPEG इमेज जिसे आप प्रोसेस करना चाहते हैं (उदा., `ukrainian_sign.jpg`) | OCR इंजन के लिए स्रोत फ़ाइल। | + +> **Pro tip:** यदि आप Linux या macOS पर हैं, तो वही कोड .NET CLI (`dotnet new console`) के साथ काम करता है, इसलिए भारी IDE को छोड़ने में संकोच न करें। + +## चरण 1 – NuGet के माध्यम से Aspose.OCR इंस्टॉल करें + +अपना टर्मिनल (या पैकेज मैनेजर कंसोल) खोलें और चलाएँ: + +```bash +dotnet add package Aspose.OCR +``` + +यह एकल लाइन नवीनतम Aspose.OCR बाइनरीज़ और सभी ट्रांज़िटिव डिपेंडेंसीज़ को डाउनलोड करती है। कोई मैनुअल DLL जुग्लिंग आवश्यक नहीं। + +## चरण 2 – OCR इंजन बनाएं (एक्सट्रैक्शन का हृदय) + +अब जब लाइब्रेरी उपलब्ध है, हम `OcrEngine` का एक इंस्टेंस बना सकते हैं। यह ऑब्जेक्ट **extracting text from image** डेटा के लिए जिम्मेदार है। + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Why this matters:** इंजन OCR एल्गोरिदम, भाषा मॉडल, और कॉन्फ़िगरेशन विकल्पों को संलग्न करता है। इसे एक बार इंस्टैंशिएट करके कई इमेज पर पुनः उपयोग करना मेमोरी‑कुशल और तेज़ है। + +## चरण 3 – OCR के लिए इमेज लोड करें (और भाषा सेट करें) + +अगला कदम इंजन को बताना है कि कौन सी तस्वीर पढ़नी है। यहाँ **load image for OCR** वाक्यांश काम आता है। + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Edge case:** यदि फ़ाइल मौजूद नहीं है, तो `Image.FromFile` `FileNotFoundException` फेंकता है। प्रोडक्शन कोड के लिए कॉल को try‑catch ब्लॉक में रैप करें। + +## चरण 4 – OCR करें और टेक्स्ट निकालें + +इमेज लोड होने के बाद, इंजन अब **extract text from image** कर सकता है। `Recognize` मेथड यह भारी काम करता है। + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +यदि सब कुछ ठीक रहता है, तो `recognizedText` में OCR इंजन द्वारा पढ़े गए सभी टेक्स्ट का प्लेन‑टेक्स्ट प्रतिनिधित्व होगा। + +## चरण 5 – JPG को टेक्स्ट में बदलें (सब कुछ एक साथ) + +अब तक हमने जो कोड बनाया है वह पहले से ही **convert jpg to text** करता है, लेकिन चलिए इसे एक साफ़ मेथड में रैप करते हैं जिसे आप बार‑बार कॉल कर सकते हैं। + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +अब आप बस यह कर सकते हैं: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Expected output** (संक्षिप्त रूप में): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +यदि इमेज में अंग्रेज़ी टेक्स्ट है, तो `OcrLanguage.English` बदलें और आप संबंधित आउटपुट देखेंगे। + +## चरण 6 – सामान्य “How to OCR Image” प्रश्नों को संभालना + +### 6.1 क्या मैं PNG या BMP को OCR कर सकता हूँ? + +बिल्कुल। `Image.FromFile` मेथड उन सभी फ़ॉर्मैट्स को सपोर्ट करता है जिन्हें System.Drawing पहचानता है, इसलिए बस पाथ को `.png` या `.bmp` फ़ाइल की ओर इंगित करें और बाकी कोड समान रहता है। + +### 6.2 यदि इमेज लो‑रेज़ोल्यूशन है तो क्या करें? + +OCR की सटीकता 300 dpi से नीचे बहुत घट जाती है। एक त्वरित समाधान है कि इंजन को फीड करने से पहले `Graphics` के साथ इमेज को अपस्केल करें: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 क्या मुझे Aspose.OCR के लिए लाइसेंस चाहिए? + +Aspose एक वॉटरमार्क के साथ मुफ्त ट्रायल देता है। प्रोडक्शन उपयोग के लिए, लाइसेंस खरीदें और जोड़ें: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +## पूर्ण कार्यशील उदाहरण + +नीचे एक पूर्ण, तैयार‑चलाने योग्य कंसोल एप्लिकेशन है जो **how to OCR image**, **load image for OCR**, और **convert jpg to text** को एक साफ़ पैकेज में दर्शाता है। + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**इसे कैसे चलाएँ** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +आपको कंसोल में निकाला गया टेक्स्ट प्रिंट होता दिखेगा, जो पुष्टि करता है कि आपने सफलतापूर्वक C# का उपयोग करके **extract text from image** किया है। + +## सामान्य समस्याएँ एवं प्रो टिप्स + +| समस्या | क्यों होता है | समाधान | +|-------|----------------|-----| +| खाली आउटपुट | इमेज बहुत डार्क या कम कॉन्ट्रास्ट है। | `Bitmap` के साथ प्री‑प्रोसेस करके ब्राइटनेस बढ़ाएँ। | +| गलत भाषा | `Language` प्रॉपर्टी डिफ़ॉल्ट इंग्लिश पर रही। | `ocrEngine.Language = OcrLanguage.Ukrainian;` (या आपका लक्ष्य) स्पष्ट रूप से सेट करें। | +| आउट‑ऑफ़‑मेमोरी त्रुटि | बड़ी इमेजेज को बिना डिस्पोज़ किए लोड किया गया। | `Image.FromFile` को `using` ब्लॉक में रैप करें (जैसा दिखाया गया है)। | +| लाइसेंस वॉटरमार्क | लाइसेंस के बिना ट्रायल पर चल रहा है। | `Main` में जल्दी एक खरीदा हुआ लाइसेंस लागू करें। | + +## निष्कर्ष + +हमने अभी-अभी वह सब कुछ कवर किया है जो आपको C# में **extract text from image** करने के लिए चाहिए—Aspose.OCR इंस्टॉल करने से लेकर **loading image for OCR**, और **convert jpg to text** तक, साथ ही बहुभाषी परिदृश्यों को संभालना। पूर्ण सैंपल प्रोग्राम सभी हिस्सों को जोड़ता है, जिससे आपको किसी भी OCR‑संबंधित प्रोजेक्ट के लिए एक विश्वसनीय आधार मिलता है। + +आगे, आप निम्नलिखित का अन्वेषण कर सकते हैं: + +* फ़ाइलों के बजाय **how to OCR image** स्ट्रीम्स ( `MemoryStream` का उपयोग करें)। +* **c# image to text** पोस्ट‑प्रोसेसिंग जैसे स्पेल‑चेकिंग जोड़ना। +* OCR चरण को बड़े पाइपलाइन में इंटीग्रेट करना (जैसे, परिणाम को डेटाबेस में स्टोर करना)। + +विभिन्न भाषाओं, इमेज फ़ॉर्मैट्स, और प्री‑प्रोसेसिंग ट्रिक्स के साथ प्रयोग करने में संकोच न करें। OCR विज्ञान जितना ही कला है, और जितना अधिक आप प्रयोग करेंगे, परिणाम उतने ही बेहतर होंगे। + +कोडिंग का आनंद लें, और आपकी इमेजेस हमेशा पढ़ने योग्य रहें! + +## संबंधित ट्यूटोरियल + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ C# में इमेज टेक्स्ट निकालें](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [इमेज से टेक्स्ट निकालें – .NET के लिए Aspose.OCR के साथ OCR ऑप्टिमाइज़ेशन](/ocr/english/net/ocr-optimization/) +- [OCR में रेक्टेंगल तैयार करके इमेज से टेक्स्ट कैसे निकालें](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/hindi/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..de01c0ae7 --- /dev/null +++ b/ocr/hindi/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-05-25 +description: C# में OCR का उपयोग करके इमेज फ़ाइलों से टेक्स्ट निकालने का तरीका। Aspose.OCR + का उपयोग करके JPG से चीनी अक्षरों को पहचानना सीखें, कुछ सरल चरणों में। +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: hi +og_description: C# में OCR का उपयोग करके इमेज फ़ाइलों से टेक्स्ट निकालने का तरीका। + यह गाइड आपको Aspose.OCR का उपयोग करके JPG से चीनी अक्षरों को पहचानने का तरीका दिखाता + है। +og_title: C# में OCR का उपयोग कैसे करें – JPG से चीनी टेक्स्ट को पहचानें +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: C# में OCR कैसे उपयोग करें – JPG से चीनी टेक्स्ट पहचानें +url: /hi/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में OCR का उपयोग कैसे करें – JPG से चीनी टेक्स्ट पहचानें + +क्या आपने कभी सोचा है **how to use OCR** को अपने फोन से ली गई तस्वीर से शब्द निकालने के लिए? आप अकेले नहीं हैं। कई वास्तविक‑दुनिया प्रोजेक्ट्स में—जैसे रसीद स्कैनर, अनुवाद ऐप्स, या स्वचालित डेटा एंट्री—आपको **extract text from image** फ़ाइलों को तेज़ी और भरोसेमंद तरीके से निकालना होगा। + +इस ट्यूटोरियल में हम एक पूर्ण, चलाने योग्य उदाहरण के माध्यम से चलेंगे जो **recognizes text from JPG** फ़ाइलों को पहचानता है और यहाँ तक कि **recognize Chinese characters** की जटिल स्थिति को **OCR Chinese Simplified** भाषा पैक का उपयोग करके संभालता है। अंत तक, आपके पास एक स्व-निहित कंसोल ऐप होगा जो पता लगाए गए स्ट्रिंग को कंसोल में प्रिंट करेगा, बिना किसी अतिरिक्त मैन्युअल डाउनलोड की आवश्यकता के। + +> **Quick note:** कोड Aspose.OCR ≥ 23.7 के साथ काम करता है, जो पहली बार उपयोग पर स्वचालित रूप से भाषा संसाधन लाता है। यदि आप पुराने संस्करण पर हैं, तो आपको भाषा को मैन्युअली जोड़ना होगा। + +## आवश्यकताएँ + +- .NET 6.0 SDK या बाद का (उदाहरण .NET 6 को टार्गेट करता है, लेकिन .NET 5 भी काम करता है) +- Visual Studio 2022 या VS Code का नवीनतम संस्करण C# एक्सटेंशन के साथ +- पहले भाषा डाउनलोड के लिए इंटरनेट कनेक्शन +- एक JPG इमेज जिसमें Simplified Chinese टेक्स्ट हो (हम इसे `chinese_sign.jpg` कहेंगे) + +बस इतना ही—कोई भारी OCR इंजन नहीं, कोई नेटिव DLL जुगलबंदी नहीं। बस कुछ NuGet कमांड्स और कुछ कोड की पंक्तियाँ। + +## चरण 1: NuGet के माध्यम से Aspose.OCR स्थापित करें + +सबसे पहले: हमें OCR लाइब्रेरी चाहिए। अपने प्रोजेक्ट फ़ोल्डर में टर्मिनल खोलें और चलाएँ: + +```bash +dotnet add package Aspose.OCR +``` + +या, यदि आप Visual Studio UI पसंद करते हैं, तो **Dependencies → Manage NuGet Packages** पर राइट‑क्लिक करें, “Aspose.OCR” खोजें, और **Install** पर क्लिक करें। + +> **Pro tip:** अपने पैकेजों को अपडेट रखें। नए भाषा पैक और प्रदर्शन सुधार हर माइनर रिलीज़ में आते हैं। + +## चरण 2: नया कंसोल प्रोजेक्ट बनाएं (यदि आपने अभी तक नहीं बनाया है) + +यदि आप शुरू से शुरू कर रहे हैं, तो एक नया कंसोल ऐप बनाएं: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +अब आपके पास OCR कोड के लिए तैयार `Program.cs` फ़ाइल है। + +## चरण 3: OCR कोड लिखें – JPG से Simplified Chinese पहचानें + +`Program.cs` खोलें और इसकी सामग्री को नीचे दिए गए कोड से बदलें। प्रत्येक पंक्ति में टिप्पणी है ताकि आप देख सकें *क्यों* हम यह कदम उठा रहे हैं, न कि केवल *क्या* कर रहे हैं। + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### पीछे क्या हो रहा है? + +- **`OcrEngine.Language`** Aspose को बताता है कि कौन सा शब्दकोश उपयोग करना है। `ChineseSimplified` चुनकर, हम इंजन को Simplified Chinese भाषा पैक खोजने के लिए निर्देशित करते हैं। +- **First‑time download**: जब `Recognize` चलता है, SDK Aspose के CDN से जुड़ता है, ≈6 MB भाषा फ़ाइल को डाउनलोड करता है, इसे स्थानीय रूप से कैश करता है, और फिर OCR जारी रखता है। बाद के कॉल तुरंत होते हैं। +- **`Image.FromFile`** किसी भी रास्टर फ़ॉर्मेट के साथ काम करता है जिसे .NET डिकोड कर सकता है—JPG, PNG, BMP—इसलिए आप कई प्रकार की **extract text from image** फ़ाइलों से टेक्स्ट निकाल सकते हैं, केवल JPG नहीं। + +## चरण 4: एप्लिकेशन चलाएँ और आउटपुट सत्यापित करें + +बिल्ड करें और चलाएँ: + +```bash +dotnet run +``` + +आपको कुछ इस तरह दिखना चाहिए: + +``` +=== Recognized Text === +欢迎光临 +``` + +यदि कंसोल गिबरिश या खाली स्ट्रिंग प्रिंट करता है, तो दोबारा जाँचें कि: + +1. इमेज में वास्तव में स्पष्ट, हाई‑कॉन्ट्रास्ट चीनी अक्षर हों। +2. फ़ाइल पाथ सही हो (कोई अतिरिक्त स्पेस या गायब एक्सटेंशन न हो)। +3. आपका मशीन `https://download.aspose.com` तक पहुँच सकता हो भाषा पैक के लिए। + +## चरण 5: किनारे के मामलों और सामान्य समस्याओं को संभालना + +### 5.1 कम‑गुणवत्ता वाली इमेजेस से निपटना + +जब स्रोत इमेज ब्लरी, शोरयुक्त, या खराब लाइटिंग वाली होती है तो OCR की सटीकता घटती है। एक त्वरित समाधान है इमेज को प्री‑प्रोसेस करना: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 हेडलेस एनवायरनमेंट में चलाना + +यदि आप GUI के बिना Linux कंटेनर में डिप्लॉय कर रहे हैं, तो सुनिश्चित करें कि `libgdiplus` लाइब्रेरी (`System.Drawing` के लिए आवश्यक) स्थापित है: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 भाषा पैक को मैन्युअली कैश करना + +आप भाषा फ़ाइल को एक बार डाउनलोड कर सकते हैं और Aspose को `License` API के माध्यम से उस पर पॉइंट कर सकते हैं, जिससे एक‑बार नेटवर्क कॉल समाप्त हो जाती है। यह ऑफ़लाइन परिदृश्यों के लिए उपयोगी है। + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## पूर्ण कार्यशील उदाहरण (ऑल‑इन‑वन) + +नीचे *पूर्ण* प्रोग्राम है जिसे आप `Program.cs` में कॉपी‑पेस्ट कर सकते हैं। कोई छिपे हुए हिस्से नहीं, कोई बाहरी स्क्रिप्ट नहीं। + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### अपेक्षित आउटपुट + +यदि JPG में वाक्यांश “欢迎光临” है, तो कंसोल प्रिंट करेगा: + +``` +=== Recognized Text === +欢迎光临 +``` + +इमेज को किसी भी अन्य Simplified Chinese साइन, सड़क नाम, या प्रोडक्ट लेबल से बदलने में संकोच न करें—इंजन अपनी पूरी कोशिश करेगा। + +## निष्कर्ष + +हमने अभी **how to use OCR** को C# में **extract text from image** फ़ाइलों से निकालने के लिए कवर किया है, विशेष रूप से **recognize Chinese characters** को **JPG** में संभालते हुए। Aspose.OCR की ऑन‑द‑फ्लाई भाषा डाउनलोड का उपयोग करके, आप अपने डिप्लॉयमेंट को हल्का रख सकते हैं जबकि **OCR Chinese Simplified** को बॉक्स से ही सपोर्ट कर सकते हैं। + +अगला क्या? इन विचारों को आज़माएँ: + +- **Batch processing**: इमेजेस के फ़ोल्डर पर लूप चलाएँ और प्रत्येक परिणाम को CSV में लिखें। +- **Combine with translation APIs**: पहचाने गए स्ट्रिंग को Azure Translator में फीड करें रियल‑टाइम मल्टीलेंग्वेज़ ऐप्स के लिए। +- **Explore other languages**: `OcrLanguage.ChineseSimplified` को `Japanese` या `Arabic` से बदलें और देखें कि वही कोड कैसे अनुकूलित होता है। + +परफ़ॉर्मेंस ट्यूनिंग, लाइसेंसिंग, या OCR को वेब सर्विस में इंटीग्रेट करने के बारे में सवाल हैं? नीचे कमेंट करें—हैप्पी कोडिंग! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + +## संबंधित ट्यूटोरियल्स + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ इमेज टेक्स्ट निकालें C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [कई भाषाओं के लिए Aspose OCR के साथ टेक्स्ट इमेज पहचानें](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [OCR में रेक्टेंगल तैयार करके इमेज से टेक्स्ट निकालने का तरीका](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hindi/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/hindi/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..20be59a85 --- /dev/null +++ b/ocr/hindi/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: C# में रूसी टेक्स्ट को OCR करने और Aspose OCR के साथ इमेज से टेक्स्ट + निकालना सीखें। तेज़ी से इमेज को टेक्स्ट में बदलने के लिए चरण‑दर‑चरण कोड। +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: hi +og_description: C# में रूसी टेक्स्ट OCR को आसान बनाएं। इमेज से टेक्स्ट निकालना, इमेज + को टेक्स्ट में बदलना C# में सीखें, और Aspose OCR के साथ OCR के लिए इमेज लोड करें। +og_title: C# में रूसी टेक्स्ट OCR – पूर्ण Aspose OCR गाइड +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: C# में रूसी टेक्स्ट का OCR – Aspose OCR का उपयोग करके पूर्ण गाइड +url: /hi/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# में रूसी टेक्स्ट OCR – Aspose OCR का उपयोग करके पूर्ण गाइड + +क्या आपको कभी C# में रूसी टेक्स्ट OCR करने की ज़रूरत पड़ी, लेकिन यह नहीं पता था कि किस लाइब्रेरी पर भरोसा किया जाए? आप अकेले नहीं हैं। सायरिलिक इमेज से साफ़, पढ़ने योग्य अक्षर निकालना ऐसे लगता है जैसे गुप्त संदेशों को डिकोड करना—ख़ासकर जब सही भाषा मॉडल सेट न किया हो। + +इस ट्यूटोरियल में हम एक व्यावहारिक उदाहरण के माध्यम से दिखाएंगे कि **इमेज से टेक्स्ट निकालना** कैसे किया जाता है, *इमेज‑टू‑टेक्स्ट C#* शैली में कैसे बदलते हैं, और Aspose OCR के साथ रूसी भाषा पहचान की बारीकियों को कैसे संभालते हैं। अंत तक आपके पास एक तैयार‑चलाने‑योग्य कंसोल ऐप होगा जो OCR के लिए इमेज लोड करता है, पहचाने गए स्ट्रिंग को प्रिंट करता है, और अधिक उन्नत परिदृश्यों के लिए एक ठोस आधार प्रदान करता है। + +## आप क्या सीखेंगे + +- **Aspose OCR C#** को रूसी भाषा समर्थन के लिए कैसे इंस्टॉल और कॉन्फ़िगर करें। +- OCR के लिए **इमेज लोड करने** और इंजन को कॉल करने के सटीक चरण। +- सामान्य समस्याओं जैसे भाषा रिसोर्स की कमी या धुंधली स्कैन को कैसे संभालें। +- समाधान को विस्तारित करने के तरीके, जैसे कई फ़ाइलों की बैच प्रोसेसिंग या कॉन्फिडेंस थ्रेशोल्ड को ट्यून करना। + +Aspose का कोई पूर्व अनुभव आवश्यक नहीं है; बस C# और .NET की बुनियादी समझ हो तो आप शुरू कर सकते हैं। + +## आवश्यकताएँ + +शुरू करने से पहले सुनिश्चित करें कि आपके पास निम्नलिखित हैं: + +1. **.NET 6.0** (या बाद का) SDK स्थापित हो – कोड .NET Core और .NET Framework दोनों पर काम करता है। +2. **Visual Studio 2022** (या आपका पसंदीदा कोई IDE)। +3. एक **Aspose.OCR for .NET** NuGet पैकेज – आप Aspose वेबसाइट से मुफ्त ट्रायल की प्राप्त कर सकते हैं। +4. एक **Russian language model** फ़ाइल (`rus.traineddata`) – इसे Aspose रिसोर्स पेज से डाउनलोड करें और बाद में संदर्भित करने के लिए किसी फ़ोल्डर में रखें। +5. एक सैंपल इमेज (`russian_doc.png`) जिसमें स्पष्ट सायरिलिक टेक्स्ट हो। + +सब कुछ तैयार है? बढ़िया—चलिए शुरू करते हैं। + +## चरण 1: प्रोजेक्ट सेट अप करें और Aspose OCR इंस्टॉल करें + +पहले, एक नया कंसोल प्रोजेक्ट बनाएं: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +अब Aspose OCR पैकेज जोड़ें: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** यदि आप ट्रायल लाइसेंस उपयोग कर रहे हैं, तो `Aspose.Total.lic` फ़ाइल को हाथ में रखें; आप इसे कोड में लोड करेंगे ताकि वॉटरमार्क न दिखे। + +पैकेज इंस्टॉल हो जाने के बाद, `Program.cs` खोलें। आपको डिफ़ॉल्ट `Main` मेथड दिखेगा—इसकी सामग्री को उस स्केलेटन से बदल दें जिसे हम आगे बनाएँगे। + +## चरण 2: रूसी भाषा के लिए OCR इंजन कॉन्फ़िगर करें + +ऑपरेशन का दिल `OcrEngine` ऑब्जेक्ट है। हमें इसे दो बातें बतानी हैं: कौन सी भाषा पहचाननी है और भाषा मॉडल फ़ाइलें कहाँ स्थित हैं। + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Why this matters:** यदि आप `Language = OcrLanguage.Russian` सेट करना छोड़ देते हैं, तो इंजन डिफ़ॉल्ट रूप से अंग्रेज़ी उपयोग करेगा, और सभी सायरिलिक अक्षर गड़बड़ प्रतीकों की तरह दिखेंगे। `ResourceFolder` वह डायरेक्टरी दर्शाता है जिसमें `rus.traineddata` फ़ाइल रखी है; इसके बिना Aspose *resource not found* एक्सेप्शन फेंकेगा। + +## चरण 3: OCR के लिए इमेज लोड करें + +अब हमें **OCR के लिए इमेज लोड** करनी है। Aspose OCR `System.Drawing.Image` के साथ काम करता है, इसलिए आप कोई भी समर्थित फ़ॉर्मेट (PNG, JPEG, BMP, आदि) पास कर सकते हैं। फ़ाइल पाथ सही रखें; रिलेटिव पाथ ठीक है जब आप इमेज को एक्सीक्यूटेबल के पास रखें। + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** यदि इमेज बहुत बड़ी है (5 MB से अधिक) तो पहले उसे डाउनस्केल करना बेहतर होगा। DPI बहुत कम होने पर OCR की सटीकता घटती है, लेकिन बहुत बड़े फ़ाइलों से मेमोरी पर दबाव पड़ सकता है। आवश्यक होने पर `Graphics` का उपयोग करके जल्दी से रीसाइज़ किया जा सकता है। + +## चरण 4: टेक्स्ट पहचानें – इमेज‑टू‑टेक्स्ट C# शैली + +इंजन कॉन्फ़िगर हो गया और इमेज लोड हो गई, अब वास्तविक पहचान एक ही कॉल में होती है: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +जब आप प्रोग्राम चलाएँ (`dotnet run`), तो आपको कुछ इस तरह दिखना चाहिए: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +यदि आउटपुट गड़बड़ दिखे, तो दोबारा जाँचें कि: + +- `rus.traineddata` फ़ाइल `ResourceFolder` में मौजूद है। +- इमेज बहुत धुंधली नहीं है; OCR से पहले एक साधा बाइनराइज़ेशन फ़िल्टर लागू करने पर विचार करें। +- भाषा सेटिंग वास्तव में `OcrLanguage.Russian` है। + +## चरण 5: फाइन‑ट्यूनिंग और सामान्य समस्याएँ + +### कॉन्फिडेंस थ्रेशोल्ड समायोजित करना + +Aspose OCR प्रत्येक अक्षर के लिए आंतरिक रूप से एक कॉन्फिडेंस वैल्यू लौटाता है। जबकि API इसे सीधे एक्सपोज़ नहीं करती, आप **डिटेल्ड आउटपुट** सक्षम करके देख सकते हैं कि कौन से शब्द कम कॉन्फिडेंस वाले हैं: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +यदि आप बार‑बार गलत पहचान देखते हैं, तो प्रयास करें: + +- **प्रि‑प्रोसेसिंग**: इमेज को ग्रेस्केल में बदलें, कॉन्ट्रास्ट बढ़ाएँ, या मीडियन फ़िल्टर लागू करें। +- **DPI सेटिंग्स**: सायरिलिक स्क्रिप्ट के लिए इमेज कम से कम 300 DPI की होनी चाहिए। + +### कई इमेज की बैच प्रोसेसिंग + +यदि आपको **इमेज से टेक्स्ट निकालना** फ़ाइलों में बड़े पैमाने पर करना है, तो पहचान लॉजिक को लूप में रखें: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +अब प्रत्येक PNG का अपना `.txt` समकक्ष बन जाएगा—डॉक्यूमेंट आर्काइविंग के लिए उपयोगी। + +### यूनिकोड आउटपुट को संभालना + +सायरिलिक अक्षर यूनिकोड हैं, इसलिए सुनिश्चित करें कि आपका कंसोल एन्कोडिंग उन्हें दिखा सके: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +यह लाइन `Main` मेथड शुरू होते ही रखें। इसके बिना आप रूसी अक्षरों के बजाय प्रश्नचिन्ह (`?`) देख सकते हैं। + +## पूर्ण कार्यशील उदाहरण + +नीचे पूरा, तैयार‑चलाने‑योग्य कोड दिया गया है। इसे `Program.cs` में कॉपी‑पेस्ट करें, पाथ्स को समायोजित करें, और आप तैयार हैं। + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**अपेक्षित आउटपुट** (मान लेते हैं सैंपल इमेज में लिखा है “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +यदि कुछ और दिखे, तो चरण 5 में दिए गए ट्रबलशूटिंग टिप्स को फिर से देखें। + +## निष्कर्ष + +अब आपके पास Aspose OCR का उपयोग करके C# में **ocr russian text** करने का एक ठोस, एंड‑टू‑एंड उदाहरण है। लाइब्रेरी इंस्टॉल करने से लेकर रूसी भाषा मॉडल कॉन्फ़िगर करने, इमेज लोड करने और उसे साफ़ यूनिकोड टेक्स्ट में बदलने तक, हर पहलू कवर किया गया है। + +याद रखें, विश्वसनीय OCR की कुंजी है अच्छा स्रोत सामग्री: स्पष्ट फ़ॉन्ट, पर्याप्त DPI, और सही भाषा रिसोर्सेज। बुनियादी बातों में महारत हासिल करने के बाद आप बैच प्रोसेसिंग, क्लाउड स्टोरेज के साथ इंटीग्रेशन, या यहाँ तक कि AI पोस्ट‑प्रोसेसिंग के साथ स्पेल‑चेकिंग भी जोड़ सकते हैं। + +### आगे क्या? + +- **aspose ocr c#** के उन्नत विकल्पों जैसे लेआउट एनालिसिस या PDF आउटपुट का अन्वेषण करें। +- इसे **extract text from image** वर्कफ़्लो के साथ Azure Functions में सर्वरलेस प्रोसेसिंग के लिए जोड़ें। +- विभिन्न भाषाओं को आज़माएँ—सिर्फ `OcrLanguage.Russian` को `OcrLanguage.English` या किसी अन्य समर्थित कोड में बदलें। + +कोई सवाल या ऐसी इमेज जो सहयोग नहीं कर रही हो? नीचे कमेंट करें, और हैप्पी कोडिंग! + +![ocr रूसी टेक्स्ट उदाहरण](ocr-russian-example.png){alt="ocr रूसी टेक्स्ट उदाहरण"} + +## संबंधित ट्यूटोरियल + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/hindi/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..7fc12c319 --- /dev/null +++ b/ocr/hindi/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-25 +description: C# में Aspose OCR का उपयोग करके छवि से टेक्स्ट पहचानें। जानें कि OCR + के लिए छवि कैसे लोड करें, OCR भाषा कैसे सेट करें, OCR इंजन कैसे बनाएं और TIFF से + टेक्स्ट कैसे निकालें। +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: hi +og_description: C# में Aspose OCR का उपयोग करके छवि से टेक्स्ट पहचानें। यह ट्यूटोरियल + दिखाता है कि OCR इंजन कैसे बनाएं, OCR के लिए छवि लोड करें, OCR भाषा सेट करें, और + TIFF से टेक्स्ट निकालें। +og_title: Aspose OCR के साथ छवि से टेक्स्ट पहचानें – पूर्ण C# गाइड +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Aspose OCR के साथ छवि से टेक्स्ट पहचानें – पूर्ण C# गाइड +url: /hi/net/text-recognition/recognize-text-from-image-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 – पूर्ण C# गाइड + +क्या आपको कभी **इमेज से टेक्स्ट पहचानने** की जरूरत पड़ी लेकिन यह नहीं पता था कि कौन‑सी लाइब्रेरी आपको गति और सटीकता दोनों देगी? आप अकेले नहीं हैं। कई इनवॉइस‑प्रोसेसिंग या अभिलेखीय प्रोजेक्ट्स में सबसे बड़ी समस्या यह है कि TIFF फ़ाइलों से साफ़, खोज योग्य टेक्स्ट प्राप्त करना बिना कस्टम पार्सर लिखे। + +असल बात यह है: Aspose OCR for .NET इस पूरी पाइपलाइन को आसान बना देता है। इस गाइड में हम सब कुछ कवर करेंगे—पैकेज इंस्टॉल करना, **OCR इंजन बनाना**, TIFF लोड करना, OCR भाषा सेट करना, और अंत में **TIFF से टेक्स्ट निकालना**। अंत तक आपके पास एक तैयार‑चलाने‑योग्य कंसोल एप्लिकेशन होगा जो **इमेज फ़ाइलों से टेक्स्ट जल्दी‑से‑पहचान** सकता है। + +## Prerequisites + +- .NET 6.0 या बाद का (कोड .NET Core और .NET Framework के साथ भी काम करता है) +- Visual Studio 2022 (या कोई भी IDE जो आप पसंद करते हैं) +- Aspose.OCR NuGet पैकेज (GPU समर्थन के लिए `Aspose.OCR.Gpu` ऐड‑ऑन आवश्यक है) +- एक GPU जिसमें CUDA समर्थन हो यदि आप अतिरिक्त गति चाहते हैं (वैकल्पिक लेकिन अनुशंसित) + +> **Pro tip:** यदि आपके पास GPU नहीं है, तो बस `GpuDevice` लाइन को हटा दें और इंजन स्वचालित रूप से CPU पर फ़ॉल्बैक हो जाएगा। + +## Step 1: Install Aspose OCR and Create OCR Engine + +सबसे पहले, NuGet के माध्यम से आवश्यक पैकेज जोड़ें: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +अब हम **OCR इंजन बना** सकते हैं। यह ऑब्जेक्ट प्रोसेस का हृदय है; यह डिवाइस चयन और मेमोरी लिमिट जैसी कॉन्फ़िगरेशन रखता है। + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**क्यों महत्वपूर्ण है:** इंजन को GPU से बाइंड करने से आप **इमेज से टेक्स्ट पहचानने** में लगने वाला समय बहुत घटा देते हैं, विशेषकर बड़े बैच हाई‑रिज़ॉल्यूशन TIFF फ़ाइलों के लिए। + +## Step 2: Load Image for OCR + +अब हमें **OCR के लिए इमेज लोड** करनी है। Aspose.OCR `System.Drawing.Image` के साथ काम करता है, इसलिए GDI+ द्वारा समर्थित कोई भी फ़ॉर्मेट (मल्टी‑पेज TIFF सहित) ठीक रहेगा। + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +यदि आप मल्टी‑पेज TIFF के साथ काम कर रहे हैं तो `image.SelectActiveFrame` का उपयोग करके पेजों पर लूप कर सकते हैं, लेकिन अधिकांश मामलों में एक ही कॉल पर्याप्त है। + +## Step 3: Set OCR Language + +इंजन जादू से नहीं जानता कि आप कौन‑सी भाषा स्कैन कर रहे हैं। **OCR भाषा सेट** करें इससे पहले कि आप रिकग्नाइज़र चलाएँ; अन्यथा आपको बहुत गड़बड़ आउटपुट मिलेगा। + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **क्या आप जानते हैं?** रन‑टाइम पर भाषा बदलना सस्ता है—आप पेजों के बीच इस प्रॉपर्टी को बदलकर मिश्रित‑भाषा दस्तावेज़ भी प्रोसेस कर सकते हैं। + +## Step 4: Perform the Recognition – Recognize Text from Image + +अब मज़ेदार हिस्सा: वास्तव में **इमेज से टेक्स्ट पहचानना**। `Recognize` मेथड सभी पहचाने गए अक्षरों के साथ एक साधारण स्ट्रिंग लौटाता है। + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +यदि आपको कॉन्फिडेंस स्कोर या बाउंडिंग बॉक्स चाहिए तो आप ओवरलोड का उपयोग कर सकते हैं जो `OcrResult` ऑब्जेक्ट लौटाता है, लेकिन अधिकांश एक्सट्रैक्शन टास्क के लिए साधारण स्ट्रिंग पर्याप्त है। + +## Step 5: Extract Text from TIFF (and handle multi‑page files) + +जब स्रोत एक कई पेज वाला TIFF हो, तो आपको प्रत्येक फ्रेम के लिए स्टेप 2‑4 दोहराने होंगे। यहाँ एक त्वरित लूप है जो **TIFF से टेक्स्ट निकालता** है, पेज‑दर‑पेज: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +ऊपर दिया गया कोड हर पेज के लिए निकाला गया टेक्स्ट प्रिंट करता है, जिससे परिणाम को डेटाबेस या सर्च इंडेक्स में पाइप करना बहुत आसान हो जाता है। + +## Step 6: Display or Persist the Extracted Text + +अंत में, चलिए **निकाले गए टेक्स्ट को दिखाते** हैं और वैकल्पिक रूप से बाद में प्रोसेसिंग के लिए फ़ाइल में लिखते हैं। + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +प्रोग्राम चलाने पर पहचान किए गए अक्षर आउटपुट होंगे और आपके स्रोत TIFF के बगल में `extracted_text.txt` बन जाएगा। + +--- + +## Common Questions & Edge Cases + +- **अगर मेरा GPU पहचान नहीं रहा है तो?** + `GpuDevice` लाइन को हटा दें; इंजन स्वचालित रूप से CPU मोड में स्विच हो जाएगा। प्रदर्शन धीमा होगा लेकिन परिणाम सटीक रहेंगे। + +- **क्या मैं PNG या JPEG फ़ाइलें प्रोसेस कर सकता हूँ?** + बिल्कुल—`Image.FromFile` System.Drawing द्वारा समर्थित किसी भी फ़ॉर्मेट के साथ काम करता है, इसलिए आप **OCR के लिए इमेज लोड** कर सकते हैं चाहे एक्सटेंशन कुछ भी हो। + +- **लो‑रिज़ॉल्यूशन स्कैन को कैसे हैंडल करें?** + `Recognize` कॉल करने से पहले `ocrEngine.PreprocessOptions.Dpi` को बढ़ाएँ। उच्च DPI इंजन को अधिक पिक्सेल देता है, जिससे सटीकता बढ़ती है। + +- **TIFF का आकार सीमित है क्या?** + `GpuMemoryLimit` प्रॉपर्टी GPU उपयोग को सीमित करती है। यदि आप सीमा तक पहुँच जाते हैं, तो इंजन शेष पेजों के लिए CPU पर फ़ॉल्बैक हो जाएगा। + +## Conclusion + +अब आपके पास एक पूर्ण, प्रोडक्शन‑रेडी स्निपेट है जो Aspose OCR का उपयोग करके C# में **इमेज फ़ाइलों से टेक्स्ट पहचानता** है। ट्यूटोरियल ने बताया कि कैसे **OCR इंजन बनाना**, **OCR के लिए इमेज लोड करना**, **OCR भाषा सेट करना**, और **TIFF से टेक्स्ट निकालना**—सभी GPU एक्सेलेरेशन के साथ गति बढ़ाने के लिए। + +अब आप कर सकते हैं: + +- विभिन्न भाषाओं के साथ प्रयोग करें (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, आदि)। +- आउटपुट को एक खोज योग्य ElasticSearch इंडेक्स में एकीकृत करें। +- डेटा गुणवत्ता सुधारने के लिए पोस्ट‑प्रोसेसिंग (स्पेल‑चेक, रेगेक्स क्लीनअप) जोड़ें। + +अपने इनवॉइस बैच पर इसे आज़माएँ, मेमोरी लिमिट को ट्यून करें, और OCR प्रदर्शन को आसमान छूते देखें। Happy coding! + +## Related Tutorials + +- [Aspose.OCR का उपयोग करके भाषा चयन के साथ C# में इमेज टेक्स्ट निकालें](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [OCR में रेक्टेंगल तैयार करके इमेज से टेक्स्ट निकालने का तरीका](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [इमेज से टेक्स्ट निकालें – Aspose.OCR के साथ लाइन पहचानें](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..10a6d5cce 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# 中建立 OCR 引擎 – 完整指南](./create-ocr-engine-in-c-complete-guide/) +一步步教您在 C# 中建立完整的 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/hongkong/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..21a3ac24d --- /dev/null +++ b/ocr/hongkong/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-25 +description: 在 C# 中建立 OCR 引擎,並學習如何在幾行程式碼內檢查其評估模式與授權狀態。 +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: zh-hant +og_description: 在 C# 中建立 OCR 引擎,即時查看如何偵測評估模式並顯示授權狀態。 +og_title: 使用 C# 建立 OCR 引擎 – 步驟指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: 使用 C# 建立 OCR 引擎 – 完整指南 +url: /zh-hant/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中建立 OCR 引擎 – 完整指南 + +有沒有想過如何在 C# 中 **create OCR engine** 物件,而不必在大量文件中搜尋?你並不是唯一有此困擾的人。許多開發者在需要啟動 OCR 引擎、驗證它是否處於試用模式,以及向使用者顯示授權狀態時,常會卡住。 + +在本教學中,我們將逐步說明一個簡潔、端對端的範例,**creates an OCR engine**、檢查其 **OCR engine evaluation mode**,並印出關於授權狀態的友善訊息。完成後,你將擁有一個可直接執行的主控台應用程式,並對在自己的專案中處理 OCR 授權有清晰的概念。 + +## 你將學會 + +- 如何實例化 `OcrEngine`(任何 OCR 工作流程的核心)。 +- 為何偵測 **evaluation mode** 對合規性與使用者體驗很重要。 +- 檢查 **check OCR license** 狀態的最佳方式,並對異常狀態作出回應。 +- 常見陷阱——null 參考、例外處理與版本不匹配。 + +除了已安裝的 OCR SDK,無需其他外部工具。只要你熟悉基本的 C# 語法,即可開始。 + +## 前置條件 + +- .NET 6.0 或更新版本(程式碼可在 .NET Core 與 .NET Framework 上編譯)。 +- 具備 `OcrEngine` 類別且提供 `IsEvaluation` 屬性的 OCR SDK(例如假設的 `MyOcrSdk`)。 +- 文字編輯器或 IDE(Visual Studio、VS Code、Rider—自行選擇)。 + +就這樣。讓我們開始吧。 + +## 步驟 1:建立新主控台專案 + +首先,建立一個全新的主控台應用程式,以便在獨立環境中執行程式碼。 + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +開啟產生的 `Program.cs`。我們將其內容取代為一個完整範例,**creates OCR engine** 實例並處理授權。 + +## 步驟 2:匯入 OCR SDK 命名空間 + +假設 SDK 已透過 NuGet 參考(`MyOcrSdk` 為佔位符),在檔案頂部加入 using 指令。 + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +如果尚未加入套件,請執行: + +```bash +dotnet add package MyOcrSdk +``` + +> **專業提示:** 請保持 SDK 版本為最新;較新的發行版通常會改善 evaluation‑mode 偵測。 + +## 步驟 3:建立 OCR 引擎實例 + +現在我們終於 **create OCR engine** 物件。這是任何 OCR 工作流程的核心——可視為稍後讀取影像的大腦。 + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +為何此步驟關鍵?`OcrEngine` 封裝了所有設定、語言套件與授權資料。若沒有它,就無法處理影像或查詢 evaluation 標誌。 + +> **旁註:** 某些 SDK 允許在建構子傳入設定物件(例如語言、DPI)。若需要自訂設定,請相應修改此行。 + +## 步驟 4:判斷 OCR 引擎的 Evaluation Mode + +大多數 OCR 廠商提供的試用版會在 **evaluation mode** 下執行,直至提供有效的授權金鑰。了解是否處於試用模式,可讓你顯示相應的 UI 提示或限制特定功能。 + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation` 屬性在引擎未授權或使用時間限制的試用版時會回傳 `true`。這是一個快速且可靠的方式來保護高級功能。 + +### 若屬性不存在該怎麼辦? + +較舊的 SDK 版本可能改以 `GetLicenseInfo()` 方法提供資訊。此時,你需要檢查回傳物件中的 `IsTrial` 標誌。升級時務必參考 SDK 的變更紀錄。 + +## 步驟 5:顯示目前的授權狀態 + +最後,讓我們向使用者顯示引擎是已授權還是仍在試用。簡單的 console write‑line 即可達成,但你也可以將其改寫為 GUI 應用程式。 + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +三元運算子讓程式碼保持簡潔,且訊息足夠清晰,適合終端使用者或開發者閱讀日誌。 + +## 完整可執行範例 + +將上述所有步驟整合,以下是一個自包含的程式,你可以直接複製貼上到 `Program.cs`,再以 `dotnet run` 執行。 + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### 預期輸出 + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +若 SDK 拋出例外(例如缺少原生 DLL),catch 區塊會印出有用的錯誤訊息,而不會讓整個應用程式崩潰。 + +## 處理邊緣情況與常見陷阱 + +### 1. Null Engine Instances + +雖然建構子通常會回傳有效物件,但若缺少必要的原生相依性,某些 SDK 可能會回傳 `null`。請做好防護: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. License Expiration While Running + +試用授權可能在執行期間過期。若應用程式長時間運行,請定期重新查詢 `IsEvaluation`。 + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. 不同版本的屬性名稱 + +較舊的版本可能會提供 `engine.EvaluationMode` 或 `engine.License.IsTrial`。升級時,請檢查 SDK 發行說明以找出破壞性變更。 + +### 4. 多執行緒情境 + +如果啟動多個 OCR 工作者,請 **每個執行緒建立一個 OCR engine**,除非 SDK 明確支援執行緒安全的共享。共享單一引擎可能導致競爭條件與錯誤的授權讀取。 + +## 生產環境的專業提示 + +- **Cache the licensing status** 在首次檢查後快取授權狀態,以避免不必要的屬性呼叫。 +- **Log the license key**(遮蔽)於啟動時記錄,以供稽核追蹤——協助支援團隊診斷授權問題。 +- **Provide a UI toggle**,告知使用者目前為試用模式,並提供「購買授權」按鈕。 +- **Automate license renewal**,若 SDK 提供 activation API,請自動化授權續期,以維持順暢的使用者體驗。 + +## 結論 + +我們僅用幾行程式碼 **created OCR engine** 物件,檢查 **OCR engine evaluation mode**,並印出清晰的 **OCR licensing status** 訊息。完整範例即開即用,能優雅地處理錯誤,並說明每一步的「原因」——讓你能將其套用至桌面、Web 或服務端情境。 + +接下來,你可以探索: + +- 將影像餵入 `engine.Recognize`,並處理多語言支援。 +- 使用 **check OCR license** API 以程式方式啟動已購買的金鑰。 +- 結合 UI 框架(WinForms、WPF、MAUI)以顯示授權徽章。 + +試試看這些方法,你就能擁有堅實的 OCR 基礎,隨時應付任何應用程式。祝開發愉快! + +## 相關教學 + +- [如何提取 OCR – OCR 配置](/ocr/english/net/ocr-configuration/) +- [如何使用 Aspose.OCR for .NET 取得 OCR 結果](/ocr/english/net/text-recognition/get-recognition-result/) +- [如何在 .NET 中使用 Aspose.OCR 進行 PDF OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/ocr-optimization/_index.md b/ocr/hongkong/net/ocr-optimization/_index.md index c078585c2..6d17893ac 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 結果儲存為文件。 +### [在 OCR 圖像辨識中前處理圖像 – 完整 Aspose C# 指南](./preprocess-image-for-ocr-complete-aspose-c-guide/) +完整的 C# 教學,說明如何使用 Aspose.OCR 前處理圖像,提升 OCR 準確度與效能。 ## 常見問題 diff --git a/ocr/hongkong/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/hongkong/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..cdd70e01b --- /dev/null +++ b/ocr/hongkong/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: 使用 Aspose 進行圖像預處理以提升 OCR 準確度,並對 JPEG 檔案執行 OCR。學習如何透過 Aspose 以清晰、逐步的教學方式提取文字。 +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: zh-hant +og_description: 使用 Aspose 進行影像前處理以提升 OCR 準確度。遵循本指南,在 JPEG 圖片上執行 OCR,並使用 Aspose 於 C# + 中擷取文字。 +og_title: 預處理圖像以供 OCR – Aspose C# 教學 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: OCR 圖像前處理 – 完整 Aspose C# 指南 +url: /zh-hant/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 圖像前處理以進行 OCR – 完整 Aspose C# 指南 + +有沒有想過如何 **preprocess image for OCR**,讓文字每次都能乾淨地辨識?你並非唯一面對這問題的人——開發者常常要與雜訊掃描、低對比度 JPEG 以及不穩定的光線作戰。好消息是,只要做幾個聰明的調整,就能大幅 **improve OCR accuracy**,而且 Aspose 讓這過程變得輕鬆。 + +在本教學中,我們將逐步示範一個實務範例,說明如何 **run OCR on JPEG** 圖片、套用自訂的影像處理流程,最後 **extract text using Aspose**。完成後,你將擁有一段可直接貼上的 C# 程式碼,隨時可放入任何 .NET 專案。 + +不需要事先具備 Aspose 經驗;只要有基本的 C# 背景與 Visual Studio(或你慣用的 IDE)即可。讓我們開始吧。 + +![OCR 圖像前處理範例](preprocess-ocr.png "OCR 圖像前處理") + +## 步驟 1:設定 Aspose.OCR 引擎 – 圖像前處理以進行 OCR + +首先,我們需要一個 `OcrEngine` 實例,並告訴它預期的語言。大多數情況下預設為英語,但你可以透過更改 `OcrLanguage` 列舉,改成法語、德語等。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Why this matters:** 引擎是整個作業的核心;沒有它就無法套用任何實際 **preprocess image for OCR** 的影像濾鏡。可以把它想像成所有材料混合的廚房。 + +## 步驟 2:建構自訂影像處理流程 – 提升 OCR 準確度 + +現在進入重點。Aspose 允許你串接多個濾鏡。以下我們啟用四個最有效的濾鏡: + +1. **Deskew** – 使傾斜的文件校正(預設最大 5°)。 +2. **Denoise** – 平滑顆粒狀背景。 +3. **Binarize** – 以閾值將影像轉為黑白。 +4. **ContrastBoost** – 讓淡淡的字元更突出。 + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** 若來源影像已相當清晰,你可以降低 `Strength` 或直接關閉某個濾鏡。過度處理可能會抹掉淡字元,因此請以真實樣本多加測試。 + +## 步驟 3:載入 JPEG(或任何影像)並執行 OCR – 在 JPEG 上執行 OCR + +Aspose 支援 .NET 能讀取的任何影像格式——JPEG、PNG、BMP,隨你挑選。以下示範如何將 JPEG 檔案送入引擎,並啟動辨識程序。 + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Why JPEG?** JPEG 壓縮常會產生干擾 OCR 的雜訊。透過我們的前處理流程,特別是去噪與二值化步驟,可減輕這些問題,讓你能自信地 **run OCR on JPEG**。 + +## 步驟 4:輸出辨識文字 – 使用 Aspose 抽取文字 + +最後,我們只需將文字寫入主控台、檔案或任何下游服務。示範用只需輸出到主控台即可。 + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +執行程式後,應會看到類似以下的輸出: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +若輸出呈現亂碼,請回到 **Step 2** 調整濾鏡設定。微小的調整常能在 **improve OCR accuracy** 上帶來顯著提升。 + +## 常見邊緣情況與處理方式 + +| 情況 | 建議調整 | +|-----------|----------------------| +| **非常暗的影像** | 將 `ContrastBoost.Level` 提高至 1.5 或更高。 | +| **傾斜 > 5°** | 將 `DeskewOptions.MaxAngle` 提高(例如 10.0),或手動先旋轉影像。 | +| **彩色文字在彩色背景上** | 使用自訂閾值的 `BinarizeOptions`,或改用 `AdaptiveBinarizeOptions`。 | +| **大型檔案(> 5 MB)** | 先將影像載入 `MemoryStream`,以避免檔案鎖定問題。 | + +這些調整讓你的流程保持彈性且具未來適應性,特別是當你需要從各種來源 **extract text using Aspose** 時。 + +## 完整範例 – 一次呈現全部步驟 + +以下是完整、可直接複製貼上的程式。它可於 .NET 6+ 編譯,且僅需 `Aspose.OCR` NuGet 套件。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +將其儲存為 `Program.cs`,加入 Aspose.OCR 套件(`dotnet add package Aspose.OCR`),然後執行 `dotnet run`。你會在主控台看到已清理的文字。 + +## 重點回顧 – 為何此方法有效 + +- **Preprocess image for OCR**:此流程移除最常見的錯誤來源(傾斜、噪點、低對比度)。 +- **Improve OCR accuracy**:每個濾鏡皆調校以提升引擎看到的訊噪比。 +- **Run OCR on JPEG**:即使是壓縮過的影像,經過校正與二值化後亦可辨識。 +- **Extract text using Aspose**:`Recognize` 方法回傳純文字字串,可直接用於任何下游邏輯。 + +結合以上步驟,你即可在僅數行程式碼內取得可靠、可投入生產環境的 OCR 解決方案。 + +## 往後步驟與相關主題 + +- **Batch processing** – 迭代資料夾內的影像,將每個結果寫入 `.txt` 檔案。 +- **Language packs** – 將 `OcrLanguage.English` 換成 `OcrLanguage.Spanish`,或加入自訂字典。 +- **PDF extraction** – 結合 Aspose.OCR 與 Aspose.PDF,直接從掃描的 PDF 中抽取文字。 +- **Performance tuning** – 使用 `Parallel.ForEach` 平行執行引擎,以處理大量工作負載。 + +歡迎自行嘗試調整濾鏡數值、測試不同影像格式,或串接額外的 Aspose 濾鏡,例如 `SharpnessOptions`。掌握基礎後,無限可能等著你。 + +--- + +*祝編程愉快!若遇到任何問題,歡迎在下方留言,我們會一起排除故障。* + +## 相關教學 + +- [使用 Aspose.OCR 濾鏡的圖像前處理(.NET)](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [從圖像抽取文字 – Aspose.OCR 的 OCR 最佳化(.NET)](/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/hongkong/net/text-recognition/_index.md b/ocr/hongkong/net/text-recognition/_index.md index 948767d8e..02a3865e9 100644 --- a/ocr/hongkong/net/text-recognition/_index.md +++ b/ocr/hongkong/net/text-recognition/_index.md @@ -55,9 +55,24 @@ url: /zh-hant/net/text-recognition/ 使用 Aspose.OCR 釋放 .NET 中 OCR 的潛力。輕鬆從 PDF 中提取文字。立即下載以獲得無縫整合體驗。 ### [OCR影像辨識中的辨識表](./recognize-table/) 透過我們關於 OCR 影像辨識中表格辨識的綜合指南,釋放 Aspose.OCR for .NET 的潛力。 +### [使用 Aspose OCR 從影像辨識文字 – 完整 C# 指南](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +完整的 C# 教學,示範如何使用 Aspose OCR 從影像中提取文字,涵蓋安裝、設定與範例程式碼。 +### [如何在 C# 中使用 OCR – 從 JPG 識別中文文字](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +示範如何在 C# 使用 Aspose.OCR 從 JPG 圖片中辨識中文文字,包含安裝、設定與範例程式碼。 +### [OCR 俄文文字於 C# – 使用 Aspose OCR 完整指南](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +完整的 C# 教學,示範如何使用 Aspose OCR 從影像中辨識俄文文字,涵蓋安裝、設定與範例程式碼。 +### [使用 Aspose OCR 從影像提取文字 – 完整 C# 指南](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +完整的 C# 教學,示範如何使用 Aspose OCR 從影像中提取文字,涵蓋安裝、設定與範例程式碼。 +### [使用 ASP.NET Core Minimal API 從影像提取文字 – 完整指南](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +完整的指南,示範如何在 ASP.NET Core Minimal API 中使用 Aspose OCR 提取影像文字,涵蓋設定與範例程式碼。 +### [C# OCR 教學:使用 Aspose 從 PNG 收據提取文字](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +使用 Aspose OCR 從 PNG 收據圖像中提取文字的完整 C# 教學,涵蓋安裝、設定與範例程式碼。 +### [在 C# 中將 TIFF 轉換為文字 – 完整批次 OCR 指南](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +使用 Aspose.OCR 在 C# 中批次將 TIFF 影像轉換為文字,提供完整步驟與範例程式碼。 + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/hongkong/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..3f4ef728b --- /dev/null +++ b/ocr/hongkong/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-25 +description: C# OCR 教學,示範如何在 C# 中載入圖像檔案,並使用 Aspose OCR 從收據的 PNG 圖片辨識文字 – 逐步指南。 +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: zh-hant +og_description: C# OCR 教學,指導您在 C# 中載入影像檔案,並使用 Aspose OCR 識別收據中的 PNG 文字。 +og_title: c# OCR 教學 – 從 PNG 收據提取文字 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: C# OCR 教學:使用 Aspose 從 PNG 收據提取文字 +url: /zh-hant/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR 教學 – 使用 Aspose 從 PNG 收據提取文字 + +有沒有曾經需要一個 **c# OCR 教學**,真的能解決問題而不需要無止盡的 Google?你來對地方了。在本指南中,我們將 **load image file c#**、**recognize png text**,以及 **read receipt OCR** 結果,同時向你展示如何使用 Aspose OCR 進行 **perform OCR image** 處理。 + +我們會先安裝所需的 NuGet 套件,逐行說明程式碼,最後以整潔的 JSON 輸出讓你直接串接到下一個資料管線。沒有冗餘,只有實用、可直接執行的解決方案。 + +## 你將學會 + +- 如何在 .NET 6(或更新)專案中設定 Aspose OCR。 +- **load an image file c#** 的完整步驟,並將其交給引擎。 +- 如何從收據影像 **recognize png text** 並取得結果。 +- 如何將 **read receipt OCR** 輸出為格式化良好的 JSON。 +- 在不同檔案類型上執行 **perform OCR image** 操作及處理常見陷阱的技巧。 + +**先決條件** +- Visual Studio 2022(或任何你喜歡的 IDE)。 +- .NET 6 SDK 或更新版本。 +- 一張 PNG 格式的收據圖片(我們稱之為 `receipt.png`)。 + +如果你已備妥,讓我們開始吧。 + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR 教學 – 設定 Aspose OCR 引擎 + +首先,我們需要 Aspose OCR 函式庫。打開解決方案資料夾中的終端機,執行以下指令: + +```bash +dotnet add package Aspose.OCR +``` + +這條指令會一次下載所有必要的套件,包括影像解碼的原生二進位檔。安裝完成後,建立一個新的主控台專案或將程式碼加入現有專案中。 + +### 為什麼選擇 Aspose? + +Aspose OCR 支援超過 30 種語言,能離線運作,且回傳豐富的 `OcrResult` 物件——非常適合需要超出純文字的 **perform OCR image** 任務。 + +## 載入影像檔案 c# 並準備收據 + +現在函式庫已就緒,讓我們 **load image file c#**。`System.Drawing.Image` 類別負責主要的工作,但如果你偏好跨平台方案,也可以使用 `SkiaSharp`。 + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **專業提示:** 如範例所示,將 `Image` 包在 `using` 陳述式中,以即時釋放原生資源——在迴圈中大量 **perform OCR image** 時尤其重要。 + +## 使用 Aspose 進行 PNG 文字辨識 + +影像已載入記憶體後,引擎即可 **recognize png text**。Aspose 會回傳包含原始字串與每個辨識字詞詳細資料的 `OcrResult`。 + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +為什麼要呼叫 `RecognizeWithResult` 而不是較簡單的 `Recognize`?前者能取得信心分數、邊界框與換行資訊——如果之後需要 **read receipt OCR** 以抽取項目明細,會非常方便。 + +## 以 JSON 讀取收據 OCR 結果 + +大多數下游系統都喜愛 JSON,因此我們將 `OcrResult` 序列化。`System.Text.Json` 序列化器能優雅處理複雜物件,我們也會開啟縮排以提升可讀性。 + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +產生的 JSON 大致如下(為簡潔起見已裁剪): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +現在你可以將 `jsonResult` 串接到資料庫、訊息佇列,或僅僅記錄下來作除錯使用。 + +## 執行 OCR 影像處理並顯示輸出 + +最後,將 JSON 輸出至主控台。在實務應用中,你可能會寫入檔案或透過 HTTP 傳送,但使用主控台能快速驗證是否順利執行。 + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +執行程式 (`dotnet run`) 後,你應該會看到格式化良好的 JSON。若收據影像清晰,文字辨識會相當準確;若不清晰,可考慮提升影像解析度或在送入引擎前套用前處理濾鏡(例如灰階、對比度提升)。 + +### 處理常見邊緣案例 + +| 情況 | 處理方式 | +|-----------|------------| +| **Image is blurry** | 使用 `System.Drawing` 進行前處理,銳化或提升 DPI。 | +| **Receipt contains multiple languages** | 設定 `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Large batch processing** | 重複使用單一 `OcrEngine` 實例;每次迭代只更換 `Image`。 | +| **Memory pressure** | 立即釋放 `Image` 物件,並考慮在非同步管線中使用 `await Task.Run`。 | + +這些調整可讓你的 **perform OCR image** 工作流程在輸入不完美時仍保持穩定。 + +## 總結 + +恭喜,你剛完成一個 **c# OCR tutorial**,能載入影像、**recognizes png text**,並將 **reads receipt OCR** 輸出為乾淨的 JSON。核心步驟(引擎設定、影像載入、OCR 執行、序列化與顯示)構成堅實基礎,日後可延伸至發票、護照或其他掃描文件。 + +### 接下來? + +- 嘗試使用 `SkiaSharp` 來 **load image file c#**,以實現真正的跨平台支援。 +- 更深入探索 `OcrResult.Words`,抽取項目、價格與日期——非常適合費用追蹤應用程式。 +- 將本教學與 Azure Functions 或 AWS Lambda 結合,打造無伺服器的收據處理 API。 + +隨意調整程式碼、加入更多影像,或甚至切換至其他語言套件。OCR 的世界充滿驚喜,而你現在已擁有探索它們的工具。 + +祝程式開發順利,願你的收據永遠清晰可讀! + +## 相關教學 + +- [使用 Aspose.OCR 進行語言選擇的 C# 影像文字提取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [從影像提取文字 – 使用 Aspose.OCR 於 .NET 的 OCR 最佳化](/ocr/english/net/ocr-optimization/) +- [如何使用 OCR - 在未偵測文字區域的情況下辨識影像](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/hongkong/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..eddb41935 --- /dev/null +++ b/ocr/hongkong/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-05-25 +description: 使用 Aspose.OCR 於 C# 將 TIFF 轉換為文字。學習批次圖像轉文字的轉換方法,並高效提取 TIFF 檔案中的文字。 +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: zh-hant +og_description: 使用 Aspose.OCR 將 TIFF 轉換為文字。本指南示範批次影像轉文字的轉換方式,以及如何在幾行 C# 程式碼中從 TIFF + 檔案提取文字。 +og_title: 將 TIFF 轉換為文字(C#)– 完整批次 OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: 在 C# 中將 TIFF 轉換為文字 – 完整批次 OCR 指南 +url: /zh-hant/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中將 TIFF 轉換為文字 – 完整批次 OCR 指南 + +是否曾需要 **將 TIFF 轉換為文字**,卻不知從何下手?你並不孤單——許多開發者在處理掃描文件時,都會卡在批次 OCR 上。本文將手把手示範一個 **從 TIFF 檔案擷取文字** 的解決方案,使用 Aspose.OCR,並以平行方式執行,讓大型資料夾在數秒內完成。 + +我們同時也會談到 **批次影像轉文字** 的最佳實踐,最終你將擁有一段可重複使用的程式碼,能將整個目錄的掃描影像一次性轉成整齊的 *.txt* 檔案——非常適合建立索引、搜尋,或供下游分析使用。 + +## 需要的環境 + +- **.NET 6.0** 或更新版本(程式碼亦可在 .NET Framework 上編譯) +- **Aspose.OCR for .NET** NuGet 套件(`Install-Package Aspose.OCR`) +- 一個包含一個或多個 *.tif* 檔案的資料夾(經典的 TIFF 掃描格式) +- 你慣用的 IDE(Visual Studio、VS Code、Rider——隨你喜好) + +就這些。無需外部服務、API 金鑰,只要純粹的 C# 與 Aspose。 + +![處理中的 TIFF 檔案及其產生的文字檔案之螢幕截圖](/images/ocr-result.png "OCR 結果顯示已轉換的 TIFF 為文字輸出") + +*(Alt text: 螢幕截圖顯示已將 TIFF 轉換為文字的輸出結果)* + +## 步驟 1:設定 OCR 引擎 – 將 TIFF 轉換為文字 + +首先,我們需要一個 `OcrEngine` 實例,並告訴它要讀取英文字符。引擎是轉換的核心;正確設定可確保結果可靠。 + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*為什麼這很重要:* +Aspose.OCR 支援數十種語言。如果你的掃描文件是多語言,只要將 `OcrLanguage.English` 改成對應的列舉值即可。若未指定語言,引擎會進入自動偵測模式,速度較慢且準確度可能下降。 + +## 步驟 2:收集所有 TIFF 檔案 – 高效提取 TIFF 文字 + +接著,我們從你指定的資料夾中抓取每一個 *.tif* 檔案。使用 `Directory.GetFiles` 可取得乾淨的陣列,方便後續批次處理。 + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*小技巧:* 若掃描檔案散布於子資料夾,可使用 `SearchOption.AllDirectories` 旗標。但請注意,遞迴層級過深可能會在批次階段增加記憶體使用量。 + +## 步驟 3:執行平行 OCR – 批次影像轉文字 + +現在進入有趣的部分。Aspose.OCR 內建靜態輔助工具 `BatchOcr.RecognizeAll`,接受檔案路徑陣列、引擎以及 `parallelism` 提示。我們將啟動四條執行緒,在現代四核心筆記型電腦上可獲得近線性加速。 + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*為什麼要使用平行處理?* +一次處理大量高解析度 TIFF 會非常耗費 CPU。將工作分散到多條執行緒,可讓所有核心保持忙碌,顯著縮短總執行時間。若在核心更多的伺服器上執行,只要相應提升 `parallelism` 數值即可。 + +## 步驟 4:寫入輸出 – 將掃描影像轉為 TXT 檔案 + +最後,我們遍歷字典,將每段文字寫入與原始檔名相同但副檔名為 *.txt* 的檔案。這就是 **將掃描影像轉為 txt** 成真的時刻。 + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### 程式碼功能說明(簡易說明) + +1. **建立** 一個設定為英文的 OCR 引擎。 +2. **收集** 目標資料夾內的所有 TIFF 檔案。 +3. **執行** `BatchOcr.RecognizeAll`,使用四條執行緒,將每張影像轉成字串。 +4. **遍歷** 結果,將 `.tif` 副檔名換成 `.txt`,並寫入磁碟。 + +以上就是在不到 50 行程式碼內完成 **將 TIFF 轉換為文字** 工作流程的全部內容。 + +## 處理例外情況 – 當流程不順時 + +- **遺失或損毀的 TIFF** – `BatchOcr` 會拋出 `OcrException`。如需優雅降級,請將呼叫包在 `try / catch` 中。 +- **非英文文件** – 將 `OcrLanguage.English` 改成 `OcrLanguage.Spanish`、`OcrLanguage.French` 等,或使用 `OcrLanguage.AutoDetect`。 +- **極大尺寸的影像** – 考慮在 OCR 前降低 DPI(`ocrEngine.ImagePreprocessing.Dpi = 200`),以節省記憶體,但可能會犧牲部分準確度。 +- **輸出編碼** – 若需特定代碼頁(例如 Windows‑1252),可使用 `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`。 + +## 專業提示:打造穩健的批次轉換 + +- **記錄失敗**:建立 `List failedFiles`,將拋例的檔案加入清單,最後寫入日誌。 +- **重複使用引擎**:同一個 `OcrEngine` 實例可在多個檔案間重複使用,切勿在迴圈內重新實例化。 +- **驗證結果**:簡單的 `if (string.IsNullOrWhiteSpace(extractedText))` 可偵測空白或無法辨識的掃描。 +- **結合 PDF**:若來源是多頁 PDF,可先使用 Aspose.PDF 逐頁轉成 TIFF,再套用本批次流程。 + +## 後續步驟 – 超越簡單轉換 + +現在你已能 **批次擷取 TIFF 文字**,接下來或許想: + +- 將 *.txt* 檔案匯入搜尋索引(Elasticsearch、Azure Cognitive Search)。 +- 為每個結果執行語言偵測,將文件導向特定語系的處理管線。 +- 透過將 OCR 文字覆蓋回原始影像,產生可搜尋的 PDF(再次使用 Aspose.PDF)。 + +所有這些情境皆建立在同一核心概念上:**批次影像轉文字** 是更大文件處理系統的基礎模組。 + +--- + +### 結論 + +你剛剛學會如何使用 Aspose.OCR **將 TIFF 轉換為文字**,以平行方式處理整個資料夾,並將每個結果儲存為乾淨的 *.txt* 檔案。此解決方案輕量、可完全自訂,且已具備上線條件——無論是數位化舊發票、歸檔掃描合約,或是為文字搜尋引擎供稿,都能輕鬆應對。 + +快試試看,調整平行度,開始把新產生的文字檔案投入你的工作流程吧。祝 OCR 順利! + +--- + + +## 相關教學 + +- [使用 OCR 操作於資料夾中擷取影像文字](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [影像文字擷取 – 使用 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/hongkong/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/hongkong/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..f9a8d6255 --- /dev/null +++ b/ocr/hongkong/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: 學習如何使用精簡的 ASP.NET Core API 從圖像中提取文字。透過 POST 上傳圖像,讀取 multipart 表單資料並對圖像執行 + OCR。 +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: zh-hant +og_description: 使用精簡的 ASP.NET Core API 從圖像提取文字。本指南說明如何透過 POST 上傳圖像、讀取 multipart 表單資料,並對圖像執行 + OCR。 +og_title: 在 ASP.NET Core 中從圖像擷取文字 – 步驟說明 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: 在 ASP.NET Core Minimal API 中從圖片提取文字 – 完整指南 +url: /zh-hant/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從圖像中提取文字的 ASP.NET Core Minimal API 完整指南 + +你有沒有想過如何在不使用龐大框架的情況下 **extract text from image**?你並不孤單。許多開發者需要一個快速的方式,讓使用者上傳圖片後即可取得原始文字,無論是掃描收據、數位化手寫筆記,或是為搜尋索引提供文字。 + +在本教學中,我們將建立一個小型的 ASP.NET Core Minimal API,具備 **uploads image via POST** 功能,解析 *multipart/form‑data* 負載,然後使用單例 `OcrEngine` 來 **perform OCR on image**。完成後,你將擁有一個可直接在任何 .NET 8 專案中使用的完整可執行應用,即可立即開始從圖像中提取文字。 + +## 你將建立的內容 + +- 一個監聽 `/ocr` 的最小化 Web 應用程式。 +- 一個接受使用 `multipart/form-data` POST 請求傳送的圖像檔案的端點。 +- 讀取上傳檔案、將其送入 OCR 引擎,並回傳純文字結果的邏輯。 +- 可選的 GPU 加速程式碼片段(已註解),供具備相容顯示卡的使用者使用。 + +**先決條件** +- .NET 8 SDK(或更新版本)。 +- 具備 C# 與命令列的基本知識。 +- 提供 `OcrEngine` 類別的 OCR 函式庫(範例假設使用一個虛構的 NuGet 套件)。 + +如果你已具備上述條件,讓我們開始吧。 + +## 步驟 1:設定專案並加入 OCR 套件 + +首先,建立一個新的 Web 專案,並將 OCR 函式庫加入專案。 + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **專業提示:** 請保持相依套件為最新版本。較新的版本通常能提升效能,尤其是在 GPU 加速推論時。 + +## 步驟 2:註冊單例 OCR 引擎(主要服務) + +我們希望整個應用程式只使用一個 `OcrEngine` 實例——不必在每個請求都重新建立引擎。將它註冊到 builder 的服務容器中。 + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**為什麼使用單例?** +建立 OCR 引擎的成本相當高——例如需要將神經網路權重載入記憶體。重複使用同一個實例可節省 CPU 時間與記憶體,從而提升每次 `/ocr` 呼叫的回應速度。 + +## 步驟 3:建構應用程式 + +現在我們將實體化 `WebApplication` 物件。 + +```csharp +var app = builder.Build(); +``` + +那行程式碼看起來幾乎像魔法,但實際上它在底層為我們剛剛設定的路由、middleware 與 DI 容器 **wires** 起來。 + +## 步驟 4:定義 POST 端點 – “Upload Image via POST” + +這就是本教學的核心:一個會 **upload image via POST**、讀取 multipart 負載,並將資料交給 OCR 引擎的端點。 + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### 逐步說明邏輯 + +| 步驟 | 發生了什麼 | 為何重要 | +|------|------------|----------| +| **ReadFormAsync** | 解析傳入的 *multipart/form-data* 請求。 | 若未執行此步驟,將無法取得上傳的檔案。 | +| **form.Files["image"]** | 取得表單欄位名稱為 `image` 的檔案。 | 為呼叫端提供可預測的合約。 | +| **Content‑type check** | 檢查檔案是否為圖像(例如 `image/png`)。 | 防止 OCR 引擎在非圖像資料上失敗。 | +| **Image.FromStream** | 將原始串流轉換為 `System.Drawing.Image`。 | OCR 函式庫需要 `Image` 物件,而非原始位元組陣列。 | +| **ocr.Recognize(img)** | 呼叫 OCR 引擎以 **how to recognize text from image**。 | 這是核心的 **perform OCR on image** 步驟。 | +| **Results.Text** | 回傳純文字回應。 | 為下游服務提供簡單、易於消費的格式。 | + +## 步驟 5:執行 API + +最後,啟動 Web 伺服器。 + +```csharp +app.Run(); +``` + +當你執行 `dotnet run` 時,API 會監聽在 `http://localhost:5000`(或你自行設定的埠號)。你可以使用 `curl` 進行測試: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**預期輸出:** 主控台會印出辨識出的字元,例如: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +若圖像模糊或語言不受支援,OCR 引擎會回傳空字串或錯誤訊息——請在 **production code** 中妥善處理這些情況。 + +## 邊緣案例與最佳實踐 + +### 1. 大檔案 + +預設的請求主體大小上限為 30 MB。若要處理更大的掃描檔,可能需要調整: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. 非同步 OCR + +某些 OCR 函式庫提供非同步方法(`RecognizeAsync`)。如果你的函式庫支援,請將 `ocr.Recognize(img)` 改為 `await ocr.RecognizeAsync(img)`,並將 lambda 標記為 `async`。 + +### 3. 安全性考量 + +- **Validate file size**:在載入記憶體前先驗證檔案大小。 +- **Sanitize the filename**:若將檔案寫入磁碟,請先清理檔名。 +- **Rate‑limit**:對端點實施速率限制,以防止拒絕服務攻擊。 + +### 4. GPU 加速 + +若取消註解 `engine.GpuDevice = new GpuDevice(0);` 並且硬體支援 CUDA 或 DirectML,你將看到明顯的效能提升,特別是在高解析度圖像上。 + +## 完整範例 + +以下是完整的 `Program.cs`,你可以直接複製貼上到全新的 Minimal API 專案中。 + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +儲存後,執行 `dotnet run`,即可隨時 **extract text from image**。 + +## 結論 + +我們已完整說明如何使用 ASP.NET Core Minimal API 來實作 **complete, end‑to‑end solution**,從專案骨架開始,**registered a singleton OCR engine**,建立一個 **uploads image via POST**、**read multipart form data** 的端點,最終 **perform OCR on image**,回傳乾淨的純文字。 + +從此你可以: + +- 為回應加入 JSON 包裝,以提供更豐富的資料。 +- 接入資料庫以儲存提取出的文字。 +- 擴充支援多語言(例如 `OcrLanguage.Spanish` 等)。 + +這個模式相當易於擴展——只要將相同的端點放入更大的微服務,或在 API Gateway 後面暴露即可。 + +有關 PDF 處理、批次作業或 GPU 調校的問題嗎?歡迎留言,祝開發愉快! + +## 相關教學 + +- [使用 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/hongkong/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/hongkong/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..5f7ad771c --- /dev/null +++ b/ocr/hongkong/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,290 @@ +--- +category: general +date: 2026-05-25 +description: 使用 C# 與 Aspose OCR 從圖像中提取文字。了解如何將 jpg 轉換為文字、載入圖像進行 OCR,快速獲得可靠的結果。 +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: zh-hant +og_description: 使用 C# 從圖像提取文字。本指南說明如何將 jpg 轉換為文字、載入圖像進行 OCR,以及處理多語言內容。 +og_title: 在 C# 中從圖像擷取文字 – Aspose OCR 教程 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: 在 C# 中從影像提取文字 – 完整 Aspose OCR 指南 +url: /zh-hant/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 從圖片中提取文字(C#)– 完整 Aspose OCR 指南 + +有沒有想過如何使用純 C# 程式碼**extract text from image**?你並不是唯一有此疑問的人。無論是數位化收據、掃描招牌,或只是對 OCR 好奇,能夠從圖片中抽取字元是一項實用技能。在本教學中,我們將逐步示範一個完整、可執行的範例,說明如何使用 Aspose.OCR **extract text from image**,同時也會說明如何**convert jpg to text**、**load image for OCR**,以及一次解答經典的「**how to ocr image**」問題。 + +完成本指南後,你將擁有一個自包含的主控台應用程式,能讀取 JPEG 檔案、辨識烏克蘭語(或任何其他支援的語言),並將結果輸出到主控台。沒有模糊的參考,沒有遺漏的部份——只要複製貼上即可執行的完整解決方案。 + +--- + +## 你將學到什麼 + +* 如何安裝 Aspose.OCR NuGet 套件。 +* 在 C# 中**load image for OCR** 所需的完整程式碼。 +* 如何設定語言並真正**extract text from image**。 +* 有效率地**convert jpg to text** 的技巧。 +* 常見的陷阱以及如何避免它們。 + +如果你已經設定好 .NET 開發環境,就可以直接開始。否則,以下的先決條件部分會讓你快速上手。 + +## 先決條件 + +| 需求 | 為什麼重要 | +|-------------|----------------| +| .NET 6.0 SDK(或更新版本) | 為主控台應用程式提供執行環境。 | +| Visual Studio 2022 或 VS Code | 讓編輯與除錯更方便。 | +| 網際網路連線(首次執行時) | NuGet 需要下載 Aspose.OCR。 | +| 你想處理的 JPEG 圖片(例如 `ukrainian_sign.jpg`) | OCR 引擎的來源檔案。 | + +> **專業提示:**如果你使用 Linux 或 macOS,相同的程式碼可在 .NET CLI(`dotnet new console`)下執行,因此可以省去繁重的 IDE。 + +## 第一步 – 透過 NuGet 安裝 Aspose.OCR + +在終端機(或套件管理員主控台)中執行以下指令: + +```bash +dotnet add package Aspose.OCR +``` + +這一行指令會下載最新的 Aspose.OCR 二進位檔以及所有相依的套件,無需手動處理 DLL。 + +## 第二步 – 建立 OCR 引擎(提取的核心) + +現在函式庫已就緒,我們可以建立 `OcrEngine` 的實例。此物件負責**extract text from image**資料的處理。 + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **為什麼重要:**引擎封裝了 OCR 演算法、語言模型與設定選項。只建立一次並在多張圖片間重複使用,可提升記憶體效率與速度。 + +## 第三步 – 載入圖片以進行 OCR(並設定語言) + +下一步是告訴引擎要讀取哪張圖片。這就是**load image for OCR**發揮作用的地方。 + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **例外情況:**如果檔案不存在,`Image.FromFile` 會拋出 `FileNotFoundException`。在正式環境中請將呼叫包在 try‑catch 區塊內。 + +## 第四步 – 執行 OCR 並提取文字 + +圖片載入後,引擎即可**extract text from image**。`Recognize` 方法負責主要的辨識工作。 + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +如果一切順利,`recognizedText` 會包含 OCR 引擎所讀取到的純文字內容。 + +## 第五步 – 將 JPG 轉換為文字(完整整合) + +我們目前寫的程式碼已經**convert jpg to text**,但讓我們將它封裝成一個可重複呼叫的整潔方法。 + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +現在你只需要這樣呼叫: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**預期輸出**(為簡潔起見已截斷): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +如果圖片內含英文文字,將 `OcrLanguage.English` 改成相應語言,即可看到對應的輸出。 + +## 第六步 – 處理常見的「How to OCR Image」問題 + +### 6.1 我可以 OCR PNG 或 BMP 嗎? + +當然可以。`Image.FromFile` 支援 System.Drawing 能辨識的所有格式,只要將路徑指向 `.png` 或 `.bmp` 檔案,其他程式碼皆保持不變。 + +### 6.2 如果圖片解析度太低怎麼辦? + +當解析度低於 300 dpi 時,OCR 準確度會急劇下降。快速的解決方式是使用 `Graphics` 將圖片放大後再送入引擎: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 使用 Aspose.OCR 是否需要授權? + +Aspose 提供帶有浮水印的免費試用版。正式使用時,請購買授權並加入: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +## 完整範例程式 + +以下是一個完整、可直接執行的主控台應用程式,示範**how to OCR image**、**load image for OCR** 與 **convert jpg to text** 的完整流程。 + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**如何執行** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +執行後,你應該會在主控台看到提取出的文字,證明已成功使用 C# **extract text from image**。 + +## 常見陷阱與專業提示 + +| 問題 | 為什麼會發生 | 解決方式 | +|-------|----------------|-----| +| 空白輸出 | 圖片過暗或對比度低。 | 使用 `Bitmap` 前處理以提升亮度。 | +| 語言設定錯誤 | `Language` 屬性仍為預設的英文。 | 明確設定 `ocrEngine.Language = OcrLanguage.Ukrainian;`(或其他目標語言)。 | +| 記憶體不足錯誤 | 載入過大的圖片卻未釋放。 | 將 `Image.FromFile` 包在 `using` 區塊中(如範例所示)。 | +| 授權浮水印 | 使用試用版且未提供授權。 | 在 `Main` 早期套用購買的授權。 | + +## 結論 + +我們已說明在 C# 中**extract text from image**所需的全部步驟——從安裝 Aspose.OCR、**load image for OCR**、**convert jpg to text** 到多語系處理。完整的範例程式將所有環節串接起來,為任何 OCR 相關專案提供可靠的基礎。 + +接下來,你可以探索: + +* **How to OCR image** 串流而非檔案(使用 `MemoryStream`)。 +* 加入 **c# image to text** 後處理,例如拼字檢查。 +* 將 OCR 步驟整合至更大的工作流程(例如將結果儲存至資料庫)。 + +歡迎嘗試不同語言、圖片格式與前處理技巧。OCR 如同藝術與科學的結合,玩得越多,結果越好。 + +祝程式開發愉快,願你的圖片永遠可讀! + +## 相關教學 + +- [使用 Aspose.OCR 進行語言選擇的 C# 圖片文字提取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [從圖片提取文字 – 使用 Aspose.OCR 於 .NET 的 OCR 最佳化](/ocr/english/net/ocr-optimization/) +- [透過在 OCR 中準備矩形來提取圖片文字的方法](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/hongkong/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..7c46269a1 --- /dev/null +++ b/ocr/hongkong/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-05-25 +description: 如何在 C# 中使用 OCR 從圖像檔案提取文字。只需幾個簡單步驟,即可學會使用 Aspose.OCR 從 JPG 識別中文字符。 +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: zh-hant +og_description: 如何在 C# 中使用 OCR 從圖像檔案提取文字。本指南示範如何使用 Aspose.OCR 從 JPG 識別中文字符。 +og_title: 如何在 C# 中使用 OCR – 從 JPG 識別中文文字 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: 如何在 C# 中使用 OCR – 從 JPG 識別中文文字 +url: /zh-hant/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 如何在 C# 中使用 OCR – 從 JPG 識別中文文字 + +有沒有想過 **如何使用 OCR** 從手機拍攝的圖片中提取文字?你並不孤單。在許多實際專案中——例如收據掃描器、翻譯應用程式或自動化資料輸入——你都需要快速且可靠地 **從圖像中提取文字**。 + +在本教學中,我們將逐步說明一個完整且可執行的範例,該範例 **從 JPG 檔案中識別文字**,甚至能處理使用 **OCR Chinese Simplified** 語言套件的 **中文字符識別**。完成後,你將擁有一個獨立的主控台應用程式,能將偵測到的字串印出到主控台,且不需要額外手動下載。 + +> **快速說明:** 此程式碼適用於 Aspose.OCR ≥ 23.7,會在首次使用時自動下載語言資源。若使用較舊版本,則需手動加入語言。 + +## 前置條件 + +在開始之前,請確保你已具備: + +- .NET 6.0 SDK 或更新版本(範例目標為 .NET 6,但 .NET 5 亦可使用) +- 最新版的 Visual Studio 2022 或搭配 C# 擴充功能的 VS Code +- 首次下載語言檔時需要的網際網路連線 +- 包含簡體中文文字的 JPG 圖片(此處稱為 `chinese_sign.jpg`) + +就這樣——不需要大型 OCR 引擎,也不必處理原生 DLL。只要幾個 NuGet 指令和幾行程式碼即可。 + +## 第一步:透過 NuGet 安裝 Aspose.OCR + +首先,我們需要 OCR 函式庫。於專案資料夾中開啟終端機並執行: + +```bash +dotnet add package Aspose.OCR +``` + +或者,你也可以使用 Visual Studio 介面,於 **Dependencies → Manage NuGet Packages** 右鍵點擊,搜尋 “Aspose.OCR”,然後點選 **Install**。 + +> **小技巧:** 保持套件為最新版本。每個次要版本都會加入新的語言套件與效能優化。 + +## 第二步:建立新的主控台專案(如果尚未建立) + +如果從頭開始,建立一個全新的主控台應用程式: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +現在你已擁有一個 `Program.cs` 檔案,可用於放置 OCR 程式碼。 + +## 第三步:撰寫 OCR 程式碼 – 從 JPG 識別簡體中文 + +開啟 `Program.cs`,將其內容替換為下列程式碼。每一行皆有註解,讓你了解 *為何* 這樣做,而不只是 *做了什麼*。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 背後的運作原理 + +- **`OcrEngine.Language`** 告訴 Aspose 要使用哪個字典。選擇 `ChineseSimplified` 後,引擎會尋找簡體中文語言套件。 +- **首次下載**:當呼叫 `Recognize` 時,SDK 會連線至 Aspose 的 CDN,下載約 6 MB 的語言檔案,並在本機快取,之後的辨識即時完成。 +- **`Image.FromFile`** 能處理 .NET 可解碼的任何點陣圖格式——JPG、PNG、BMP——因此你可以 **從圖像中提取文字**,不僅限於 JPG。 + +## 第四步:執行應用程式並驗證輸出 + +建置並執行: + +```bash +dotnet run +``` + +你應該會看到類似以下的結果: + +``` +=== Recognized Text === +欢迎光临 +``` + +如果主控台顯示亂碼或空字串,請再次確認以下項目: + +1. 圖片確實包含清晰且高對比度的中文字符。 +2. 檔案路徑正確(沒有多餘的空格或遺漏副檔名)。 +3. 你的機器能連線至 `https://download.aspose.com` 以下載語言套件。 + +## 第五步:處理邊緣情況與常見陷阱 + +### 5.1 處理低品質影像 + +當來源影像模糊、雜訊多或光線不足時,OCR 的準確度會下降。快速的解決方式是先對影像進行前處理: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 在無頭環境執行 + +如果你將應用程式部署至沒有圖形介面的 Linux 容器,請確保已安裝 `libgdiplus` 函式庫(`System.Drawing` 所必需)。 + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 手動快取語言套件 + +你可以先下載語言檔,然後透過 `License` API 指向該檔案,這樣就能避免一次性的網路下載,對於離線情境相當方便。 + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## 完整範例(全功能) + +以下是可直接複製貼上至 `Program.cs` 的 *完整* 程式碼。沒有隱藏的部份,也不需要外部腳本。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 預期輸出 + +若 JPG 包含「欢迎光临」這句話,主控台將會印出: + +``` +=== Recognized Text === +欢迎光临 +``` + +你可以自行更換成其他簡體中文招牌、街道名稱或商品標籤——引擎會盡力辨識。 + +## 結論 + +我們剛剛說明了在 C# 中 **如何使用 OCR** 來 **從圖像檔案中提取文字**,特別是處理 **在 JPG 中識別中文字符** 的挑戰。透過 Aspose.OCR 即時下載語言的功能,你可以保持部署的輕量化,同時即時支援 **OCR Chinese Simplified**。 + +接下來可以試試以下想法: + +- **批次處理**:遍歷資料夾中的影像,將每個結果寫入 CSV。 +- **結合翻譯 API**:將辨識出的字串送至 Azure Translator,實作即時多語言應用程式。 +- **探索其他語言**:將 `OcrLanguage.ChineseSimplified` 換成 `Japanese` 或 `Arabic`,觀察相同程式碼的適應情況。 + +對效能調校、授權或將 OCR 整合至 Web 服務有任何疑問嗎?歡迎在下方留言——祝開發愉快! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + +## 相關教學 + +- [使用 Aspose.OCR 進行語言選擇的 C# 圖像文字提取](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [使用 Aspose OCR 識別多語言圖像文字](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [透過設定矩形在 OCR 中提取圖像文字](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hongkong/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/hongkong/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..bb8176810 --- /dev/null +++ b/ocr/hongkong/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-05-25 +description: 學習如何在 C# 中使用 Aspose OCR 進行俄文文字的光學字符辨識,從圖像中擷取文字。一步一步的程式碼示範,快速將圖像轉換為文字(C#)。 +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: zh-hant +og_description: 在 C# 中輕鬆實現俄文 OCR。學習如何從圖片提取文字、將圖片轉換為文字(C#),以及使用 Aspose OCR 載入圖片進行 OCR。 +og_title: C# 中的俄文 OCR – 完整 Aspose OCR 指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: 在 C# 中 OCR 俄文文本 – 使用 Aspose OCR 的完整指南 +url: /zh-hant/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 在 C# 中 OCR 俄文文字 – 使用 Aspose OCR 的完整指南 + +有沒有曾經需要在 C# 中 OCR 俄文文字卻不確定該選哪個函式庫?你並不孤單。從西里爾字母圖片中取得乾淨、可讀的字元,有時感覺像在破解祕密訊息——尤其是如果沒有設定正確的語言模型。 + +在本教學中,我們將示範一個實作範例,教你如何 **從圖片提取文字**、以 *image to text C#* 方式轉換,並處理俄文辨識的細節,全部使用 Aspose OCR。完成後,你將擁有一個可直接執行的主控台應用程式,能載入圖片進行 OCR、印出辨識結果,並為更進階的情境奠定堅實基礎。 + +## 你將學到 + +- 如何安裝與設定 **Aspose OCR C#** 以支援俄文。 +- **載入圖片進行 OCR** 並呼叫引擎的完整步驟。 +- 處理常見問題(如缺少語言資源或影像模糊)的技巧。 +- 延伸解決方案的方法,例如批次處理多個檔案或調整信心門檻。 + +不需要事先使用過 Aspose;只要對 C# 與 .NET 有基本認識,即可上手。 + +## 前置條件 + +在開始之前,請先確保你具備以下項目: + +1. 已安裝 **.NET 6.0**(或更新版)SDK ─ 這段程式碼同時支援 .NET Core 與 .NET Framework。 +2. **Visual Studio 2022**(或任何你慣用的 IDE)。 +3. **Aspose.OCR for .NET** NuGet 套件 ─ 可從 Aspose 官網取得免費試用金鑰。 +4. **俄文語言模型** 檔案(`rus.traineddata`)─ 從 Aspose 資源頁下載,放置於稍後會引用的資料夾中。 +5. 一張包含清晰西里爾文字的範例圖片(`russian_doc.png`)。 + +都準備好了嗎?太好了──讓我們開始吧。 + +## 步驟 1:建立專案並安裝 Aspose OCR + +首先,建立一個新的主控台專案: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +接著加入 Aspose OCR 套件: + +```bash +dotnet add package Aspose.OCR +``` + +> **專業小技巧:** 若使用試用授權,請將 `Aspose.Total.lic` 檔案備好;稍後會在程式碼中載入,以避免浮水印。 + +套件安裝完成後,開啟 `Program.cs`。你會看到預設的 `Main` 方法──將其內容替換為我們即將建立的骨架程式碼。 + +## 步驟 2:為俄文語言設定 OCR 引擎 + +核心物件是 `OcrEngine`。我們需要告訴它兩件事:要辨識的語言以及語言模型檔案所在位置。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **為什麼這很重要:** 若未設定 `Language = OcrLanguage.Russian`,引擎會預設使用英文,所有西里爾字元都會變成亂碼。`ResourceFolder` 必須指向包含 `rus.traineddata` 的目錄;否則 Aspose 會拋出「找不到資源」例外。 + +## 步驟 3:載入圖片進行 OCR + +現在我們要 **載入圖片進行 OCR**。Aspose OCR 使用 `System.Drawing.Image`,因此任何支援的格式(PNG、JPEG、BMP 等)皆可。請確認檔案路徑正確;相對路徑在圖片與執行檔同目錄時也能正常運作。 + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **邊緣情況:** 若圖片過大(超過 5 MB),建議先縮小。當 DPI 太低時 OCR 準確度會下降,而巨大的檔案則可能造成記憶體壓力。必要時可使用 `Graphics` 進行快速縮放。 + +## 步驟 4:辨識文字 – 從圖片到文字的 C# 方式 + +引擎設定完成、圖片載入後,辨識只需要一行呼叫: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +執行程式(`dotnet run`)後,應會看到類似以下的輸出: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +若輸出是亂碼,請再次確認: + +- `rus.traineddata` 檔案已放在 `ResourceFolder` 中。 +- 圖片不過於模糊;必要時可先做二值化處理。 +- 語言設定確實為 `OcrLanguage.Russian`。 + +## 步驟 5:微調與常見問題 + +### 調整信心門檻 + +Aspose OCR 內部會為每個字元回傳信心值。雖然 API 本身不直接暴露,但可啟用 **詳細輸出** 以觀察哪些詞的信心較低: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +若發現頻繁誤辨,可嘗試: + +- **前處理**:將圖片轉為灰階、提升對比度,或套用中值濾波。 +- **DPI 設定**:確保圖片至少 300 DPI,對西里爾字體尤為重要。 + +### 批次處理多張圖片 + +若需要 **從圖片提取文字** 的批次作業,只要把辨識程式碼包在迴圈中即可: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +如此每張 PNG 都會產生對應的 `.txt` 檔案──非常適合文件歸檔。 + +### 處理 Unicode 輸出 + +西里爾字元屬於 Unicode,請確保主控台編碼能正確顯示: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +將此行放在 `Main` 方法一開始。若未設定,可能會看到問號 (`?`) 取代俄文字。 + +## 完整範例 + +以下是可直接執行的完整程式碼。複製貼上至 `Program.cs`,調整路徑後即可運行。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**預期輸出**(假設範例圖片顯示「Пример текста на русском языке.」): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +若看到其他結果,請回到第 5 步的故障排除建議再檢查一次。 + +## 結論 + +現在你已掌握使用 Aspose OCR 在 C# 中 **ocr russian text** 的完整端對端範例。從安裝函式庫、設定俄文語言模型、載入圖片,到將其轉換為乾淨的 Unicode 文字,每一步都已說明。 + +記住,可靠的 OCR 依賴於良好的來源素材:清晰的字型、足夠的 DPI,以及正確的語言資源。熟悉基礎後,你可以擴展至批次處理、與雲端儲存整合,甚至結合 AI 後處理進行拼寫檢查。 + +### 接下來可以做什麼? + +- 探索 **aspose ocr c#** 的進階功能,如版面分析或 PDF 輸出。 +- 結合 **extract text from image** 工作流程於 Azure Functions,實現無伺服器處理。 +- 嘗試其他語言──只要把 `OcrLanguage.Russian` 改成 `OcrLanguage.English` 或其他支援的代碼即可。 + +有問題或遇到無法辨識的圖片嗎?歡迎在下方留言,我們一起解決! + +![ocr russian text example](ocr-russian-example.png){alt="ocr 俄文文字範例"} + +## 相關教學 + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/hongkong/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..cbf30e721 --- /dev/null +++ b/ocr/hongkong/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-25 +description: 使用 Aspose OCR 於 C# 識別圖像文字。了解如何載入圖像進行 OCR、設定 OCR 語言、建立 OCR 引擎以及從 TIFF + 提取文字。 +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: zh-hant +og_description: 使用 Aspose OCR 於 C# 識別圖像中的文字。本教學示範如何建立 OCR 引擎、載入待 OCR 圖像、設定 OCR 語言,並從 + TIFF 中提取文字。 +og_title: 使用 Aspose OCR 從圖像中辨識文字 – 完整 C# 指南 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: 使用 Aspose OCR 從圖像辨識文字 – 完整 C# 指南 +url: /zh-hant/net/text-recognition/recognize-text-from-image-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 進行影像文字辨識 – 完整 C# 教學 + +是否曾需要 **recognize text from image**,卻不確定哪個函式庫能同時提供速度與準確度?你並不孤單。在許多發票處理或檔案保存專案中,最大的痛點往往是從 TIFF 檔案中取得乾淨、可搜尋的文字,而不必自行撰寫解析器。 + +事實上:Aspose OCR for .NET 讓整個流程變得輕而易舉。在本教學中,我們會一步步說明所有必備步驟——安裝套件、**creating OCR engine**、載入 TIFF、設定 OCR 語言,最後 **extracting text from TIFF**。完成後,你將擁有一個可直接執行的主控台應用程式,能在瞬間 **recognize text from image** 檔案。 + +## Prerequisites + +- .NET 6.0 或更新版本(程式碼同樣支援 .NET Core 與 .NET Framework) +- Visual Studio 2022(或任何你慣用的 IDE) +- Aspose.OCR NuGet 套件(若需 GPU 加速,必須額外安裝 `Aspose.OCR.Gpu` 外掛) +- 若想獲得額外速度,需具備支援 CUDA 的 GPU(可選,但建議) + +> **Pro tip:** 若沒有 GPU,只需省略 `GpuDevice` 那一行,引擎會自動回退至 CPU。 + +## Step 1: Install Aspose OCR and Create OCR Engine + +首先,透過 NuGet 加入必要的套件: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +接著我們可以 **create OCR engine**。此物件是整個流程的核心,負責保存執行裝置與記憶體限制等設定。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Why this matters:** 將引擎綁定至 GPU 後,**recognize text from image** 的時間會大幅縮短,尤其是大量高解析度 TIFF 時。 + +## Step 2: Load Image for OCR + +接下來,我們需要 **load image for OCR**。Aspose.OCR 使用 `System.Drawing.Image`,只要是 GDI+ 支援的格式(包括多頁 TIFF)皆可。 + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +若處理多頁 TIFF,可使用 `image.SelectActiveFrame` 迴圈遍歷每一頁,但在大多數情況下只需一次呼叫即可。 + +## Step 3: Set OCR Language + +引擎不會自動知道你要辨識的語言。**Set OCR language** 後再執行辨識,否則會得到大量亂碼。 + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Did you know?** 在執行期間切換語言的成本很低,你甚至可以在不同頁面之間變更此屬性,以處理混合語言的文件。 + +## Step 4: Perform the Recognition – Recognize Text from Image + +現在進入有趣的部分:實際 **recognize text from image**。`Recognize` 方法會回傳一個純文字字串,包含所有偵測到的字元。 + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +如果需要信心分數或文字框資訊,可使用回傳 `OcrResult` 物件的重載版本,但對大多數抽取任務而言,純文字已足夠。 + +## Step 5: Extract Text from TIFF (and handle multi‑page files) + +當來源是包含多頁的 TIFF 時,需對每一個影格重複步驟 2‑4。以下是一段快速迴圈,**extracts text from TIFF**,逐頁處理: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +上述程式會列印每一頁的抽取文字,讓你輕鬆將結果寫入資料庫或搜尋索引。 + +## Step 6: Display or Persist the Extracted Text + +最後,我們 **display the extracted text**,並可選擇寫入檔案以供後續處理。 + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +執行程式後,應會在螢幕上顯示辨識出的字元,並在來源 TIFF 旁產生 `extracted_text.txt`。 + +--- + +## Common Questions & Edge Cases + +- **What if my GPU isn’t detected?** + 移除 `GpuDevice` 那一行;引擎會自動切換至 CPU 模式。效能會較慢,但結果仍保持準確。 + +- **Can I process PNG or JPEG files?** + 當然可以——`Image.FromFile` 支援所有 System.Drawing 可處理的格式,所以你可以 **load image for OCR**,不受副檔名限制。 + +- **How do I handle low‑resolution scans?** + 在呼叫 `Recognize` 前,提高 `ocrEngine.PreprocessOptions.Dpi`。較高的 DPI 讓引擎取得更多像素,提升辨識準確度。 + +- **Is there a limit to the size of the TIFF?** + `GpuMemoryLimit` 屬性會限制 GPU 記憶體使用量。若超過上限,剩餘頁面會自動回退至 CPU 處理。 + +--- + +## Conclusion + +現在你已擁有一段完整、可投入生產環境的程式碼,能使用 Aspose OCR 在 C# 中 **recognize text from image**。本教學說明了如何 **create OCR engine**、**load image for OCR**、**set OCR language**,以及 **extract text from TIFF**,同時利用 GPU 加速提升速度。 + +接下來你可以: + +- 嘗試不同語言(`OcrLanguage.Spanish`、`OcrLanguage.ChineseSimplified` 等)。 +- 將輸出整合至可搜尋的 ElasticSearch 索引。 +- 加入後處理(拼字檢查、正規表達式清理)以提升資料品質。 + +不妨在自己的發票批次上試試看,調整記憶體上限,觀察 OCR 效能的提升。祝開發順利! + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..ba0b0aed2 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. +### [OCR motor létrehozása C#‑ban – Teljes útmutató](./create-ocr-engine-in-c-complete-guide/) +Ismerje meg, hogyan hozhat létre saját OCR motort C#‑ban az Aspose.OCR segítségével, lépésről lépésre. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/hungarian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..e6f1604ee --- /dev/null +++ b/ocr/hungarian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,268 @@ +--- +category: general +date: 2026-05-25 +description: Készíts OCR-motort C#-ban, és tanuld meg, hogyan ellenőrizheted néhány + kódsorral az értékelési módot és a licenc állapotát. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: hu +og_description: Készíts OCR motor C#-ban, és azonnal lásd, hogyan lehet felismerni + az értékelési módot, valamint megjeleníteni a licenc állapotát. +og_title: OCR motor létrehozása C#‑ban – Lépésről lépésre útmutató +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: OCR motor létrehozása C#-ban – Teljes útmutató +url: /hu/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR motor létrehozása C#‑ban – Teljes útmutató + +Gondolkodtál már azon, hogyan **create OCR engine** objektumokat hozhatsz létre C#‑ban anélkül, hogy végtelen dokumentációt kellene átböngészni? Nem vagy egyedül. Sok fejlesztő akad el, amikor OCR motort kell indítania, ellenőriznie kell, hogy próbaüzemmódban fut-e, és a licenc állapotát kell megjelenítenie a felhasználók számára. + +Ebben az oktatóanyagról egy tömör, vég‑től‑végig példán keresztül vezetünk, amely **creates an OCR engine**, ellenőrzi annak **OCR engine evaluation mode**‑ját, és barátságos üzenetet ír ki a licenc állapotáról. A végére egy azonnal futtatható konzolalkalmazásod lesz, és egy világos mentális modell a OCR licenc kezeléséhez a saját projektjeidben. + +Nem szükséges külső eszköz a már telepített OCR SDK‑n kívül. Ha jártas vagy az alap C# szintaxisban, már indulhatsz. + +## Mit fogsz megtanulni + +- Hogyan példányosíts egy `OcrEngine`‑t (bármely OCR munkafolyamat központi eleme). +- Miért fontos a **evaluation mode** észlelése a megfelelőség és a felhasználói élmény szempontjából. +- A legjobb módja a **check OCR license** állapotának ellenőrzésére és a váratlan állapotokra való reagálásra. +- Gyakori buktatók – null hivatkozások, kivételkezelés és verzióeltérések. + +Nem szükséges külső eszköz a már telepített OCR SDK‑n kívül. Ha jártas vagy az alap C# szintaxisban, már indulhatsz. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Core‑dal és .NET Framework‑kel is fordítható). +- Egy OCR SDK, amely egy `OcrEngine` osztályt biztosít `IsEvaluation` tulajdonsággal (például a hipotetikus `MyOcrSdk`). +- Egy szövegszerkesztő vagy IDE (Visual Studio, VS Code, Rider – válaszd a kedvedet). + +Ennyi. Merüljünk el benne. + +## 1. lépés: Új konzolprojekt létrehozása + +Először hozz létre egy friss konzolalkalmazást, hogy a kódot izoláltan futtathasd. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Nyisd meg a generált `Program.cs` fájlt. A tartalmát egy teljes példával fogjuk felülírni, amely **creates OCR engine** példányokat hoz létre és kezeli a licencelést. + +## 2. lépés: Az OCR SDK névtér importálása + +Feltételezve, hogy az SDK a NuGet‑en keresztül van hivatkozva (`MyOcrSdk` egy helyőrző), add hozzá a using direktívát a fájl tetejére. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Ha még nem adtad hozzá a csomagot, futtasd: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tipp:** Tartsd naprakészen az SDK verziódat; az újabb kiadások gyakran javítják a evaluation‑mode felismerést. + +## 3. lépés: Az OCR motor példány létrehozása + +Most végre **create OCR engine** objektumokat hozunk létre. Ez bármely OCR munkafolyamat szíve – gondolj rá úgy, mint egy agyra, amely később képeket olvas. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Miért kulcsfontosságú ez a lépés? A `OcrEngine` magába foglalja az összes konfigurációt, nyelvi csomagot és licenc adatot. Nélküle nem tudsz képeket feldolgozni vagy lekérdezni az evaluation jelzőt. + +> **Megjegyzés:** Egyes SDK‑k lehetővé teszik, hogy konfigurációs objektumot adj át a konstruktorba (pl. nyelv, DPI). Ha egyedi beállításokra van szükséged, módosítsd a sort ennek megfelelően. + +## 4. lépés: Az OCR motor értékelési módjának meghatározása + +A legtöbb OCR szállító egy próba verziót kínál, amely **evaluation mode**‑ban fut, amíg érvényes licenckulcsot nem adsz meg. Ha tudod, hogy próbaüzemmódban vagy, megfelelő UI‑jelek megjelenítésére vagy bizonyos funkciók korlátozására használhatod. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Az `IsEvaluation` tulajdonság `true`‑t ad vissza, ha a motor nincs licencelve vagy időkorlátos próbaüzemmódban van. Ez egy gyors, megbízható módja a prémium funkciók védelmének. + +### Mi van, ha a tulajdonság hiányzik? + +A régebbi SDK verziók helyette egy `GetLicenseInfo()` metódust biztosíthatnak. Ebben az esetben a visszaadott objektumban kell keresned egy `IsTrial` jelzőt. Frissítéskor mindig nézd meg az SDK változási naplóját. + +## 5. lépés: A jelenlegi licenc állapot megjelenítése + +Végül mutassuk meg a felhasználónak, hogy a motor licencelt-e vagy még próbaüzemmódban van. Egy egyszerű console write‑line elvégzi a feladatot, de GUI‑alkalmazásokhoz is adaptálható. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +A ternary operátor rendezi a kódot, és az üzenetek elég egyértelműek a végfelhasználók vagy a naplókat olvasó fejlesztők számára. + +## Teljes működő példa + +Összegezve, itt egy önálló program, amelyet átmásolhatsz a `Program.cs`‑be, és futtathatsz a `dotnet run` paranccsal. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Várt kimenet + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +Ha az SDK kivételt dob (pl. hiányzó natív DLL), a catch blokk egy hasznos hibaüzenetet ír ki ahelyett, hogy az egész alkalmazást összeomlasztaná. + +## Szélsőséges esetek és gyakori buktatók kezelése + +### 1. Null motor példányok + +Bár a konstruktor általában érvényes objektumot ad vissza, egyes SDK‑k `null`‑t adhatnak vissza, ha a szükséges natív függőségek hiányoznak. Védd meg magad ellenük: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Licenc lejárása futás közben + +A próba licenc köztesen lejárhat. Időnként kérdezd le újra az `IsEvaluation` értéket, ha az alkalmazásod hosszú ideig fut. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Különböző tulajdonságnevek verziók között + +A régebbi kiadások `engine.EvaluationMode` vagy `engine.License.IsTrial` tulajdonságot is tartalmazhatnak. Frissítéskor keresd a SDK kiadási jegyzékében a töréspontokat. + +### 4. Többszálú helyzetek + +Ha több OCR munkavállalót indítasz, hozz létre **egy OCR engine példányt szálanként**, hacsak az SDK kifejezetten nem támogatja a szálbiztos megosztást. Egyetlen motor megosztása versenyhelyzetekhez és hibás licencolvasásokhoz vezethet. + +## Profi tippek a termeléshez + +- **Cache the licensing status** az első ellenőrzés után, hogy elkerüld a felesleges tulajdonság hívásokat. +- **Log the license key** (maszkolva) indításkor audit nyomvonalakhoz – segít a támogatási csapatnak a licenc problémák diagnosztizálásában. +- **Provide a UI toggle**, amely tájékoztatja a felhasználókat, hogy próbaüzemmódban vannak, és egy „Licenc vásárlása” gombot kínál. +- **Automate license renewal** az SDK aktivációs API‑jának használatával, ha elérhető, hogy a felhasználói élmény zökkenőmentes legyen. + +## Összegzés + +Most **created OCR engine** objektumokat néhány sorban hoztunk létre, megvizsgáltuk a **OCR engine evaluation mode**‑t, és kiírtunk egy egyértelmű **OCR licensing status** üzenetet. A teljes példa azonnal fut, hibákat elegánsan kezel, és kiemeli az egyes lépések „miértjét” – így asztali, web vagy szolgáltatás‑oldali környezetekhez is könnyen adaptálható. + +Ezután érdemes lehet felfedezni: + +- `engine.Recognize` használata képek betáplálásához és a többnyelvű támogatás kezelése. +- **check OCR license** API‑k használata a vásárolt kulcs programozott aktiválásához. +- Integráció UI keretrendszerekkel (WinForms, WPF, MAUI) a licenc jelvények megjelenítéséhez. + +Próbáld ki őket, és egy robusztus OCR alapot kapsz, amely bármilyen alkalmazáshoz készen áll. Boldog kódolást! + +## Kapcsolódó oktatóanyagok + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/ocr-optimization/_index.md b/ocr/hungarian/net/ocr-optimization/_index.md index 89201a564..8e466f5ed 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. +### [Képfeldolgozás OCR-hez – Teljes Aspose C# útmutató](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Ismerje meg, hogyan készítheti elő a képeket az OCR-hez a teljes Aspose C# útmutatóval, a legjobb szűrőkkel és beállításokkal. + ## 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/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/hungarian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..af0a7bd0d --- /dev/null +++ b/ocr/hungarian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Előfeldolgozza a képet OCR-hez az Aspose segítségével, hogy javítsa az + OCR pontosságát, és OCR-t futtasson JPEG fájlokon. Tanulja meg, hogyan lehet szöveget + kinyerni az Aspose használatával egy világos, lépésről‑lépésre útmutatóban. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: hu +og_description: Előfeldolgozza a képet OCR-hez az Aspose-szal, hogy növelje az OCR + pontosságát. Kövesse ezt az útmutatót, hogy JPEG-en OCR-t futtasson, és szöveget + nyerjen ki az Aspose segítségével C#-ban. +og_title: Kép előfeldolgozása OCR-hez – Aspose C# útmutató +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Kép előfeldolgozása OCR-hez – Teljes Aspose C# útmutató +url: /hu/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kép előfeldolgozása OCR-hez – Teljes Aspose C# útmutató + +Gondolkodtál már azon, hogyan **preprocess image for OCR**, hogy a szöveg minden alkalommal tisztán jelenjen meg? Nem vagy egyedül – a fejlesztők folyamatosan küzdenek zajos beolvasott képekkel, alacsony kontrasztú JPEG-ekkel és kiszámíthatatlan megvilágítással. A jó hír? Néhány okos trükkel **improve OCR accuracy** drámaian növelhető, és az Aspose ezt könnyedén megoldja. + +Ebben az útmutatóban egy valós példán keresztül mutatjuk be, hogyan **run OCR on JPEG** képeken, hogyan alkalmazz egy egyedi kép‑feldolgozási csővezetéket, és végül **extract text using Aspose**. A végére egy kész C# kódrészletet kapsz, amelyet bármely .NET projektbe beilleszthetsz. + +## Mit fogsz megtanulni + +- Miért fontos az előfeldolgozás, és mely szűrők hoznak a legnagyobb javulást. +- Hogyan konfiguráljuk az Aspose.OCR `ImageProcessingOptions`‑t a dőléskorrekcióhoz, zajcsökkentéshez, binarizáláshoz és kontrasztnöveléshez. +- A pontos kód, amely szükséges a **run OCR on JPEG** fájlokhoz és a tiszta szöveg lekéréséhez. +- Tippek és buktatók, amelyek a OCR csővezetékedet robusztussá teszik a termelésben. + +Az Aspose-s tapasztalat nem szükséges; elegendő egy alap C# háttér és a Visual Studio (vagy a kedvenc IDE-d). Kezdjünk is. + +![Kép előfeldolgozása OCR példája](preprocess-ocr.png "Preprocess image for OCR") + +## 1. lépés: Az Aspose.OCR motor beállítása – Preprocess Image for OCR + +Először is szükségünk van egy `OcrEngine` példányra, és meg kell adnunk, hogy melyik nyelvet várjuk. A legtöbb esetben az angol az alapértelmezett, de a `OcrLanguage` enum módosításával könnyen cserélhető francia, német stb. nyelvre. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Miért fontos:** A motor a művelet szíve; nélküle nem tudod alkalmazni a kép szűrőket, amelyek valójában **preprocess image for OCR**. Olyan, mint a konyha, ahol minden hozzávaló összekeveredik. + +## 2. lépés: Egyedi kép‑feldolgozási csővezeték felépítése – Improve OCR Accuracy + +Most jön a legízletesebb rész. Az Aspose lehetővé teszi több szűrő láncolását. Az alábbiakban négy leghatékonyabbat aktiváljuk: + +1. **Deskew** – kiegyenesíti a ferde dokumentumokat (alapértelmezés szerint legfeljebb 5°). +2. **Denoise** – simítja a szemcsés hátteret. +3. **Binarize** – a képet fekete‑fehérre konvertálja egy küszöbérték segítségével. +4. **ContrastBoost** – kiemeli a gyenge karaktereket. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tipp:** Ha a forrásképek már élesek, csökkentheted a `Strength` értékét vagy teljesen kikapcsolhatod a szűrőt. A túlzott feldolgozás néha törli a gyenge karaktereket, ezért érdemes valós mintákkal kísérletezni. + +## 3. lépés: JPEG (vagy bármilyen kép) betöltése és OCR futtatása – Run OCR on JPEG + +Az Aspose bármely, a .NET által olvasható képformátummal működik – JPEG, PNG, BMP, bármi. Íme, hogyan adsz egy JPEG fájlt a motorhoz, és indítod el a felismerési folyamatot. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Miért JPEG?** A JPEG tömörítés gyakran olyan hibákat vezet be, amelyek összezavarják az OCR-t. Az előfeldolgozó csővezetékünk, különösen a denoise és binarize lépések, enyhítik ezeket a problémákat, így magabiztosan **run OCR on JPEG**. + +## 4. lépés: Felismert szöveg kiírása – Extract Text Using Aspose + +Végül egyszerűen kiírjuk a szöveget a konzolra, egy fájlba vagy bármely downstream szolgáltatásba. Bemutató céljából a konzol elegendő. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +A program futtatásakor valami ilyesmit kell látnod: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Ha a kimenet összezavartnak tűnik, térj vissza a **2. lépéshez** és finomítsd a szűrő beállításokat. A kis módosítások gyakran nagy javulást hoznak az **improve OCR accuracy**‑ban. + +## Gyakori szélsőséges esetek és megoldásaik + +| Helyzet | Javasolt módosítás | +|-----------|----------------------| +| **Nagyon sötét képek** | Növeld a `ContrastBoost.Level` értékét 1,5‑re vagy magasabbra. | +| **Dőlés > 5°** | Emeld a `DeskewOptions.MaxAngle` értékét (pl. 10.0), vagy előre forgasd el a képet manuálisan. | +| **Színes szöveg színes háttéren** | Használd a `BinarizeOptions`‑t egy egyedi küszöbbel, vagy válts `AdaptiveBinarizeOptions`‑ra. | +| **Nagy fájlok ( > 5 MB )** | Töltsd be a képet először egy `MemoryStream`‑be, hogy elkerüld a fájlzárolási problémákat. | + +Ezek a finomítások rugalmasan és jövőbiztosan tartják a csővezetéket, különösen akkor, amikor **extract text using Aspose**‑t kell alkalmazni különféle forrásokból. + +## Teljes működő példa – Minden lépés egy helyen + +Az alábbiakban a teljes, másolás‑beillesztésre kész program látható. .NET 6+ környezetben fordul, és csak a `Aspose.OCR` NuGet csomagra van szükség. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Mentsd el `Program.cs`‑ként, add hozzá az Aspose.OCR csomagot (`dotnet add package Aspose.OCR`), majd futtasd a `dotnet run` parancsot. A tisztított szöveget a konzolon fogod látni. + +## Összefoglalás – Miért működik ez a megközelítés + +- **Preprocess image for OCR**: A csővezeték eltávolítja a leggyakoribb hibaforrásokat (dőlés, zaj, alacsony kontraszt). +- **Improve OCR accuracy**: Minden szűrő úgy van beállítva, hogy növelje a motor által látott jel‑zaj arányt. +- **Run OCR on JPEG**: Még a tömörített képek is olvashatóvá válnak a dőléskorrekció és binarizálás után. +- **Extract text using Aspose**: A `Recognize` metódus egy egyszerű stringet ad vissza, amely készen áll bármilyen downstream logikához. + +Ezek a lépések együtt egy megbízható, termelés‑szintű OCR megoldást biztosítanak néhány sor kóddal. + +## Következő lépések és kapcsolódó témák + +- **Batch processing** – Képek mappájának bejárása, és minden eredmény `.txt` fájlba írása. +- **Language packs** – Cseréld le az `OcrLanguage.English`‑t `OcrLanguage.Spanish`‑re vagy adj hozzá egyedi szótárakat. +- **PDF extraction** – Kombináld az Aspose.OCR‑t az Aspose.PDF‑vel, hogy közvetlenül a beolvasott PDF‑ekből nyerj szöveget. +- **Performance tuning** – Futtasd a motort párhuzamosan a `Parallel.ForEach`‑el nagy terhelés esetén. + +Nyugodtan kísérletezz a szűrőértékekkel, próbálj ki különböző képformátumokat, vagy láncolj további Aspose szűrőket, például `SharpnessOptions`‑t. A lehetőségek végtelenek, ha már elsajátítottad az alapokat. + +--- + +*Boldog kódolást! Ha bármilyen problémába ütközöl, hagyj megjegyzést alább, és együtt megoldjuk.* + +## Kapcsolódó oktatóanyagok + +- [Kép előfeldolgozása OCR-hez Aspose.OCR szűrőkkel .NET-hez](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Szöveg kinyerése képből – OCR optimalizálás Aspose.OCR-rel .NET-hez](/ocr/english/net/ocr-optimization/) +- [Képszöveg kinyerése C#‑ban nyelvválasztással Aspose.OCR használatával](/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/text-recognition/_index.md b/ocr/hungarian/net/text-recognition/_index.md index 61ddd9f74..dcf4444cf 100644 --- a/ocr/hungarian/net/text-recognition/_index.md +++ b/ocr/hungarian/net/text-recognition/_index.md @@ -55,9 +55,24 @@ 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. +### [Képről szöveg felismerése az Aspose OCR segítségével – Teljes C# útmutató](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Ismerje meg, hogyan használhatja az Aspose OCR-t C#-ban képek szövegének pontos felismerésére lépésről-lépésre útmutatóval. +### [Hogyan használjuk az OCR-t C#-ban – Kínai szöveg felismerése JPG-ből](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Ismerje meg, hogyan ismerhet fel kínai szöveget JPG képekről C#-ban az Aspose.OCR segítségével. +### [OCR orosz szöveg C#-ban – Teljes útmutató az Aspose OCR használatával](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Ismerje meg, hogyan használhatja az Aspose OCR-t orosz szöveg felismerésére C#-ban lépésről-lépésre útmutatóval. +### [Képről szöveg kinyerése C#-ban – Teljes Aspose OCR útmutató](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Fedezze fel, hogyan nyerhet ki szöveget képekből C#-ban az Aspose OCR teljes körű útmutatójával. +### [Szöveg kinyerése képről ASP.NET Core Minimal API-ban – Teljes útmutató](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Ismerje meg, hogyan nyerhet ki szöveget képekből ASP.NET Core Minimal API-val az Aspose.OCR segítségével, lépésről-lépésre útmutatóval. +### [c# OCR oktatóanyag: Szöveg kinyerése PNG nyugtákról az Aspose segítségével](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Ismerje meg, hogyan nyerhet ki szöveget PNG nyugtákról C#-ban az Aspose OCR használatával, lépésről-lépésre útmutatóval. +### [TIFF konvertálása szöveggé C#-ban – Teljes kötegelt OCR útmutató](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Tanulja meg, hogyan konvertálhat TIFF fájlokat szöveggé C#-ban tömeges OCR feldolgozással 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/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/hungarian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..588b60536 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,219 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR oktatóanyag, amely bemutatja, hogyan töltsünk be képfájlt c#-ban, + és hogyan ismerjünk fel png szöveget egy nyugtáról az Aspose OCR használatával – + lépésről lépésre útmutató. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: hu +og_description: c# OCR oktató, amely végigvezet a képfájl betöltésén C#-ban, és a + nyugtáról származó PNG szöveg felismerésén az Aspose OCR segítségével. +og_title: c# OCR útmutató – Szöveg kinyerése PNG nyugtákból +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR útmutató: Szöveg kinyerése PNG nyugtákról az Aspose segítségével' +url: /hu/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Szöveg kinyerése PNG nyugtákról az Aspose segítségével + +Valaha is szükséged volt egy **c# OCR tutorial**-ra, ami tényleg elvégzi a feladatot a végtelen googling nélkül? Jó helyen vagy. Ebben az útmutatóban **load image file c#**, **recognize png text**, és **read receipt OCR** eredményeket fogunk bemutatni, miközben megmutatjuk, hogyan **perform OCR image** feldolgozást végezzünk az Aspose OCR-rel. + +A szükséges NuGet csomag telepítésével kezdünk, végigvezetünk minden kódsoron, és egy rendezett JSON kiírással zárunk, amit közvetlenül beilleszthetsz a következő adatcsővezetékedbe. Nincs felesleges szó, csak egy gyakorlati, azonnal futtatható megoldás. + +## Mit fogsz megtanulni + +- Hogyan állítsd be az Aspose OCR-t egy .NET 6 (vagy újabb) projektben. +- A pontos lépések a **load an image file c#** betöltéséhez és az motorhoz való átadásához. +- Hogyan **recognize png text** egy nyugta képről, és rögzítsd az eredményt. +- Módszerek a **read receipt OCR** kimenet szép formázott JSON-ként való megjelenítésére. +- Tippek a **perform OCR image** műveletekhez különböző fájltípusokon, és a gyakori buktatók kezeléséhez. + +**Előfeltételek** +- Visual Studio 2022 (vagy bármely kedvenc IDE). +- .NET 6 SDK vagy újabb. +- Egy PNG nyugta kép kéznél (ezt `receipt.png`-nek hívjuk). + +Ha ezek megvannak, vágjunk bele. + +![c# OCR tutorial képernyőkép](ocr-demo.png "c# OCR tutorial eredmény JSON kimenettel") + +## c# OCR tutorial – Az Aspose OCR motor beállítása + +Először is szükségünk van az Aspose OCR könyvtárra. Nyisd meg a terminált a megoldás mappájában, és futtasd: + +```bash +dotnet add package Aspose.OCR +``` + +Ez az egyetlen parancs letölti a szükséges összetevőket, beleértve a natív binárisokat a képek dekódolásához. Telepítés után hozz létre egy új konzolos projektet, vagy add hozzá a kódot egy meglévőhöz. + +### Miért Aspose? + +Az Aspose OCR több mint 30 nyelvet támogat, offline működik, és egy gazdag `OcrResult` objektumot ad vissza – tökéletes **perform OCR image** feladatokhoz, ahol többre van szükség, mint egyszerű szövegre. + +## Load image file c# és a nyugta előkészítése + +Most, hogy a könyvtár készen áll, **load image file c#**. A `System.Drawing.Image` osztály végzi a nehéz munkát, de használhatod a `SkiaSharp`-ot is, ha inkább egy cross‑platform alternatívát szeretnél. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tipp:** Csomagold be az `Image`-et egy `using` utasításba (ahogy látható), hogy azonnal felszabadítsd a natív erőforrásokat – különösen fontos, ha sok fájlon **perform OCR image** végzel egy ciklusban. + +## PNG szöveg felismerése Aspose-szal + +Miután a kép a memóriában van, a motor most már **recognize png text**. Az Aspose egy `OcrResult`-et ad vissza, amely tartalmazza a nyers karakterláncot és részletes adatokat minden felismert szóról. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Miért hívod a `RecognizeWithResult`-ot a egyszerűbb `Recognize` helyett? Az előbbi hozzáférést biztosít a megbízhatósági pontszámokhoz, a keretekhez és a sortörésekhez – hasznos, ha később **read receipt OCR**-ra van szükséged sor‑elemek kinyeréséhez. + +## Receipt OCR eredmény olvasása JSON-ként + +A legtöbb downstream rendszer szereti a JSON-t, ezért sorosítsuk a `OcrResult`-et. A `System.Text.Json` sorosító elegánsan kezeli a komplex objektumokat, és bekapcsoljuk a behúzást az olvashatóság kedvéért. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Az eredményül kapott JSON valahogy így néz ki (rövidítve): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Most már a `jsonResult`-ot átirányíthatod egy adatbázisba, egy üzenetsorba, vagy egyszerűen naplózhatod hibakereséshez. + +## OCR képfeldolgozás végrehajtása és kimenet megjelenítése + +Végül írd ki a JSON-t a konzolra. Egy valós alkalmazásban valószínűleg fájlba írnád vagy HTTP-n küldenéd, de a konzol egyszerűen ellenőrizhetővé teszi, hogy minden működik. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Futtasd a programot (`dotnet run`), és látnod kell a szépen formázott JSON-t. Ha a nyugta kép tiszta, a szöveg pontos lesz; ha nem, fontold meg a kép felbontásának növelését vagy egy előfeldolgozó szűrő (pl. szürkeárnyalatos, kontraszt növelés) alkalmazását, mielőtt a motorba adod. + +### Gyakori szélhelyzetek kezelése + +| Helyzet | Mit kell tenni | +|-----------|------------| +| **A kép elmosódott** | `System.Drawing`-el előfeldolgozva élesítsd vagy növeld a DPI-t. | +| **A nyugta több nyelvet tartalmaz** | Állítsd be `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Nagy kötegelt feldolgozás** | Használd újra egyetlen `OcrEngine` példányt; csak a `Image`-et cseréld minden iterációban. | +| **Memória nyomás** | Az `Image` objektumokat azonnal szabadítsd fel, és fontold meg az `await Task.Run` használatát aszinkron csővezetékekhez. | + +## Összegzés + +Gratulálunk—éppen most fejeztél be egy **c# OCR tutorial**-t, amely betölt egy képet, **recognizes png text**, és **reads receipt OCR** kimenetet tiszta JSON-ként. A fő lépések (motor beállítása, kép betöltése, OCR végrehajtása, sorosítás és megjelenítés) szilárd alapot adnak, amelyet számlákra, útlevelekre vagy bármely más beolvasott dokumentumra bővíthetsz. + +### Mi a következő? + +- Kísérletezz a **load image file c#** `SkiaSharp` használatával a valódi cross‑platform támogatásért. +- Mélyedj el a `OcrResult.Words`-ban, hogy sor‑elemeket, árakat és dátumokat nyerj ki – tökéletes költségkövető alkalmazásokhoz. +- Kombináld ezt a tutorialt Azure Functions vagy AWS Lambda segítségével, hogy szerver nélküli nyugta‑feldolgozó API-t építs. + +Nyugodtan módosítsd a kódot, adj hozzá több képet, vagy akár válts más nyelvi csomagra. Az OCR világa tele van meglepetésekkel, és most már megvannak az eszközök a felfedezéshez. + +Boldog kódolást, és legyenek a nyugtáid mindig olvashatóak! + +## Kapcsolódó tutorialok + +- [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/) +- [Szöveg kinyerése képből – OCR optimalizálás Aspose.OCR-rel .NET-hez](/ocr/english/net/ocr-optimization/) +- [Hogyan használjuk az OCR-t – Kép felismerése szövegterület-érzékelés nélkül](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/hungarian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..1be6e3c06 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-05-25 +description: Konvertálja a TIFF fájlokat szöveggé az Aspose.OCR segítségével C#-ban. + Tanulja meg a kötegelt kép‑szöveg átalakítást, és hatékonyan nyerjen ki szöveget + TIFF fájlokból. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: hu +og_description: Konvertálja a TIFF-et szöveggé az Aspose.OCR segítségével. Ez az útmutató + bemutatja a kötegelt kép‑szöveg konverziót, valamint azt, hogyan lehet néhány C# + sorral szöveget kinyerni a TIFF fájlokból. +og_title: TIFF konvertálása szöveggé C#-ban – Teljes kötegelt OCR útmutató +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: TIFF konvertálása szöveggé C#-ban – Teljes kötegelt OCR útmutató +url: /hu/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# TIFF konvertálása szöveggé C#‑ban – Teljes kötegelt OCR útmutató + +Valaha szükséged volt **TIFF szöveggé konvertálásra**, de nem tudtad, hol kezdj? Nem vagy egyedül – sok fejlesztő elakad a kötegelt OCR‑nál, amikor beolvasott dokumentumokkal dolgozik. Ebben az útmutatóban egy gyakorlati megoldáson keresztül vezetünk, amely **kivonja a szöveget a TIFF** fájlokból az Aspose.OCR használatával, és párhuzamosan hajtjuk végre, így a nagy mappák másodpercek alatt elkészülnek. + +Érinteni fogjuk a **kötegelt kép‑szöveg konverzió** legjobb gyakorlatait is, így a végére egy újrahasználható kódrészletet kapsz, amely egy teljes könyvtár beolvasott képet átalakít rendezett *.txt* fájlokká – tökéletes indexeléshez, kereséshez vagy a további elemzésekhez. + +## Amire szükséged lesz + +- **.NET 6.0** vagy újabb (a kód .NET Framework‑ön is lefordítható) +- **Aspose.OCR for .NET** NuGet csomag (`Install-Package Aspose.OCR`) +- Egy mappa, amely egy vagy több *.tif* fájlt tartalmaz (a klasszikus TIFF‑szkennelési formátum) +- A kedvenc IDE‑d (Visual Studio, VS Code, Rider – bármi, amit kedvelsz) + +Ennyi. Nincsenek külső szolgáltatások, API kulcsok, csak tiszta C# és Aspose. + +![Képernyőkép egy feldolgozott TIFF fájlról és a keletkezett szövegfájlról](/images/ocr-result.png "OCR eredmény, amely a TIFF szöveggé konvertált kimenetet mutatja") + +*(Alt szöveg: Képernyőkép, amely a konvertált TIFF szöveggé kimenetet mutatja a képernyőn)* + +## 1. lépés: OCR motor beállítása – TIFF konvertálása szöveggé + +Először is szükségünk van egy `OcrEngine` példányra, amely tudja, hogy angol karaktereket kell olvasnia. A motor a konverzió szíve; helyes beállítása megbízható eredményeket biztosít. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Miért fontos ez:* +Az Aspose.OCR több tucat nyelvet támogat. Ha többnyelvű beolvasásról van szó, egyszerűen változtasd meg a `OcrLanguage.English` értéket a megfelelő enum értékre. Ha a nyelvet nem definiálod, a motor automatikus felismerés módba kerül, ami lassabb és kevésbé pontos lehet. + +## 2. lépés: Összes TIFF fájl összegyűjtése – Hatékony szövegkinyerés TIFF‑ből + +Ezután minden *.tif* fájlt lekérünk egy általad megadott mappából. A `Directory.GetFiles` használata egy tiszta tömböt ad, amelyet a kötegelt feldolgozóba táplálhatunk. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro tipp:* A `SearchOption.AllDirectories` jelző használható, ha a beolvasásaid almappákban vannak. Csak ne feledd, hogy a mélyebb rekurzió növelheti a memóriahasználatot a kötegelt lépés során. + +## 3. lépés: Párhuzamos OCR végrehajtása – Kötegelt kép‑szöveg konverzió + +Most jön a szórakoztató rész. Az Aspose.OCR egy statikus segédfüggvényt tartalmaz, a `BatchOcr.RecognizeAll`‑t, amely egy fájlútvonalak tömbjét, egy motort és egy `parallelism` tippet fogad. Négy szálat indítunk, ami egy modern négymagos laptopon közel lineáris gyorsulást eredményez. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Miért a párhuzamosság?* +Nagy felbontású TIFF‑k kötegének beolvasása CPU‑igényes lehet. A munka több szálra osztásával minden magot foglalkoztatunk, így drámaian csökkentve az összidőt. Ha szerveren több maggal futtatod, növeld a `parallelism` értékét ennek megfelelően. + +## 4. lépés: Kimenet írása – Beolvasott képek TXT fájlokká konvertálása + +Végül végigiterálunk a szótáron, és minden szövegrészt egy *.txt* fájlba írunk, amely az eredeti alapnevet viseli. Ez az a pillanat, amikor a **convert scanned images txt** valósággá válik. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Mit csinál a kód, egyszerűen magyarul + +1. **Create** egy angol nyelvre beállított OCR motort. +2. **Collect** minden TIFF fájlt a célmappából. +3. **Run** a `BatchOcr.RecognizeAll`‑t négy szállal, minden képet karakterlánccá alakítva. +4. **Loop** a eredmények felett, a `.tif` kiterjesztést `.txt`‑re cserélve, és a karakterláncot lemezre írva. + +Ez a teljes **convert TIFF to text** munkafolyamat kevesebb, mint 50 kódsorban. + +## Szélsőséges esetek kezelése – Amikor a dolgok nem mennek simán + +- **Missing or corrupted TIFFs** – a `BatchOcr` `OcrException`‑t dob. Ha szükséged van a hibamentes visszaesésre, tedd a hívást egy `try / catch` blokkba. +- **Non‑English documents** – változtasd a `OcrLanguage.English`‑t `OcrLanguage.Spanish`, `OcrLanguage.French` stb. értékre, vagy használd a `OcrLanguage.AutoDetect`‑et. +- **Very large images** – fontold meg a DPI csökkentését OCR előtt (`ocrEngine.ImagePreprocessing.Dpi = 200`), hogy memóriát takaríts meg, bár ez csökkentheti a pontosságot. +- **Output encoding** – ha egy adott kódlapra (pl. Windows‑1252) van szükséged, add át a `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`‑nek. + +## Profi tippek a robusztus kötegelt konverziókhoz + +- **Log failures**: hozz létre egy `List failedFiles` listát, és adj hozzá minden olyan fájlt, amely hibát dob; a ciklus után írd ki a listát egy naplóba. +- **Reuse the engine**: ugyanaz a `OcrEngine` példány újra felhasználható sok fájl esetén; ne hozd létre a cikluson belül. +- **Validate the result**: egy egyszerű `if (string.IsNullOrWhiteSpace(extractedText))` jelzi a üres vagy olvashatatlan beolvasásokat. +- **Combine with PDF**: ha a forrásod egy többoldalas PDF, először konvertáld minden oldalt TIFF‑re (az Aspose.PDF ezt megteszi), majd futtasd le ezt a köteget. + +## Következő lépések – A egyszerű konverzión túl + +Most, hogy tömegesen **extract text from TIFF** fájlokból tudsz szöveget kinyerni, lehet, hogy szeretnéd: + +- A *.txt* fájlokat egy keresőindexbe (Elasticsearch, Azure Cognitive Search) betáplálni. +- Minden eredményen nyelvfelismerést futtatni, hogy a dokumentumokat helyi specifikus folyamatokba irányítsuk. +- Kereshető PDF‑eket generálni az OCR szöveget visszahelyezve az eredeti képekre (újra az Aspose.PDF‑vel). + +Mindez ugyanarra az alapötletre épül: a **batch image to text conversion** egy építőköve a nagyobb dokumentum‑feldolgozó rendszereknek. + +--- + +### Következtetés + +Most megtanultad, hogyan **convert TIFF to text** az Aspose.OCR használatával, egy teljes mappát párhuzamosan feldolgozni, és minden eredményt tiszta *.txt* fájlként menteni. A megoldás könnyű, teljesen konfigurálható, és készen áll a termelésre – akár régi számlákat digitalizálsz, beolvasott szerződéseket archiválsz, vagy egy szövegkereső motorral működtetsz. + +Próbáld ki, finomítsd a párhuzamosságot, és kezd el a frissen létrehozott szövegfájlokat a szükséges munkafolyamatba betáplálni. Boldog OCR‑olást! + +--- + +## Kapcsolódó útmutatók + +- [Szöveg kinyerése képekből OCR művelettel mappákon](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Szöveg kinyerése képből – OCR optimalizálás Aspose.OCR for .NET használatával](/ocr/english/net/ocr-optimization/) +- [Képszöveg kinyerése C#‑ban nyelvválasztással az Aspose.OCR segítségével](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/hungarian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..d2528db50 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Tanulja meg, hogyan lehet szöveget kinyerni egy képből egy minimális + ASP.NET Core API-val. Töltsön fel képet POST-kéréssel, olvassa a multipart űrlap + adatokat, és hajtson végre OCR-t a képen. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: hu +og_description: Szöveg kinyerése képből egy minimalista ASP.NET Core API segítségével. + Ez az útmutató bemutatja, hogyan töltsünk fel képet POST kéréssel, hogyan olvassuk + a multipart űrlap adatokat, és hogyan hajtsunk végre OCR-t a képen. +og_title: Szöveg kinyerése képből ASP.NET Core-ban – Lépésről lépésre +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Képből szöveg kinyerése ASP.NET Core Minimal API-ban – Teljes útmutató +url: /hu/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kép szövegének kinyerése ASP.NET Core Minimal API‑val – Teljes útmutató + +Gondolkodtál már azon, hogyan **extract text from image** anélkül, hogy nehéz keretrendszerekkel bajlódnál? Nem vagy egyedül. Sok fejlesztőnek gyors megoldásra van szüksége, hogy a felhasználók egy képet feltölthessenek, és visszakapják a nyers karaktereket, legyen szó számlák beolvasásáról, kézírásos jegyzetek digitalizálásáról vagy keresőindex működtetéséről. + +Ebben az útmutatóban egy apró ASP.NET Core Minimal API‑t hozunk létre, amely **uploads image via POST**, feldolgozza a *multipart/form‑data* terhet, majd **perform OCR on image** egy singleton `OcrEngine` segítségével. A végére egy teljesen futtatható alkalmazásod lesz, amelyet bármely .NET 8 projektbe beilleszthetsz, és azonnal elkezdhetsz **extract text from image**. + +## Mit fogsz építeni + +- Egy minimal web app, amely a `/ocr` útvonalra figyel. +- Egy végpont, amely egy `multipart/form-data` POST kérésben küldött képfájlt fogad. +- Logika, amely beolvassa a feltöltött fájlt, átadja az OCR motornak, és egyszerű szöveges eredményt ad vissza. +- Opcionális GPU gyorsítási kódrészlet (kikommentezve) azok számára, akiknek kompatibilis kártyájuk van. + +**Előfeltételek** +- .NET 8 SDK (vagy újabb). +- Alapvető ismeretek C#‑ban és a parancssorban. +- Egy OCR könyvtár, amely egy `OcrEngine` osztályt biztosít (a példa egy hipotetikus NuGet csomagot feltételez). + +Ha ezek megvannak, vágjunk bele. + +## 1. lépés: A projekt beállítása és az OCR csomag hozzáadása + +Először hozz létre egy új webprojektet, és húzd be az OCR könyvtárat. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro tipp:** Tartsd naprakészen a függőségeket. Az újabb verziók gyakran hoznak teljesítményjavulást, különösen a GPU‑gyorsított következtetés esetén. + +## 2. lépés: Singleton OCR motor regisztrálása (elsődleges szolgáltatás) + +Egyetlen `OcrEngine` példányt szeretnénk az egész alkalmazás számára – nincs szükség új motor indítására kérésenként. Regisztráld a builder szolgáltatáskontejnerében. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Miért singleton?** +Egy OCR motor létrehozása költséges lehet – gondolj a neurális hálózat súlyainak memóriába töltésére. Az ugyanazon példány újrafelhasználásával CPU‑ciklusokat és RAM‑ot takarítunk meg, ami gyorsabb válaszidőt jelent minden `/ocr` hívásnál. + +## 3. lépés: Az alkalmazás felépítése + +Most megvalósítjuk a `WebApplication` objektumot. + +```csharp +var app = builder.Build(); +``` + +Ez a sor szinte varázslatosnak tűnik, de a háttérben felállítja a routingot, a middleware‑t és a DI konténert, amelyet épp konfiguráltunk. + +## 4. lépés: A POST végpont definiálása – „Upload Image via POST” + +Itt van az útmutató szíve: egy végpont, amely **upload image via POST**, beolvassa a multipart terhet, és átadja az adatot az OCR motornak. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### A logika részletezése + +| Lépés | Mi történik | Miért fontos | +|------|--------------|----------------| +| **ReadFormAsync** | Feldolgozza a bejövő *multipart/form-data* kérést. | Enélkül nem férhetsz hozzá a feltöltött fájlokhoz. | +| **form.Files["image"]** | Lekéri azt a fájlt, amelynek a form‑field neve `image`. | Biztosítja a hívók számára a kiszámítható szerződést. | +| **Content‑type ellenőrzés** | Ellenőrzi, hogy a fájl kép (pl. `image/png`). | Megakadályozza, hogy az OCR motor ne képes legyen nem‑képadatokon. | +| **Image.FromStream** | Átalakítja a nyers streamet `System.Drawing.Image`‑dé. | Az OCR könyvtár egy `Image` objektumot vár, nem nyers byte‑tömböt. | +| **ocr.Recognize(img)** | Az OCR motor meghívása a **how to recognize text from image**-re. | Ez a fő **perform OCR on image** lépés. | +| **Results.Text** | Visszaküldi az egyszerű szöveges választ. | Egyszerű, fogyasztható formátum a downstream szolgáltatások számára. | + +## 5. lépés: Az API futtatása + +Végül indítsd el a webkiszolgálót. + +```csharp +app.Run(); +``` + +Amikor a `dotnet run` parancsot futtatod, az API a `http://localhost:5000` (vagy általad választott port) címen fog figyelni. Tesztelheted `curl`‑lel: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Várható kimenet:** A konzol kiírja a felismert karaktereket, például: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Ha a kép homályos vagy a nyelv nem támogatott, az OCR motor egy üres stringet vagy hibaüzenetet ad vissza – ezeket az eseteket kezeld a produkciós kódban. + +## Szélsőséges esetek és legjobb gyakorlatok + +### 1. Nagy fájlok + +Az alapértelmezett kérés‑test limit 30 MB. Nagyobb beolvasásokhoz lehet, hogy módosítanod kell: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Aszinkron OCR + +Néhány OCR könyvtár aszinkron metódusokat (`RecognizeAsync`) biztosít. Ha a tiéd is, cseréld le a `ocr.Recognize(img)`‑t `await ocr.RecognizeAsync(img)`‑re, és jelöld a lambda‑t `async`‑ként. + +### 3. Biztonsági megfontolások + +- **Érvényesítsd a fájlméretet** a memóriába töltés előtt. +- **Tisztítsd meg a fájlnevet** ha valaha leírod a lemezre. +- **Rate‑limit** a végpontot a szolgáltatásmegtagadási támadások elkerülése érdekében. + +### 4. GPU gyorsítás + +Ha kikommentezed a `engine.GpuDevice = new GpuDevice(0);` sort, és a hardvered támogatja a CUDA‑t vagy a DirectML‑t, jelentős sebességnövekedést fogsz látni, különösen nagy felbontású képeknél. + +## Teljes működő példa + +Az alábbiakban a teljes `Program.cs` található, amelyet beilleszthetsz egy új Minimal API projektbe. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Mentsd el, futtasd a `dotnet run`‑t, és készen állsz a **extract text from image** igény szerint. + +## Következtetés + +Áttekintettünk egy **complete, end‑to‑end solution**‑t a kép szövegének kinyerésére ASP.NET Core Minimal API‑val. A projekt felépítésétől kezdve **registered a singleton OCR engine**, felépítettünk egy végpontot, amely **uploads image via POST**, **read multipart form data**, és végül **perform OCR on image**, hogy tiszta egyszerű szöveget adjon vissza. + +Innen tovább: + +- Adj hozzá JSON burkolókat a gazdagabb válaszokért. +- Csatlakoztass egy adatbázist a kinyert szöveg tárolásához. +- Bővítsd a támogatást több nyelvre (`OcrLanguage.Spanish`, stb.). + +A minta jól skálázható – egyszerűen helyezd el ugyanazt a végpontot egy nagyobb mikroszolgáltatásba, vagy tedd elérhetővé egy API gateway mögött. + +Van kérdésed a PDF‑ek kezelésével, kötegelt feldolgozással vagy GPU hangolással kapcsolatban? Írj egy megjegyzést, és jó kódolást! + +## Kapcsolódó útmutatók + +- [Kép szövegének kinyerése Aspose.OCR .NET használatával](/ocr/english/net/image-and-drawing-recognition/) +- [Kép szövegének kinyerése – OCR optimalizálás Aspose.OCR .NET‑hez](/ocr/english/net/ocr-optimization/) +- [Kép szövegének kinyerése C#‑ben nyelvválasztással Aspose.OCR használatával](/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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/hungarian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..db1cf3812 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-05-25 +description: Képből szöveg kinyerése C# és az Aspose OCR segítségével. Tanulja meg, + hogyan konvertálja a jpg-t szöveggé, hogyan töltse be a képet OCR-hez, és hogyan + érhet el gyorsan megbízható eredményeket. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: hu +og_description: Szöveg kinyerése képből C#-val. Ez az útmutató bemutatja, hogyan konvertáljunk + JPG-t szöveggé, hogyan töltsünk be képet OCR-hez, és hogyan kezeljünk többnyelvű + tartalmat. +og_title: Képből szöveg kinyerése C#-ban – Aspose OCR útmutató +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Szöveg kinyerése képből C#-ban – Teljes Aspose OCR útmutató +url: /hu/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Kép szövegének kinyerése C#‑ban – Teljes Aspose OCR útmutató + +Gondolkodtál már azon, hogyan **extract text from image** egyszerű C# kóddal? Nem vagy egyedül. Akár nyugtákat digitalizálsz, táblákat szkennelsz, vagy csak kíváncsi vagy az OCR-re, a kép karaktereinek kinyerése hasznos képesség. Ebben az útmutatóban egy teljes, futtatható példán keresztül mutatjuk be, hogyan **extract text from image** a Aspose.OCR-rel, és kitérünk arra is, hogyan **convert jpg to text**, **load image for OCR**, és megválaszoljuk a klasszikus “**how to ocr image**” kérdést egyszer és mindenkorra. + +A útmutató végére egy önálló konzolalkalmazásod lesz, amely JPEG fájlt olvas be, ukrán (vagy bármely más támogatott nyelvet) felismer, és kiírja az eredményt a konzolra. Nincs homályos hivatkozás, nincs hiányzó rész – csak egy teljes megoldás, amelyet másolhatsz‑beilleszthetsz és futtathatsz. + +--- + +## Mit fogsz megtanulni + +* Hogyan telepítsd az Aspose.OCR NuGet csomagot. +* A pontos kód, amelyre szükség van a **load image for OCR** C#‑ban. +* Hogyan állítsd be a nyelvet, és ténylegesen **extract text from image**. +* Trükkök a **convert jpg to text** hatékonyan. +* Gyakori buktatók és azok elkerülése. + +Ha már van .NET fejlesztői környezeted beállítva, készen állsz a merülésre. Ellenkező esetben az alábbi előkövetelmények szekció felkészít. + +--- + +## Előkövetelmények + +| Requirement | Why it matters | +|-------------|----------------| +| .NET 6.0 SDK (or newer) | A konzolalkalmazás futtatásához szükséges runtime-et biztosítja. | +| Visual Studio 2022 or VS Code | Könnyebbé teszi a szerkesztést és a hibakeresést. | +| Internet connection (first run) | A NuGet-nek le kell töltenie az Aspose.OCR-t. | +| A JPEG image you want to process (e.g., `ukrainian_sign.jpg`) | Az OCR motor forrásfájlja. | + +> **Pro tipp:** Ha Linuxon vagy macOS-en vagy, ugyanaz a kód működik a .NET CLI‑val (`dotnet new console`), így nyugodtan kihagyhatod a nehéz IDE‑t. + +--- + +## 1. lépés – Aspose.OCR telepítése NuGet‑en keresztül + +Open your terminal (or Package Manager Console) and run: + +```bash +dotnet add package Aspose.OCR +``` + +Ez az egyetlen sor letölti a legújabb Aspose.OCR binárisokat és az összes tranzitív függőséget. Kézi DLL‑kezelés nem szükséges. + +--- + +## 2. lépés – OCR motor létrehozása (a kinyerés szíve) + +Miután a könyvtár rendelkezésre áll, létrehozhatunk egy `OcrEngine` példányt. Ez az objektum felelős a **extracting text from image** adatokért. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Miért fontos:** A motor magába foglalja az OCR algoritmusokat, nyelvi modelleket és konfigurációs beállításokat. Egyszeri példányosítása és több kép esetén való újrahasználata memóriahatékony és gyors. + +--- + +## 3. lépés – Kép betöltése OCR‑hez (és a nyelv beállítása) + +A következő lépés, hogy megmondjuk a motornak, melyik képet olvassa be. Itt jön képbe a **load image for OCR** kifejezés. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Szélsőséges eset:** Ha a fájl nem létezik, az `Image.FromFile` `FileNotFoundException`‑t dob. A hívást érdemes try‑catch blokkba tenni a produkciós kódban. + +--- + +## 4. lépés – OCR végrehajtása és szöveg kinyerése + +Miután a kép betöltődött, a motor most már **extract text from image**. A `Recognize` metódus végzi a nehéz munkát. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Ha minden rendben megy, a `recognizedText` tartalmazni fogja a OCR motor által olvasott szöveg egyszerű szöveges reprezentációját. + +--- + +## 5. lépés – JPG konvertálása szöveggé (összeállítás) + +Az eddig felépített kód már **convert jpg to text**, de csomagoljuk be egy rendezett metódusba, amelyet többször is meghívhatsz. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Most egyszerűen ezt teheted: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Várható kimenet** (rövidítve a tömörség kedvéért): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Ha a kép angol szöveget tartalmaz, módosítsd `OcrLanguage.English`‑re, és a megfelelő kimenetet fogod látni. + +--- + +## 6. lépés – Gyakori “How to OCR Image” kérdések kezelése + +### 6.1 OCR‑zhetek PNG‑t vagy BMP‑t? + +Természetesen. Az `Image.FromFile` metódus támogatja a System.Drawing által felismert összes formátumot, így csak a `.png` vagy `.bmp` fájlra mutasd az elérési utat, a kód többi része változatlan marad. + +### 6.2 Mi van, ha a kép alacsony felbontású? + +Az OCR pontossága drámaian csökken 300 dpi alatt. Egy gyors megoldás, hogy a képet `Graphics`‑szel felskálázzuk, mielőtt a motorba adnánk: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Szükségem van licencre az Aspose.OCR‑hez? + +Az Aspose ingyenes próbaidőszakot kínál vízjellel. Produkciós használathoz vásárolj licencet és add hozzá: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Teljes működő példa + +Az alábbiakban egy teljes, azonnal futtatható konzolalkalmazás látható, amely bemutatja, hogyan **how to OCR image**, **load image for OCR**, és **convert jpg to text** egy rendezett csomagban. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Hogyan futtasd** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +A konzolon meg kell jelennie a kinyert szövegnek, ami megerősíti, hogy sikeresen **extract text from image** C#‑ban. + +--- + +## Gyakori buktatók és pro tippek + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| Blank output | A kép túl sötét vagy alacsony kontrasztú. | Előfeldolgozás `Bitmap`‑tel a fényerő növeléséhez. | +| Wrong language | A `Language` tulajdonság alapértelmezett angol maradt. | Explicit módon állítsd be `ocrEngine.Language = OcrLanguage.Ukrainian;` (vagy a kívánt nyelvet). | +| Out‑of‑memory error | Nagyon nagy képek betöltése felszabadítás nélkül. | Az `Image.FromFile`-t `using` blokkba helyezd (ahogy a példában látható). | +| License watermark | Próba verzióval futtatás licenc nélkül. | A licencet már a `Main` elején alkalmazd. | + +--- + +## Összegzés + +Most már mindent lefedtünk, amire szükséged van a **extract text from image** C#‑ban – az Aspose.OCR telepítésétől, a **loading image for OCR**‑ig, a **convert jpg to text**‑ig és a többnyelvű helyzetek kezeléséig. A teljes mintaprogram összekapcsolja ezeket a részeket, megbízható alapot biztosítva bármely OCR‑hoz kapcsolódó projekthez. + +Ezután érdemes lehet: + +* **How to OCR image** adatfolyamok használata fájlok helyett (használd a `MemoryStream`‑et). +* **c# image to text** utófeldolgozás hozzáadása, például helyesírás-ellenőrzés. +* Az OCR lépés integrálása egy nagyobb folyamatba (pl. az eredmények adatbázisba mentése). + +Nyugodtan kísérletezz különböző nyelvekkel, képformátumokkal és előfeldolgozási trükkökkel. Az OCR annyira művészet, mint tudomány, és minél többet játszol vele, annál jobb eredményeket kapsz. + +Boldog kódolást, és legyenek a képeid mindig olvashatóak! + +## Kapcsolódó oktatóanyagok + +- [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 szövegének kinyerése – OCR optimalizálás Aspose.OCR-rel .NET‑hez](/ocr/english/net/ocr-optimization/) +- [Hogyan nyerjünk ki szöveget képből téglalapok előkészítésével az OCR‑ban](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/hungarian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..19734c4be --- /dev/null +++ b/ocr/hungarian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: Hogyan használjuk az OCR-t C#-ban a képfájlok szövegének kinyeréséhez. + Tanulja meg, hogyan ismerje fel a kínai karaktereket egy JPG-ből az Aspose.OCR segítségével + néhány egyszerű lépésben. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: hu +og_description: Hogyan használjuk az OCR-t C#-ban a képfájlok szövegének kinyeréséhez. + Ez az útmutató megmutatja, hogyan ismerhetjük fel a kínai karaktereket egy JPG-ből + az Aspose.OCR segítségével. +og_title: Hogyan használjunk OCR-t C#-ban – Kínai szöveg felismerése JPG-ből +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Hogyan használjuk az OCR-t C#-ban – Kínai szöveg felismerése JPG-ből +url: /hu/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hogyan használjunk OCR-t C#-ban – Kínai szöveg felismerése JPG-ből + +Gondolkodtál már azon, **hogyan használjunk OCR-t**, hogy szavakat nyerjünk ki egy telefonoddal készített képből? Nem vagy egyedül. Sok valós projektben – gondoljunk csak a nyugtaolvasókra, fordító alkalmazásokra vagy az automatikus adatbevitelre – gyorsan és megbízhatóan kell **szöveget kinyerni képfájlokból**. + +Ebben az útmutatóban egy teljes, futtatható példán keresztül vezetünk végig, amely **felismeri a szöveget JPG** fájlokból, és még a **kínai karakterek felismerésének** nehéz esetét is kezeli a **OCR Chinese Simplified** nyelvi csomag használatával. A végére egy önálló konzolos alkalmazásod lesz, amely a felismert karakterláncot a konzolra írja, extra manuális letöltések nélkül. + +> **Gyors megjegyzés:** A kód az Aspose.OCR ≥ 23.7 verzióval működik, amely első használatkor automatikusan letölti a nyelvi erőforrásokat. Ha régebbi verziót használsz, manuálisan kell hozzáadnod a nyelvet. + +## Előfeltételek + +Mielőtt belevágnánk, győződj meg róla, hogy rendelkezel: + +- .NET 6.0 SDK vagy újabb (a példa a .NET 6-ra céloz, de a .NET 5 is működik) +- A Visual Studio 2022 vagy VS Code legújabb verziója C# kiegészítővel +- Internetkapcsolat az első nyelvi letöltéshez +- Egy JPG kép, amely egyszerűsített kínai szöveget tartalmaz (ezt `chinese_sign.jpg`‑nek hívjuk) + +Ennyi—nincs nehéz OCR motor, nincs natív DLL manipuláció. Csak néhány NuGet parancs és néhány sor kód. + +## 1. lépés: Aspose.OCR telepítése NuGet-en keresztül + +Először is szükségünk van az OCR könyvtárra. Nyiss egy terminált a projekt mappádban, és futtasd: + +```bash +dotnet add package Aspose.OCR +``` + +Vagy ha a Visual Studio felületet részesíted előnyben, jobb‑kattints a **Dependencies → Manage NuGet Packages** menüre, keresd meg az “Aspose.OCR”‑t, és kattints a **Install** gombra. + +> **Pro tipp:** Tartsd naprakészen a csomagjaidat. Új nyelvi csomagok és teljesítményjavítások minden kisebb kiadásban megjelennek. + +## 2. lépés: Új konzolos projekt létrehozása (ha még nincs) + +Ha a semmiből indulsz, hozz létre egy új konzolos alkalmazást: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Most már van egy `Program.cs` fájlod, amely készen áll az OCR kódra. + +## 3. lépés: Az OCR kód megírása – Egyszerűsített kínai felismerése JPG-ből + +Nyisd meg a `Program.cs`‑t, és cseréld le a tartalmát a következőre. Minden sor meg van magyarázva, hogy lásd *miért* csináljuk az adott lépést, ne csak *mit* csinálunk. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Mi történik a háttérben? + +- **`OcrEngine.Language`** megmondja az Aspose-nak, melyik szótárat használja. A `ChineseSimplified` kiválasztásával azt utasítjuk a motorra, hogy keresse az egyszerűsített kínai nyelvi csomagot. +- **Első alkalommal történő letöltés**: Amikor a `Recognize` fut, az SDK kapcsolatba lép az Aspose CDN‑jével, letölti a ≈6 MB-os nyelvi fájlt, helyileg gyorsítótárazza, majd folytatja az OCR‑t. A későbbi hívások azonnaliak. +- **`Image.FromFile`** bármilyen raster formátummal működik, amelyet a .NET képes dekódolni – JPG, PNG, BMP – így **szöveget nyerhetsz ki képfájlokból** sokféle típusból, nem csak JPG‑ből. + +## 4. lépés: Az alkalmazás futtatása és a kimenet ellenőrzése + +Építsd és futtasd: + +```bash +dotnet run +``` + +Valami ilyesmit kell látnod: + +``` +=== Recognized Text === +欢迎光临 +``` + +Ha a konzol értelmetlen szöveget vagy üres karakterláncot ír, ellenőrizd a következőket: + +1. A kép valóban tiszta, nagy kontrasztú kínai karaktereket tartalmaz. +2. A fájl útvonala helyes (nincsenek felesleges szóközök vagy hiányzó kiterjesztések). +3. A géped el tudja érni a `https://download.aspose.com` címet a nyelvi csomaghoz. + +## 5. lépés: Szélsőséges esetek és gyakori hibák kezelése + +### 5.1 Alacsony minőségű képek kezelése + +Az OCR pontossága csökken, ha a forráskép elmosódott, zajos vagy rossz megvilágítású. Egy gyors megoldás a kép előfeldolgozása: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Futtatás fej nélküli környezetben + +Ha Linux konténerbe telepítesz GUI nélkül, győződj meg róla, hogy a `libgdiplus` könyvtár (amely a `System.Drawing`‑hez szükséges) telepítve van: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 A nyelvi csomag manuális gyorsítótárazása + +Letöltheted a nyelvi fájlt egyszer, és az `License` API‑val megadhatod az Aspose‑nak, így elkerülve az egyszeri hálózati hívást. Ez offline helyzetekben hasznos. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Teljes működő példa (mindegy egyben) + +Az alábbi *teljes* programot másolhatod be a `Program.cs`‑be. Nincs rejtett rész, nincs külső szkript. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Várt kimenet + +Ha a JPG a “欢迎光临” kifejezést tartalmazza, a konzol kiírja: + +``` +=== Recognized Text === +欢迎光临 +``` + +Nyugodtan cseréld le a képet bármely más egyszerűsített kínai jelre, utcanevre vagy termékcímkére – a motor a legjobbat fogja nyújtani. + +## Következtetés + +Most bemutattuk, **hogyan használjunk OCR-t** C#‑ban a **szöveg kinyeréséhez képfájlokból**, különösen a **kínai karakterek felismerésének** kihívását egy **JPG**‑ben. Az Aspose.OCR on‑the‑fly nyelvi letöltésének kihasználásával könnyű maradhat a telepítés, miközben natívan támogatja a **OCR Chinese Simplified**‑t. + +Mi a következő? Próbáld ki ezeket az ötleteket: + +- **Kötegelt feldolgozás**: Egy mappában lévő képeken iterálj, és írd az eredményeket CSV‑be. +- **Kombinálás fordító API‑kkal**: A felismert karakterláncot küldd az Azure Translator‑nek valós idejű többnyelvű alkalmazásokhoz. +- **Más nyelvek felfedezése**: Cseréld le a `OcrLanguage.ChineseSimplified`‑t `Japanese`‑ra vagy `Arabic`‑ra, és nézd meg, hogyan alkalmazkodik a kód. + +Van kérdésed a teljesítményhangolással, licenceléssel vagy az OCR webszolgáltatásba való integrálásával kapcsolatban? Írj egy megjegyzést alább – jó kódolást! + +--- + +![Konzol kimenet képernyőképe, amely bemutatja, hogyan használjunk OCR-t C#-ban kínai szöveg felismeréséhez JPG képből](ocr-chinese-demo.png "hogyan használjunk OCR konzol kimenetet") + +## Kapcsolódó útmutatók + +- [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/) +- [szöveg felismerése képen több nyelvhez az Aspose OCR-rel](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Hogyan nyerjünk ki szöveget képből téglalapok előkészítésével az OCR-ben](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/hungarian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/hungarian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..3578b167a --- /dev/null +++ b/ocr/hungarian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Tanulja meg, hogyan használjon OCR-t orosz szöveghez C#‑ban, és hogyan + nyerjen ki szöveget képből az Aspose OCR segítségével. Lépésről‑lépésre kód a kép + szöveggé gyors konvertálásához C#‑ban. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: hu +og_description: Az orosz szöveg OCR-e C#-ban egyszerű. Tanulja meg, hogyan lehet szöveget + kinyerni képből, képet szöveggé konvertálni C#-ban, és képet betölteni OCR-hez az + Aspose OCR-rel. +og_title: Orosz szöveg OCR C#-ban – Teljes Aspose OCR útmutató +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR orosz szöveg C#-ban – Teljes útmutató az Aspose OCR használatához +url: /hu/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR orosz szöveg C#‑ban – Teljes útmutató az Aspose OCR használatával + +Valaha szükséged volt arra, hogy orosz szöveget OCR‑elj C#‑ban, de nem tudtad, melyik könyvtárban bízhatsz? Nem vagy egyedül. A tiszta, olvasható karakterek kinyerése egy cirill képből úgy érezhető, mintha titkos üzeneteket fejtenél meg – különösen, ha nem állítottad be a megfelelő nyelvi modellt. + +Ebben az oktatóanyagban egy gyakorlati példán keresztül mutatjuk be, hogyan **extract text from image** fájlokból, hogyan konvertálj *image to text C#* stílusban, és hogyan kezeld az orosz nyelv felismerésének sajátosságait az Aspose OCR-rel. A végére egy azonnal futtatható konzolalkalmazásod lesz, amely betölti a képet OCR‑hez, kiírja a felismert karakterláncot, és szilárd alapot ad a fejlettebb forgatókönyvekhez. + +## Mit fogsz megtanulni + +- Hogyan telepítsd és konfiguráld a **Aspose OCR C#**‑t az orosz nyelvi támogatáshoz. +- A pontos lépések a **load image for OCR** elvégzéséhez és a motor meghívásához. +- Tippek a gyakori buktatók kezeléséhez, mint a hiányzó nyelvi erőforrások vagy a homályos beolvasások. +- Módszerek a megoldás kibővítésére, például több fájl kötegelt feldolgozása vagy a megbízhatósági küszöbök finomhangolása. + +Az Aspose‑szal kapcsolatos előzetes tapasztalat nem szükséges; egy alapvető ismeret a C#‑ról és a .NET‑ről már elegendő a kezdéshez. + +## Előfeltételek + +Mielőtt belemerülnénk, győződj meg róla, hogy a következőkkel rendelkezel: + +1. **.NET 6.0** (vagy újabb) SDK telepítve – a kód mind .NET Core‑on, mind .NET Framework‑ön működik. +2. **Visual Studio 2022** (vagy bármely kedvelt IDE). +3. Egy **Aspose.OCR for .NET** NuGet csomag – ingyenes próbaverzió kulcsot szerezhetsz az Aspose weboldaláról. +4. Egy **Russian language model** fájl (`rus.traineddata`) – töltsd le az Aspose erőforrás oldaláról, és helyezd el egy mappában, amelyre később hivatkozol. +5. Egy mintakép (`russian_doc.png`) tiszta cirill szöveggel. + +Megvan mindez? Remek – kezdjünk is bele. + +## 1. lépés: A projekt beállítása és az Aspose OCR telepítése + +Először hozz létre egy új konzolprojektet: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Ezután add hozzá az Aspose OCR csomagot: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Ha próbaverziós licencet használsz, tartsd kéznél az `Aspose.Total.lic` fájlt; a kódban betöltöd, hogy elkerüld a vízjeleket. + +Miután a csomag telepítve van, nyisd meg a `Program.cs`‑t. Látni fogod az alapértelmezett `Main` metódust – cseréld le a tartalmát a felépítendő vázra. + +## 2. lépés: Az OCR motor konfigurálása orosz nyelvhez + +A művelet szíve a `OcrEngine` objektum. Két dolgot kell megadnunk: melyik nyelvet ismerje fel, és hol találhatók a nyelvi modell fájlok. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Why this matters:** Ha kihagyod a `Language = OcrLanguage.Russian` beállítást, a motor alapértelmezés szerint angolt használ, és a cirill karakterek összezavart szimbólumokként jelennek meg. A `ResourceFolder` arra a könyvtárra mutat, amely a `rus.traineddata` fájlt tartalmazza; enélkül az Aspose *resource not found* kivételt dob. + +## 3. lépés: Kép betöltése OCR‑hez + +Most be kell **load image for OCR**. Az Aspose OCR a `System.Drawing.Image`‑del dolgozik, így bármely támogatott formátumot (PNG, JPEG, BMP, stb.) átadhatsz. Győződj meg róla, hogy a fájl útvonala helyes; relatív utak is működnek, ha a képet a végrehajtható mellé helyezed. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** Ha a kép nagy (több mint 5 MB), érdemes először lecsökkenteni. Az OCR pontossága csökken, ha a DPI túl alacsony, de a hatalmas fájlok memória nyomást okozhatnak. Egy gyors átméretezés elvégezhető a `Graphics`‑szel, ha szükséges. + +## 4. lépés: Szöveg felismerése – Képből szöveg C#‑stílusban + +Az motor konfigurálása és a kép betöltése után a tényleges felismerés egyetlen hívás: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +A program futtatásakor (`dotnet run`) valami ilyesmit kell látnod: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Ha a kimenet értelmetlennek tűnik, ellenőrizd a következőket: + +- `rus.traineddata` fájl jelen van a `ResourceFolder`‑ben. +- A kép nem túl homályos; fontold meg egy egyszerű binarizációs szűrő alkalmazását OCR előtt. +- A nyelvi beállítás valóban `OcrLanguage.Russian`. + +## 5. lépés: Finomhangolás és gyakori buktatók + +### Bizalomküszöb beállítása + +Az Aspose OCR belsőleg karakterenként visszaad egy megbízhatósági értéket. Bár az API nem teszi közvetlenül elérhetővé, engedélyezheted a **detailed output**‑ot, hogy lásd, mely szavak alacsony bizalommal rendelkeznek: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Ha gyakran észlelsz hibás felismeréseket, próbáld ki: + +- **Pre‑processing**: Konvertáld a képet szürkeárnyalatúvá, növeld a kontrasztot, vagy alkalmazz medián szűrőt. +- **DPI settings**: Győződj meg róla, hogy a kép legalább 300 DPI legyen a cirill szkriptekhez. + +### Tömeges feldolgozás több képpel + +Ha tömegesen kell **extract text from image** fájlokat feldolgozni, csomagold a felismerési logikát egy ciklusba: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Most minden PNG saját `.txt` megfelelőjét kapja – praktikus a dokumentumok archiválásához. + +### Unicode kimenet kezelése + +A cirill karakterek Unicode‑ok, ezért győződj meg róla, hogy a konzol kódolása képes megjeleníteni őket: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Helyezd ezt a sort közvetlenül a `Main` metódus eleje után. Enélkül kérdőjelek (`?`) jelenhetnek meg az orosz betűk helyett. + +## Teljes működő példa + +Alább a teljes, azonnal futtatható kód. Másold be a `Program.cs`‑be, állítsd be az útvonalakat, és már indulhat is. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Várható kimenet** (feltételezve, hogy a mintakép a „Пример текста на русском языке.” szöveget tartalmazza): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Ha valami mást látsz, nézd át újra az 5. lépésben szereplő hibaelhárítási tippeket. + +## Összegzés + +Most már van egy szilárd, vég‑től‑végig példád arra, hogyan **ocr russian text** C#‑ban az Aspose OCR használatával. A könyvtár telepítésétől, az orosz nyelvi modell konfigurálásáig, a kép betöltéséig és tiszta Unicode szöveggé alakításáig minden lépés lefedett. + +Ne feledd, a megbízható OCR kulcsa a jó forrásanyag: tiszta betűtípusok, megfelelő DPI és a helyes nyelvi erőforrások. Miután elsajátítottad az alapokat, bővítheted a kötegelt feldolgozásra, integrálhatod felhő tárolóval, vagy akár AI utófeldolgozással kombinálhatod a helyesírás-ellenőrzéshez. + +### Mi a következő? + +- Fedezd fel a **aspose ocr c#** haladó beállításait, mint a layout elemzés vagy a PDF kimenet. +- Kombináld ezt **extract text from image** munkafolyamatokkal az Azure Functions‑ben a szerver nélküli feldolgozáshoz. +- Próbálj ki különböző nyelveket – egyszerűen cseréld le a `OcrLanguage.Russian`‑t `OcrLanguage.English`‑re vagy egy másik támogatott kódra. + +Van kérdésed vagy egy nehéz kép, ami nem működik? Írj egy megjegyzést alább, és jó kódolást! + +![ocr russian text example](ocr-russian-example.png){alt="ocr orosz szöveg példa"} + +## Kapcsolódó oktatóanyagok + +- [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/) +- [szövegkép felismerése több nyelvhez az Aspose OCR-rel](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Szöveg kinyerése képből az Aspose.OCR .NET használatával](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/hungarian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..1216d9822 --- /dev/null +++ b/ocr/hungarian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: Szöveg felismerése képről az Aspose OCR használatával C#-ban. Tanulja + meg, hogyan töltsön be képet OCR-hez, állítsa be az OCR nyelvet, hozza létre az + OCR motorját, és nyerjen ki szöveget TIFF-fájlból. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: hu +og_description: Szöveg felismerése képről az Aspose OCR használatával C#-ban. Ez az + útmutató bemutatja, hogyan hozhatunk létre OCR-motort, töltsünk be képet OCR-hez, + állítsuk be az OCR nyelvet, és hogyan nyerhetünk ki szöveget TIFF-ből. +og_title: Szöveg felismerése képről az Aspose OCR-rel – Teljes C# útmutató +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Képről szöveg felismerése az Aspose OCR-rel – Teljes C# útmutató +url: /hu/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# szöveg felismerése képről Aspose OCR‑rel – Teljes C# útmutató + +Szükséged volt már **szöveg felismerésére képről**, de nem tudtad, melyik könyvtár biztosítja a sebességet és a pontosságot? Nem vagy egyedül. Sok számlakezelő vagy archiválási projektben a legnagyobb gond a tiszta, kereshető szöveg kinyerése a TIFF fájlokból anélkül, hogy saját elemzőt írnál. + +A lényeg: az Aspose OCR for .NET ezt a teljes folyamatot egy könnyed feladatként teszi. Ebben az útmutatóban végigvezetünk mindenen: a csomag telepítésén, **OCR motor létrehozásán**, TIFF betöltésén, az OCR nyelvének beállításán, és végül **szöveg kinyerésén a TIFF‑ből**. A végére egy futtatható konzolalkalmazást kapsz, amely **szöveg felismerését képről** villámgyorsan elvégzi. + +## Előfeltételek + +- .NET 6.0 vagy újabb (a kód .NET Core‑dal és .NET Framework‑kel is működik) +- Visual Studio 2022 (vagy bármely kedvelt IDE) +- Aspose.OCR NuGet csomag (GPU támogatáshoz a `Aspose.OCR.Gpu` kiegészítő szükséges) +- GPU CUDA támogatással, ha a plusz sebességet szeretnéd (opcionális, de ajánlott) + +> **Pro tipp:** Ha nincs GPU-d, egyszerűen hagyd ki a `GpuDevice` sort, és a motor automatikusan CPU‑ra vált. + +## 1. lépés: Aspose OCR telepítése és OCR motor létrehozása + +Először add hozzá a szükséges csomagokat a NuGet‑en keresztül: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Most **létrehozhatjuk az OCR motort**. Ez az objektum a folyamat szíve; tartalmazza a konfigurációt, például a futtatási eszközt és a memória korlátokat. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Miért fontos:** Ha a motort GPU‑ra kötöd, drámaian csökkented a **szöveg felismerésének képről** igényelt időt, különösen nagy felbontású TIFF‑ek tömeges feldolgozásánál. + +## 2. lépés: Kép betöltése OCR‑hez + +Ezután **betölteni kell a képet OCR‑hez**. Az Aspose.OCR a `System.Drawing.Image`‑et használja, így bármely, a GDI+ által támogatott formátum (beleértve a többoldalas TIFF‑et) megfelelő. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Ha többoldalas TIFF‑et kezelsz, a `image.SelectActiveFrame` segítségével ciklizálhatsz az oldalak között, de a legtöbb esetben egy egyszerű hívás elegendő. + +## 3. lépés: OCR nyelv beállítása + +A motor nem tudja magától, hogy milyen nyelvet olvas. **Állítsd be az OCR nyelvet** a felismerő futtatása előtt; különben csak összevissza karakterekkel kapod a kimenetet. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Tudtad?** A nyelv futás közbeni váltása alacsony költségű – akár vegyes nyelvű dokumentumot is feldolgozhatsz, ha ezt a tulajdonságot oldalak között módosítod. + +## 4. lépés: Felismerés végrehajtása – Szöveg felismerése képről + +Most jön a lényeg: **szöveg felismerése képről**. A `Recognize` metódus egy egyszerű stringet ad vissza, amely tartalmazza az összes detektált karaktert. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Ha bizalmi pontszámokra vagy határoló dobozokra van szükséged, használhatod azt a túlterhelést, amely egy `OcrResult` objektumot ad vissza, de a legtöbb kinyerési feladathoz a sima string elegendő. + +## 5. lépés: Szöveg kinyerése a TIFF‑ből (többoldalas fájlok kezelése) + +Ha a forrás egy többoldalas TIFF, ismételd meg a 2‑4. lépéseket minden keretnél. Íme egy gyors ciklus, amely **kivonja a szöveget a TIFF‑ből** oldalanként: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +A fenti kód minden oldalhoz kiírja a kinyert szöveget, így egyszerűen továbbítható adatbázisba vagy keresőindexbe. + +## 6. lépés: A kinyert szöveg megjelenítése vagy mentése + +Végül **jelenítsük meg a kinyert szöveget**, és opcionálisan írjuk ki egy fájlba a későbbi feldolgozáshoz. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +A program futtatása kiírja a felismert karaktereket, és a forrás TIFF mellett létrehozza az `extracted_text.txt` fájlt. + +--- + +## Gyakori kérdések és speciális esetek + +- **Mi van, ha a GPU nem kerül felismerésre?** + Távolítsd el a `GpuDevice` sort; a motor automatikusan CPU‑ra vált. A teljesítmény lassabb lesz, de az eredmények továbbra is pontosak. + +- **Feldolgozhatok PNG vagy JPEG fájlokat is?** + Természetesen – a `Image.FromFile` bármely, a System.Drawing által támogatott formátummal működik, így **betöltheted a képet OCR‑hez** a kiterjesztéstől függetlenül. + +- **Hogyan kezeljem az alacsony felbontású beolvasásokat?** + Növeld az `ocrEngine.PreprocessOptions.Dpi` értékét a `Recognize` hívása előtt. A magasabb DPI több pixelt biztosít a motor számára, ami javítja a pontosságot. + +- **Van korlátozás a TIFF méretére?** + A `GpuMemoryLimit` tulajdonság korlátozza a GPU használatát. Ha elérted a határt, a motor a maradék oldalakat CPU‑ra váltja. + +--- + +## Összegzés + +Most már van egy komplett, termelés‑kész kódrészlet, amely **szöveg felismerését képről** valósítja meg Aspose OCR‑rel C#‑ban. Az útmutató bemutatta, hogyan **hozd létre az OCR motort**, **töltsd be a képet OCR‑hez**, **állítsd be az OCR nyelvet**, és **nyerd ki a szöveget a TIFF‑ből** – mindezt GPU‑gyorsítással a sebesség növelése érdekében. + +Innen tovább: + +- Kísérletezz különböző nyelvekkel (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, stb.). +- Integráld a kimenetet egy kereshető ElasticSearch indexbe. +- Adj hozzá utófeldolgozást (helyesírás‑ellenőrzés, regex tisztítás) a adatminőség javításához. + +Próbáld ki a saját számlacsomagodon, állítsd be a memória korlátokat, és figyeld, ahogy az OCR teljesítmény szárnyra kap. Boldog kódolást! + +## Kapcsolódó oktatóanyagok + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..09b04891d 100644 --- a/ocr/indonesian/net/ocr-configuration/_index.md +++ b/ocr/indonesian/net/ocr-configuration/_index.md @@ -62,6 +62,8 @@ Buka kekuatan pengenalan gambar OCR di .NET dengan Aspose.OCR. Ekstrak teks deng 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. +### [Buat Mesin OCR di C# – Panduan Lengkap](./create-ocr-engine-in-c-complete-guide/) +Panduan lengkap membuat mesin OCR di C# menggunakan Aspose.OCR. ### Kasus Penggunaan Umum - **Ekstrak gambar teks** dari faktur yang dipindai untuk akuntansi otomatis. @@ -98,4 +100,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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/indonesian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..427569f4e --- /dev/null +++ b/ocr/indonesian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Buat mesin OCR dalam C# dan pelajari cara memeriksa mode evaluasi serta + status lisensinya dalam beberapa baris kode. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: id +og_description: Buat mesin OCR di C# dan langsung lihat cara mendeteksi mode evaluasi + serta menampilkan status lisensi. +og_title: Buat Mesin OCR di C# – Panduan Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Buat Mesin OCR di C# – Panduan Lengkap +url: /id/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Buat Mesin OCR di C# – Panduan Lengkap + +Pernah bertanya-tanya bagaimana cara **create OCR engine** objek di C# tanpa harus mencari melalui dokumentasi yang tak berujung? Anda bukan satu-satunya. Banyak pengembang mengalami kebuntuan ketika mereka perlu membuat mesin OCR, memverifikasi apakah ia berjalan dalam mode percobaan, dan menampilkan status lisensi kepada pengguna. + +Dalam tutorial ini kami akan membimbing Anda melalui contoh singkat, end‑to‑end yang **creates an OCR engine**, memeriksa **OCR engine evaluation mode**, dan mencetak pesan ramah tentang status lisensi. Pada akhir tutorial Anda akan memiliki aplikasi console yang siap dijalankan dan model mental yang jelas untuk menangani lisensi OCR dalam proyek Anda sendiri. + +## Apa yang Akan Anda Pelajari + +- Cara menginstansiasi `OcrEngine` (inti dari setiap alur kerja OCR). +- Mengapa mendeteksi **evaluation mode** penting untuk kepatuhan dan pengalaman pengguna. +- Cara terbaik untuk **check OCR license** status dan merespons keadaan tak terduga. +- Jebakan umum—referensi null, penanganan pengecualian, dan ketidaksesuaian versi. + +Tidak diperlukan alat eksternal selain OCR SDK yang sudah Anda instal. Jika Anda nyaman dengan sintaks dasar C#, Anda siap melanjutkan. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode ini dapat dikompilasi dengan .NET Core dan .NET Framework). +- Sebuah OCR SDK yang menyediakan kelas `OcrEngine` dengan properti `IsEvaluation` (misalnya, `MyOcrSdk` hipotetik). +- Editor teks atau IDE (Visual Studio, VS Code, Rider—pilih yang Anda suka). + +Itu saja. Mari kita mulai. + +## Langkah 1: Siapkan Proyek Console Baru + +Pertama, buat aplikasi console baru agar Anda dapat menjalankan kode secara terisolasi. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Buka `Program.cs` yang dihasilkan. Kami akan mengganti isinya dengan contoh lengkap yang **creates OCR engine** instance dan menangani lisensi. + +## Langkah 2: Impor Namespace OCR SDK + +Dengan asumsi SDK direferensikan melalui NuGet (`MyOcrSdk` adalah placeholder), tambahkan pernyataan using di bagian atas file. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Jika Anda belum menambahkan paket tersebut, jalankan: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Jaga versi SDK Anda tetap terbaru; rilis yang lebih baru sering meningkatkan deteksi evaluation‑mode. + +## Langkah 3: Buat Instance Mesin OCR + +Sekarang kami akhirnya **create OCR engine** objek. Ini adalah inti dari setiap alur kerja OCR—anggaplah sebagai otak yang nantinya akan membaca gambar. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Mengapa langkah ini penting? `OcrEngine` mengenkapsulasi semua konfigurasi, paket bahasa, dan data lisensi. Tanpanya, Anda tidak dapat memproses gambar atau menanyakan flag evaluasi. + +> **Side note:** Beberapa SDK memungkinkan Anda mengirimkan objek konfigurasi ke konstruktor (mis., bahasa, DPI). Jika Anda memerlukan pengaturan khusus, ubah baris tersebut sesuai kebutuhan. + +## Langkah 4: Tentukan Mode Evaluasi Mesin OCR + +Sebagian besar vendor OCR menyediakan versi percobaan yang berjalan dalam **evaluation mode** hingga kunci lisensi yang valid diberikan. Mengetahui apakah Anda berada dalam mode percobaan memungkinkan Anda menampilkan petunjuk UI yang tepat atau membatasi fitur tertentu. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Properti `IsEvaluation` mengembalikan `true` ketika mesin tidak berlisensi atau menggunakan percobaan berjangka waktu. Ini cara cepat dan andal untuk melindungi fitur premium. + +### Bagaimana Jika Properti Tidak Ada? + +Versi SDK yang lebih lama mungkin menyediakan metode seperti `GetLicenseInfo()` sebagai gantinya. Dalam kasus itu, Anda harus memeriksa objek yang dikembalikan untuk flag `IsTrial`. Selalu konsultasikan changelog SDK saat melakukan upgrade. + +## Langkah 5: Tampilkan Status Lisensi Saat Ini + +Akhirnya, mari tunjukkan kepada pengguna apakah mesin berlisensi atau masih dalam percobaan. Sebuah console write‑line sederhana sudah cukup, namun Anda dapat menyesuaikannya untuk aplikasi GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Operator ternary menjaga kode tetap rapi, dan pesan-pesan cukup jelas bagi pengguna akhir atau pengembang yang membaca log. + +## Contoh Lengkap yang Berfungsi + +Menggabungkan semuanya, berikut program mandiri yang dapat Anda salin‑tempel ke `Program.cs` dan jalankan dengan `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Output yang Diharapkan + +- **Build percobaan:** + `Running in evaluation mode – limited functionality.` + +- **Build berlisensi:** + `Licensed – full OCR capabilities enabled.` + +Jika SDK melempar pengecualian (mis., DLL native yang hilang), blok catch akan mencetak pesan error yang membantu alih-alih membuat seluruh aplikasi crash. + +## Menangani Kasus Edge dan Jebakan Umum + +### 1. Instance Engine Null + +Meskipun konstruktor biasanya mengembalikan objek yang valid, beberapa SDK dapat mengembalikan `null` jika dependensi native yang diperlukan tidak ada. Lindungi terhadap hal ini: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Kedaluwarsa Lisensi Saat Berjalan + +Lisensi percobaan dapat kedaluwarsa di tengah sesi. Secara periodik lakukan re‑query `IsEvaluation` jika aplikasi Anda tetap hidup dalam waktu lama. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Nama Properti Berbeda Antara Versi + +Rilis lama mungkin menyediakan `engine.EvaluationMode` atau `engine.License.IsTrial`. Saat Anda melakukan upgrade, cari catatan rilis SDK untuk perubahan yang memecah kompatibilitas. + +### 4. Skenario Multi‑Thread + +Jika Anda membuat beberapa pekerja OCR, instansiasi **one OCR engine per thread** kecuali SDK secara eksplisit mendukung berbagi yang thread‑safe. Berbagi satu engine dapat menyebabkan kondisi balapan dan pembacaan lisensi yang salah. + +## Pro Tips untuk Penggunaan Produksi + +- **Cache the licensing status** setelah pemeriksaan pertama untuk menghindari pemanggilan properti yang tidak perlu. +- **Log the license key** (disamarkan) saat startup untuk jejak audit—membantu tim dukungan mendiagnosis masalah lisensi. +- **Provide a UI toggle** yang memberi tahu pengguna bahwa mereka berada dalam mode percobaan dan menawarkan tombol “Buy License”. +- **Automate license renewal** menggunakan API aktivasi SDK, jika tersedia, untuk menjaga pengalaman pengguna tetap mulus. + +## Kesimpulan + +Kami baru saja **created OCR engine** objek dalam beberapa baris, memeriksa **OCR engine evaluation mode**, dan mencetak pesan **OCR licensing status** yang jelas. Contoh lengkap dapat dijalankan langsung, menangani error dengan elegan, dan menyoroti “mengapa” di balik setiap langkah—sehingga Anda dapat menyesuaikannya untuk skenario desktop, web, atau sisi layanan. + +Selanjutnya, Anda mungkin ingin mengeksplorasi: + +- Memasukkan gambar ke dalam `engine.Recognize` dan menangani dukungan multi‑bahasa. +- Menggunakan **check OCR license** API untuk secara programatis mengaktifkan kunci yang dibeli. +- Mengintegrasikan dengan kerangka UI (WinForms, WPF, MAUI) untuk menampilkan badge lisensi. + +Cobalah hal tersebut, dan Anda akan memiliki fondasi OCR yang kuat siap untuk aplikasi apa pun. Selamat coding! + +## Tutorial Terkait + +- [Cara Mengekstrak OCR – Konfigurasi OCR](/ocr/english/net/ocr-configuration/) +- [Cara Mendapatkan Hasil OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Cara OCR PDF di .NET dengan Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/ocr-optimization/_index.md b/ocr/indonesian/net/ocr-optimization/_index.md index 74145b54e..25d4f08d4 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. +### [Pra-proses Gambar untuk OCR – Panduan Lengkap Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Pelajari cara mempersiapkan gambar dengan filter pra‑proses untuk meningkatkan akurasi OCR menggunakan Aspose OCR di C#. ## Pertanyaan yang Sering Diajukan diff --git a/ocr/indonesian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/indonesian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..856024db7 --- /dev/null +++ b/ocr/indonesian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Pra‑proses gambar untuk OCR dengan Aspose guna meningkatkan akurasi OCR + dan menjalankan OCR pada file JPEG. Pelajari cara mengekstrak teks menggunakan Aspose + dalam tutorial yang jelas, langkah demi langkah. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: id +og_description: Pra-proses gambar untuk OCR dengan Aspose guna meningkatkan akurasi + OCR. Ikuti panduan ini untuk menjalankan OCR pada JPEG dan mengekstrak teks menggunakan + Aspose di C#. +og_title: Pra-pemrosesan Gambar untuk OCR – Tutorial Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Pra-proses Gambar untuk OCR – Panduan Lengkap Aspose C# +url: /id/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pratinjau Gambar untuk OCR – Panduan Lengkap Aspose C# + +Pernah bertanya-tanya bagaimana cara **preprocess image for OCR** sehingga teks keluar bersih setiap kali? Anda bukan satu-satunya—para pengembang terus berjuang melawan pemindaian berisik, JPEG dengan kontras rendah, dan pencahayaan yang tidak menentu. Kabar baik? Dengan beberapa penyesuaian cerdas Anda dapat **improve OCR accuracy** secara dramatis, dan Aspose membuatnya mudah. + +Dalam tutorial ini kami akan menelusuri contoh dunia nyata yang menunjukkan cara **run OCR on JPEG** gambar, menerapkan pipeline pemrosesan gambar khusus, dan akhirnya **extract text using Aspose**. Pada akhir tutorial Anda akan memiliki cuplikan C# siap‑tempel yang dapat Anda masukkan ke proyek .NET mana pun. + +![Preprocess image for OCR example](preprocess-ocr.png "Preprocess image for OCR") + +## Apa yang Akan Anda Pelajari + +- Mengapa pra‑pemrosesan penting dan filter mana yang memberikan peningkatan terbesar. +- Cara mengonfigurasi `ImageProcessingOptions` Aspose.OCR untuk deskewing, denoising, binarization, dan peningkatan kontras. +- Kode tepat yang diperlukan untuk **run OCR on JPEG** dan mengambil teks bersih. +- Tips dan jebakan yang membuat pipeline OCR Anda tangguh dalam produksi. + +Tidak diperlukan pengalaman sebelumnya dengan Aspose; hanya latar belakang dasar C# dan Visual Studio (atau IDE favorit Anda). Mari kita mulai. + +## Langkah 1: Siapkan Mesin Aspose.OCR – Preprocess Image for OCR + +Hal pertama yang perlu dilakukan adalah membuat instance `OcrEngine` dan memberi tahu mesin bahasa apa yang diharapkan. Pada kebanyakan kasus bahasa Inggris adalah default, tetapi Anda dapat menggantinya dengan bahasa Prancis, Jerman, dll., dengan mengubah enum `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Mengapa ini penting:** Mesin adalah inti dari operasi; tanpa mesin Anda tidak dapat menerapkan filter gambar yang sebenarnya **preprocess image for OCR**. Anggap saja ini sebagai dapur tempat semua bahan dicampur. + +## Langkah 2: Bangun Pipeline Pemrosesan Gambar Khusus – Improve OCR Accuracy + +Sekarang bagian yang menarik. Aspose memungkinkan Anda menggabungkan beberapa filter sekaligus. Di bawah ini kami mengaktifkan empat filter paling efektif: + +1. **Deskew** – meluruskan dokumen yang miring (maks 5° secara default). +2. **Denoise** – menghaluskan latar belakang yang berbutir. +3. **Binarize** – mengubah gambar menjadi hitam‑putih menggunakan ambang batas. +4. **ContrastBoost** – membuat karakter yang lemah menjadi lebih menonjol. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** Jika gambar sumber Anda sudah tajam, Anda dapat menurunkan `Strength` atau mematikan filter sepenuhnya. Pemrosesan berlebihan kadang‑kadang dapat menghapus karakter yang lemah, jadi coba dengan contoh nyata. + +## Langkah 3: Muat JPEG (atau Gambar Apa Pun) dan Run OCR – Run OCR on JPEG + +Aspose bekerja dengan format gambar apa pun yang dapat dibaca .NET—JPEG, PNG, BMP, dan lain‑lain. Berikut cara memasukkan file JPEG ke dalam mesin dan memulai proses pengenalan. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Mengapa JPEG?** Kompresi JPEG sering menambahkan artefak yang membingungkan OCR. Pipeline pra‑pemrosesan kami, terutama langkah denoise dan binarize, mengurangi masalah tersebut, memungkinkan Anda **run OCR on JPEG** dengan percaya diri. + +## Langkah 4: Keluarkan Teks yang Diakui – Extract Text Using Aspose + +Akhirnya, kami cukup menuliskan teks ke konsol, file, atau layanan downstream apa pun. Untuk demonstrasi, konsol sudah cukup. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Saat Anda menjalankan program, Anda akan melihat sesuatu seperti: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Jika output terlihat berantakan, kembali ke **Langkah 2** dan sesuaikan pengaturan filter. Penyesuaian kecil sering menghasilkan peningkatan besar dalam **improve OCR accuracy**. + +## Kasus Edge Umum dan Cara Menanganinya + +| Situasi | Penyesuaian yang Disarankan | +|-----------|----------------------| +| **Gambar sangat gelap** | Tingkatkan `ContrastBoost.Level` menjadi 1.5 atau lebih tinggi. | +| **Miring > 5°** | Naikkan `DeskewOptions.MaxAngle` (mis., 10.0) atau pra‑putar gambar secara manual. | +| **Teks berwarna pada latar belakang berwarna** | Gunakan `BinarizeOptions` dengan ambang khusus atau beralih ke `AdaptiveBinarizeOptions`. | +| **File besar ( > 5 MB )** | Muat gambar ke dalam `MemoryStream` terlebih dahulu untuk menghindari masalah penguncian file. | + +Penyesuaian ini menjaga pipeline Anda tetap fleksibel dan tahan masa depan, terutama ketika Anda perlu **extract text using Aspose** dari berbagai sumber. + +## Contoh Lengkap yang Siap Pakai – Semua Langkah dalam Satu Tempat + +Berikut adalah program lengkap yang siap disalin‑tempel. Program ini dapat dikompilasi dengan .NET 6+ dan hanya memerlukan paket NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Simpan sebagai `Program.cs`, tambahkan paket Aspose.OCR (`dotnet add package Aspose.OCR`), dan jalankan `dotnet run`. Anda akan melihat teks yang telah dibersihkan tercetak di konsol. + +## Ringkasan – Mengapa Pendekatan Ini Berhasil + +- **Preprocess image for OCR**: Pipeline menghilangkan sumber kesalahan paling umum (miring, noise, kontras rendah). +- **Improve OCR accuracy**: Setiap filter disetel untuk meningkatkan rasio sinyal‑ke‑noise yang dilihat mesin. +- **Run OCR on JPEG**: Bahkan gambar terkompresi menjadi terbaca setelah deskewing dan binarization. +- **Extract text using Aspose**: Metode `Recognize` mengembalikan string biasa, siap untuk logika downstream apa pun. + +Bersama-sama, langkah‑langkah ini memberi Anda solusi OCR produksi yang andal dalam beberapa baris kode saja. + +## Langkah Selanjutnya dan Topik Terkait + +- **Pemrosesan batch** – Loop melalui folder gambar dan tulis setiap hasil ke file `.txt`. +- **Paket bahasa** – Ganti `OcrLanguage.English` dengan `OcrLanguage.Spanish` atau tambahkan kamus khusus. +- **Ekstraksi PDF** – Gabungkan Aspose.OCR dengan Aspose.PDF untuk mengambil teks langsung dari PDF yang dipindai. +- **Optimasi performa** – Jalankan mesin secara paralel menggunakan `Parallel.ForEach` untuk beban kerja besar. + +Silakan bereksperimen dengan nilai filter, coba format gambar lain, atau gabungkan filter Aspose tambahan seperti `SharpnessOptions`. Langit adalah batasnya setelah Anda menguasai dasar‑dasarnya. + +--- + +*Selamat coding! Jika Anda menemukan kendala, tinggalkan komentar di bawah dan kami akan membantu memecahkannya bersama.* + +## Tutorial Terkait + +- [Preprocess Image OCR dengan Filter Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Ekstrak Teks dari Gambar – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/text-recognition/_index.md b/ocr/indonesian/net/text-recognition/_index.md index 7aee7bb85..2832c2c10 100644 --- a/ocr/indonesian/net/text-recognition/_index.md +++ b/ocr/indonesian/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Tingkatkan aplikasi .NET Anda dengan Aspose.OCR untuk pengenalan teks gambar yan Buka potensi OCR di .NET dengan Aspose.OCR. Ekstrak teks dari PDF dengan mudah. Unduh sekarang untuk pengalaman integrasi yang lancar. ### [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. +### [Mengenali Teks dari Gambar dengan Aspose OCR – Panduan Lengkap C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Panduan lengkap C# untuk mengenali teks dari gambar menggunakan Aspose OCR, langkah demi langkah untuk integrasi mudah. +### [Ekstrak Teks dari Gambar dalam C# – Panduan Lengkap Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Panduan lengkap C# untuk mengekstrak teks dari gambar menggunakan Aspose OCR, langkah demi langkah untuk integrasi mudah. +### [Cara Menggunakan OCR di C# – Mengenali Teks Cina dari JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Pelajari cara menggunakan Aspose.OCR dengan C# untuk mengenali teks berbahasa Cina pada file JPG secara akurat. +### [OCR Teks Rusia dalam C# – Panduan Lengkap Menggunakan Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Panduan lengkap C# untuk mengenali teks berbahasa Rusia menggunakan Aspose OCR, langkah demi langkah untuk integrasi mudah. +### [Ekstrak Teks dari Gambar dalam ASP.NET Core Minimal API – Panduan Lengkap](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Panduan lengkap untuk mengekstrak teks dari gambar menggunakan ASP.NET Core Minimal API dengan Aspose OCR, langkah demi langkah untuk integrasi mudah. +### [Tutorial OCR C#: Ekstrak Teks dari Resi PNG dengan Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Pelajari cara mengekstrak teks dari file PNG berisi resi menggunakan Aspose OCR dalam aplikasi C# Anda. +### [Mengonversi TIFF ke Teks dalam C# – Panduan OCR Batch Lengkap](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Panduan lengkap untuk mengonversi file TIFF menjadi teks menggunakan Aspose.OCR dalam batch dengan 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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/indonesian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..0b750c35f --- /dev/null +++ b/ocr/indonesian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-25 +description: Tutorial OCR C# yang menunjukkan cara memuat file gambar C# dan mengenali + teks PNG dari struk menggunakan Aspose OCR – panduan langkah demi langkah. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: id +og_description: Tutorial OCR C# yang memandu Anda dalam memuat file gambar C# dan + mengenali teks PNG dari struk menggunakan Aspose OCR. +og_title: c# OCR tutorial – Ekstrak Teks dari Resi PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'Tutorial OCR C#: Ekstrak Teks dari Resi PNG dengan Aspose' +url: /id/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tutorial c# OCR – Ekstrak Teks dari Resi PNG dengan Aspose + +Pernah membutuhkan **c# OCR tutorial** yang benar‑benar menyelesaikan pekerjaan tanpa harus terus‑menerus Googling? Anda berada di tempat yang tepat. Dalam panduan ini kami akan **load image file c#**, **recognize png text**, dan **read receipt OCR** results, sambil menunjukkan cara **perform OCR image** processing dengan Aspose OCR. + +Kami akan memulai dengan menginstal paket NuGet yang diperlukan, menelusuri setiap baris kode, dan menyelesaikannya dengan dump JSON yang rapi yang dapat Anda alirkan langsung ke pipeline data berikutnya. Tanpa basa‑basi, hanya solusi praktis yang siap dijalankan. + +## Apa yang Akan Anda Pelajari + +- Cara menyiapkan Aspose OCR dalam proyek .NET 6 (atau lebih baru). +- Langkah‑langkah tepat untuk **load an image file c#** dan menyerahkannya ke mesin. +- Cara **recognize png text** dari gambar resi dan menangkap hasilnya. +- Cara **read receipt OCR** output sebagai JSON yang terformat rapi. +- Tips untuk operasi **perform OCR image** pada berbagai jenis file dan menangani jebakan umum. + +**Prasyarat** +- Visual Studio 2022 (atau IDE apa pun yang Anda suka). +- .NET 6 SDK atau yang lebih baru. +- Sebuah gambar resi PNG yang siap pakai (kami akan menyebutnya `receipt.png`). + +Jika Anda sudah memiliki itu, mari kita mulai. + +![tangkapan layar tutorial c# OCR](ocr-demo.png "hasil tutorial c# OCR menampilkan output JSON") + +## Tutorial c# OCR – Menyiapkan Mesin Aspose OCR + +Pertama-tama, kita membutuhkan pustaka Aspose OCR. Buka terminal Anda di folder solusi dan jalankan: + +```bash +dotnet add package Aspose.OCR +``` + +Perintah tunggal itu mengunduh semua yang diperlukan, termasuk binary native untuk decoding gambar. Setelah terpasang, buat proyek konsol baru atau tambahkan kode ke proyek yang sudah ada. + +### Mengapa Aspose? + +Aspose OCR mendukung lebih dari 30 bahasa, dapat bekerja secara offline, dan mengembalikan objek `OcrResult` yang kaya—sempurna untuk tugas **perform OCR image** dimana Anda membutuhkan lebih dari sekadar teks biasa. + +## Memuat file gambar c# dan Menyiapkan Resi + +Sekarang pustaka sudah siap, mari **load image file c#**. Kelas `System.Drawing.Image` melakukan pekerjaan berat, tetapi Anda juga dapat menggunakan `SkiaSharp` jika lebih menyukai alternatif lintas‑platform. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** Bungkus `Image` dalam pernyataan `using` (seperti yang ditunjukkan) untuk segera membebaskan sumber daya native—terutama penting ketika Anda **perform OCR image** pada banyak file dalam sebuah loop. + +## Mengenali teks PNG dengan Aspose + +Dengan gambar berada di memori, mesin kini dapat **recognize png text**. Aspose mengembalikan `OcrResult` yang berisi baik string mentah maupun data terperinci tentang setiap kata yang dikenali. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Mengapa memanggil `RecognizeWithResult` alih‑alih `Recognize` yang lebih sederhana? Yang pertama memberi Anda akses ke skor kepercayaan, kotak pembatas, dan pemisahan baris—berguna jika nanti Anda perlu **read receipt OCR** untuk ekstraksi item baris. + +## Membaca Hasil OCR Resi sebagai JSON + +Sebagian besar sistem hilir menyukai JSON, jadi mari serialisasikan `OcrResult`. Serializer `System.Text.Json` menangani objek kompleks dengan elegan, dan kami akan mengaktifkan indentasi untuk keterbacaan. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +JSON yang dihasilkan terlihat seperti ini (dipangkas untuk singkat): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Anda sekarang dapat mengalirkan `jsonResult` ke basis data, antrian pesan, atau cukup mencatatnya untuk debugging. + +## Melakukan Pemrosesan Gambar OCR dan Menampilkan Output + +Akhirnya, keluarkan JSON ke konsol. Dalam aplikasi dunia nyata Anda mungkin akan menulisnya ke file atau mengirimnya lewat HTTP, tetapi konsol memudahkan verifikasi bahwa semuanya berfungsi. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Jalankan program (`dotnet run`) dan Anda akan melihat JSON yang terformat rapi tercetak. Jika gambar resi jelas, teks akan tepat; jika tidak, pertimbangkan meningkatkan resolusi gambar atau menerapkan filter pra‑pemrosesan (mis., skala abu‑abu, peningkatan kontras) sebelum memberi makan ke mesin. + +### Menangani Kasus Pinggiran Umum + +| Situasi | Apa yang harus dilakukan | +|-----------|------------| +| **Gambar buram** | Pra‑proses dengan `System.Drawing` untuk menajamkan atau meningkatkan DPI. | +| **Resi berisi banyak bahasa** | Setel `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Pemrosesan batch besar** | Gunakan kembali satu instance `OcrEngine`; hanya ubah `Image` setiap iterasi. | +| **Tekanan memori** | Segera dispose objek `Image` dan pertimbangkan `await Task.Run` untuk pipeline async. | + +## Kesimpulan + +Selamat—Anda baru saja menyelesaikan **c# OCR tutorial** yang memuat gambar, **recognizes png text**, dan **reads receipt OCR** output sebagai JSON bersih. Langkah‑langkah inti (penyiapan mesin, pemuatan gambar, eksekusi OCR, serialisasi, dan tampilan) membentuk fondasi kuat yang dapat Anda kembangkan ke faktur, paspor, atau dokumen ter‑scan lainnya. + +### Apa Selanjutnya? + +- Bereksperimen dengan **load image file c#** menggunakan `SkiaSharp` untuk dukungan lintas‑platform yang sesungguhnya. +- Selami lebih dalam `OcrResult.Words` untuk mengekstrak item baris, harga, dan tanggal—sempurna untuk aplikasi pelacakan pengeluaran. +- Gabungkan tutorial ini dengan Azure Functions atau AWS Lambda untuk membangun API pemrosesan resi tanpa server. + +Silakan ubah kode, tambahkan lebih banyak gambar, atau bahkan beralih ke paket bahasa lain. Dunia OCR penuh kejutan, dan kini Anda memiliki alat untuk menjelajahinya. + +Selamat coding, dan semoga resi Anda selalu dapat dibaca! + +## Tutorial Terkait + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Ekstrak Teks dari Gambar – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) +- [Cara Menggunakan OCR - Mengenali Gambar tanpa Deteksi Area Teks](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/indonesian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..a40453d95 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Konversi TIFF ke teks menggunakan Aspose.OCR di C#. Pelajari konversi + gambar ke teks secara batch dan ekstrak teks dari file TIFF secara efisien. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: id +og_description: Konversi TIFF ke teks dengan Aspose.OCR. Panduan ini menunjukkan konversi + gambar ke teks secara batch dan cara mengekstrak teks dari file TIFF dalam beberapa + baris kode C#. +og_title: Konversi TIFF ke Teks dalam C# – Panduan OCR Batch Lengkap +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Mengonversi TIFF ke Teks dalam C# – Panduan OCR Batch Lengkap +url: /id/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Mengonversi TIFF ke Teks dalam C# – Panduan OCR Batch Lengkap + +Pernah perlu **convert TIFF to text** tetapi tidak yakin harus mulai dari mana? Anda tidak sendirian—banyak pengembang mengalami kesulitan dengan batch OCR saat menangani dokumen yang dipindai. Dalam tutorial ini kami akan membahas solusi praktis yang **extracts text from TIFF** menggunakan Aspose.OCR, dan kami akan melakukannya secara paralel sehingga folder besar selesai dalam hitungan detik. + +Kami juga akan membahas praktik terbaik **batch image to text conversion**, sehingga pada akhir Anda akan memiliki potongan kode yang dapat digunakan kembali yang mengubah seluruh direktori gambar yang dipindai menjadi file *.txt* yang rapi—sempurna untuk pengindeksan, pencarian, atau memasukkannya ke dalam analitik hilir. + +## Apa yang Anda Butuhkan + +- **.NET 6.0** atau yang lebih baru (kode dapat dikompilasi pada .NET Framework juga) +- Paket NuGet **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Sebuah folder yang berisi satu atau lebih file *.tif* (format pemindaian TIFF klasik) +- IDE favorit Anda (Visual Studio, VS Code, Rider—apa pun yang Anda suka) + +Itu saja. Tidak ada layanan eksternal, tidak ada kunci API, hanya C# murni dan Aspose. + +![Tangkapan layar file TIFF yang sedang diproses dan file teks hasilnya](/images/ocr-result.png "Hasil OCR menampilkan output TIFF yang dikonversi ke teks") + +*(Teks Alt: Tangkapan layar yang menunjukkan output TIFF yang dikonversi ke teks di layar)* + +## Langkah 1: Siapkan Mesin OCR – Convert TIFF to Text + +Pertama-tama, kita membutuhkan instance `OcrEngine` yang tahu bahwa ia harus membaca karakter bahasa Inggris. Mesin ini adalah inti dari konversi; mengkonfigurasinya dengan benar memastikan hasil yang dapat diandalkan. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Mengapa ini penting:* +Aspose.OCR mendukung puluhan bahasa. Jika Anda menangani pemindaian multibahasa, cukup ubah `OcrLanguage.English` ke nilai enum yang sesuai. Membiarkan bahasa tidak ditentukan memaksa mesin ke mode auto‑detect, yang dapat lebih lambat dan kurang akurat. + +## Langkah 2: Kumpulkan Semua File TIFF – Extract Text from TIFF Efficiently + +Selanjutnya kami mengambil setiap file *.tif* dari folder yang Anda tentukan. Menggunakan `Directory.GetFiles` memberi kami array bersih yang dapat kami masukkan ke dalam pemroses batch. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Tip pro:* Flag `SearchOption.AllDirectories` dapat digunakan jika pemindaian Anda berada dalam sub‑folder. Ingat saja bahwa rekursi yang lebih dalam dapat meningkatkan penggunaan memori selama langkah batch. + +## Langkah 3: Lakukan OCR Paralel – Batch Image to Text Conversion + +Sekarang bagian yang menyenangkan. Aspose.OCR menyediakan helper statis `BatchOcr.RecognizeAll` yang menerima array jalur file, sebuah engine, dan petunjuk `parallelism`. Kami akan memulai empat thread, yang pada laptop quad‑core modern memberikan percepatan hampir linier. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Mengapa paralelisme?* +Memindai batch TIFF beresolusi tinggi dapat memakan banyak CPU. Dengan menyebarkan pekerjaan ke beberapa thread, kita membuat semua core sibuk, mengurangi total waktu eksekusi secara dramatis. Jika Anda menjalankannya di server dengan lebih banyak core, tingkatkan nilai `parallelism` sesuai. + +## Langkah 4: Tulis Output – Convert Scanned Images TXT Files + +Akhirnya kami mengulangi kamus dan menulis setiap potongan teks ke file *.txt* yang memiliki nama dasar yang sama dengan aslinya. Inilah saat **convert scanned images txt** menjadi kenyataan. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Apa yang dilakukan kode, dalam bahasa Inggris sederhana + +1. **Create** sebuah mesin OCR yang diatur untuk bahasa Inggris. +2. **Collect** setiap file TIFF dari folder target. +3. **Run** `BatchOcr.RecognizeAll` dengan empat thread, mengubah setiap gambar menjadi string. +4. **Loop** atas hasil, mengganti ekstensi `.tif` menjadi `.txt` dan menulis string ke disk. + +Itulah seluruh alur kerja **convert TIFF to text** dalam kurang dari 50 baris kode. + +## Menangani Kasus Edge – Ketika Sesuatu Tidak Berjalan Lancar + +- **Missing or corrupted TIFFs** – `BatchOcr` akan melempar `OcrException`. Bungkus pemanggilan dalam `try / catch` jika Anda memerlukan degradasi yang elegan. +- **Non‑English documents** – ubah `OcrLanguage.English` menjadi `OcrLanguage.Spanish`, `OcrLanguage.French`, dll., atau gunakan `OcrLanguage.AutoDetect`. +- **Very large images** – pertimbangkan menurunkan DPI sebelum OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) untuk menghemat memori, meskipun Anda mungkin kehilangan sedikit akurasi. +- **Output encoding** – jika Anda memerlukan halaman kode tertentu (misalnya Windows‑1252), berikan ke `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Tips Pro untuk Konversi Batch yang Kuat + +- **Log failures**: buat `List failedFiles` dan tambahkan setiap file yang melempar; tulis daftar ke log setelah loop. +- **Reuse the engine**: instance `OcrEngine` yang sama dapat digunakan kembali pada banyak file; jangan membuat instance di dalam loop. +- **Validate the result**: `if (string.IsNullOrWhiteSpace(extractedText))` singkat dapat menandai pemindaian yang kosong atau tidak terbaca. +- **Combine with PDF**: jika sumber Anda adalah PDF multi‑halaman, konversi setiap halaman ke TIFF terlebih dahulu (Aspose.PDF melakukannya) dan kemudian jalankan batch ini. + +## Langkah Selanjutnya – Melampaui Konversi Sederhana + +Sekarang Anda dapat **extract text from TIFF** file secara massal, Anda mungkin ingin: + +- Mengirim file *.txt* ke indeks pencarian (Elasticsearch, Azure Cognitive Search). +- Menjalankan deteksi bahasa pada setiap hasil untuk mengarahkan dokumen ke pipeline spesifik locale. +- Menghasilkan PDF yang dapat dicari dengan menumpangkan teks OCR kembali ke gambar asli (Aspose.PDF lagi). + +Semua skenario tersebut dibangun di atas ide inti yang sama: **batch image to text conversion** adalah blok bangunan untuk sistem pemrosesan dokumen yang lebih besar. + +--- + +### Kesimpulan + +Anda baru saja belajar cara **convert TIFF to text** menggunakan Aspose.OCR, memproses seluruh folder secara paralel, dan menyimpan setiap hasil sebagai file *.txt* yang bersih. Solusinya ringan, sepenuhnya dapat dikonfigurasi, dan siap untuk produksi—baik Anda mendigitalkan faktur lama, mengarsipkan kontrak yang dipindai, atau menggerakkan mesin pencari teks. + +Cobalah, sesuaikan paralelisme, dan mulailah memasukkan file teks yang baru dibuat ke dalam alur kerja apa pun yang Anda butuhkan. Selamat OCR! + +--- + +## Tutorial Terkait + +- [Ekstrak Teks dari Gambar Menggunakan Operasi OCR pada Folder](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Ekstrak Teks dari Gambar – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/indonesian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..864aa17e7 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-05-25 +description: Pelajari cara mengekstrak teks dari gambar dengan API ASP.NET Core minimal. + Unggah gambar via POST, baca data formulir multipart, dan lakukan OCR pada gambar. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: id +og_description: Ekstrak teks dari gambar menggunakan API ASP.NET Core minimal. Panduan + ini menunjukkan cara mengunggah gambar via POST, membaca data formulir multipart, + dan melakukan OCR pada gambar. +og_title: Ekstrak Teks dari Gambar di ASP.NET Core – Langkah demi Langkah +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Ekstrak Teks dari Gambar di ASP.NET Core Minimal API – Panduan Lengkap +url: /id/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ekstrak Teks dari Gambar di ASP.NET Core Minimal API – Panduan Lengkap + +Pernah bertanya-tanya bagaimana cara **extract text from image** tanpa berurusan dengan kerangka kerja yang berat? Anda tidak sendirian. Banyak pengembang membutuhkan cara cepat agar pengguna dapat mengunggah gambar dan mendapatkan kembali karakter mentah, baik itu memindai struk, mendigitalkan catatan tulisan tangan, atau menggerakkan indeks pencarian. + +Dalam tutorial ini kami akan membuat ASP.NET Core Minimal API kecil yang **uploads image via POST**, mengurai muatan *multipart/form‑data*, dan kemudian **perform OCR on image** menggunakan singleton `OcrEngine`. Pada akhir tutorial Anda akan memiliki aplikasi yang dapat dijalankan sepenuhnya yang dapat Anda masukkan ke proyek .NET 8 mana pun dan mulai mengekstrak teks dari gambar segera. + +## Apa yang Akan Anda Bangun + +- A minimal web app yang mendengarkan pada `/ocr`. +- Endpoint yang menerima file gambar yang dikirim dengan permintaan POST `multipart/form-data`. +- Logika yang membaca file yang diunggah, memberi ke OCR engine, dan mengembalikan hasil plain‑text. +- Potongan kode akselerasi GPU opsional (dikomentasikan) untuk mereka yang memiliki kartu yang kompatibel. + +**Prasyarat** +- .NET 8 SDK (atau lebih baru). +- Familiaritas dasar dengan C# dan command line. +- Pustaka OCR yang menyediakan kelas `OcrEngine` (contoh mengasumsikan paket NuGet hipotetik). + +Jika Anda sudah memiliki itu, mari kita mulai. + +## Langkah 1: Siapkan Proyek dan Tambahkan Paket OCR + +Pertama, buat proyek web baru dan tambahkan pustaka OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro tip:** Jaga dependensi Anda tetap terbaru. Versi yang lebih baru sering memberikan peningkatan performa, terutama untuk inferensi yang dipercepat GPU. + +## Langkah 2: Daftarkan Singleton OCR Engine (Layanan Utama) + +Kami menginginkan satu instance `OcrEngine` untuk seluruh aplikasi—tidak perlu membuat engine baru per permintaan. Daftarkan di container layanan builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Mengapa singleton?** +Membuat OCR engine dapat mahal—bayangkan memuat bobot jaringan saraf ke memori. Dengan menggunakan kembali instance yang sama, kita menghemat siklus CPU dan RAM, yang berarti waktu respons lebih cepat untuk setiap panggilan `/ocr`. + +## Langkah 3: Bangun Aplikasi + +Sekarang kami mematerialisasikan objek `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Baris itu terlihat hampir ajaib, tetapi di baliknya ia menghubungkan routing, middleware, dan container DI yang baru saja kami konfigurasikan. + +## Langkah 4: Definisikan Endpoint POST – “Upload Image via POST” + +Berikut inti tutorial: endpoint yang **upload image via POST**, membaca payload multipart, dan menyerahkan data ke OCR engine. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Memecah Logika + +| Langkah | Apa yang Terjadi | Mengapa Penting | +|---------|------------------|-----------------| +| **ReadFormAsync** | Menganalisis permintaan *multipart/form-data* yang masuk. | Tanpa ini, Anda tidak dapat mengakses file yang diunggah. | +| **form.Files["image"]** | Mengambil file yang nama bidang formulirnya adalah `image`. | Menjamin kontrak yang dapat diprediksi bagi pemanggil. | +| **Content‑type check** | Memverifikasi bahwa file tersebut adalah gambar (mis., `image/png`). | Mencegah OCR engine gagal pada data yang bukan gambar. | +| **Image.FromStream** | Mengonversi aliran mentah menjadi `System.Drawing.Image`. | Pustaka OCR mengharapkan objek `Image`, bukan array byte mentah. | +| **ocr.Recognize(img)** | Memanggil OCR engine untuk **how to recognize text from image**. | Ini adalah langkah inti **perform OCR on image**. | +| **Results.Text** | Mengirim kembali respons plain‑text. | Format sederhana yang dapat dikonsumsi oleh layanan hilir. | + +## Langkah 5: Jalankan API + +Akhirnya, jalankan server web. + +```csharp +app.Run(); +``` + +Saat Anda menjalankan `dotnet run`, API akan mendengarkan pada `http://localhost:5000` (atau port pilihan Anda). Anda dapat mengujinya dengan `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Output yang diharapkan:** Konsol akan mencetak karakter yang dikenali, mis.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Jika gambar buram atau bahasa tidak didukung, OCR engine akan mengembalikan string kosong atau pesan error—tangani kasus tersebut dalam kode produksi. + +## Kasus Edge & Praktik Terbaik + +### 1. File Besar + +Batas default body permintaan adalah 30 MB. Untuk pemindaian yang lebih besar Anda mungkin perlu menyesuaikan: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR Asinkron + +Beberapa pustaka OCR menyediakan metode async (`RecognizeAsync`). Jika milik Anda demikian, ganti `ocr.Recognize(img)` dengan `await ocr.RecognizeAsync(img)` dan tandai lambda sebagai `async`. + +### 3. Pertimbangan Keamanan + +- **Validasi ukuran file** sebelum memuatnya ke memori. +- **Sanitasi nama file** jika Anda pernah menuliskannya ke disk. +- **Rate‑limit** endpoint untuk menghindari serangan denial‑of‑service. + +### 4. Akselerasi GPU + +Jika Anda menghapus komentar pada baris `engine.GpuDevice = new GpuDevice(0);` dan perangkat keras Anda mendukung CUDA atau DirectML, Anda akan melihat peningkatan kecepatan yang signifikan, terutama pada gambar beresolusi tinggi. + +## Contoh Lengkap yang Berfungsi + +Berikut adalah `Program.cs` lengkap yang dapat Anda copy‑paste ke proyek Minimal API baru. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Simpan, jalankan `dotnet run`, dan Anda siap untuk **extract text from image** sesuai permintaan. + +## Kesimpulan + +Kami telah membahas **solusi lengkap, end‑to‑end** untuk mengekstrak teks dari gambar menggunakan ASP.NET Core Minimal API. Mulai dari scaffolding proyek, kami **mendaftarkan singleton OCR engine**, membangun endpoint yang **uploads image via POST**, **read multipart form data**, dan akhirnya **perform OCR on image** untuk mengembalikan plain‑text bersih. + +Dari sini Anda dapat: + +- Menambahkan pembungkus JSON untuk respons yang lebih kaya. +- Menyambungkan basis data untuk menyimpan teks yang diekstrak. +- Memperluas dukungan ke banyak bahasa (`OcrLanguage.Spanish`, dll.). + +Pola ini skalabel dengan baik—cukup letakkan endpoint yang sama ke dalam microservice yang lebih besar atau expose di belakang API gateway. + +Ada pertanyaan tentang penanganan PDF, pemrosesan batch, atau penyetelan GPU? Tinggalkan komentar, dan selamat coding! + +## Tutorial Terkait + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/indonesian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..d935651fd --- /dev/null +++ b/ocr/indonesian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,293 @@ +--- +category: general +date: 2026-05-25 +description: Ekstrak teks dari gambar menggunakan C# dan Aspose OCR. Pelajari cara + mengonversi JPG ke teks, memuat gambar untuk OCR, dan mendapatkan hasil yang andal + dengan cepat. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: id +og_description: Ekstrak teks dari gambar dengan C#. Panduan ini menunjukkan cara mengonversi + JPG ke teks, memuat gambar untuk OCR, dan menangani konten multibahasa. +og_title: Ekstrak Teks dari Gambar di C# – Tutorial OCR Aspose +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Ekstrak Teks dari Gambar di C# – Panduan Lengkap Aspose OCR +url: /id/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Ekstrak Teks dari Gambar di C# – Panduan Lengkap Aspose OCR + +Pernah bertanya-tanya bagaimana cara **extract text from image** menggunakan kode C# biasa? Anda tidak sendirian. Baik Anda sedang mendigitalkan kwitansi, memindai papan tanda, atau hanya penasaran tentang OCR, kemampuan untuk mengambil karakter dari sebuah gambar adalah keterampilan yang berguna. Dalam tutorial ini kami akan membahas contoh lengkap yang dapat dijalankan yang menunjukkan secara tepat cara **extract text from image** dengan Aspose.OCR, dan kami juga akan membahas cara **convert jpg to text**, **load image for OCR**, serta menjawab pertanyaan klasik “**how to ocr image**” sekali untuk selamanya. + +Pada akhir panduan ini Anda akan memiliki aplikasi konsol yang berdiri sendiri yang membaca file JPEG, mengenali bahasa Ukraina (atau bahasa lain yang didukung), dan mencetak hasilnya ke konsol. Tidak ada referensi yang samar, tidak ada bagian yang hilang—hanya solusi lengkap yang dapat Anda salin‑tempel dan jalankan. + +--- + +## Apa yang Akan Anda Pelajari + +* Cara menginstal paket NuGet Aspose.OCR. +* Kode tepat yang diperlukan untuk **load image for OCR** di C#. +* Cara mengatur bahasa dan benar‑benar **extract text from image**. +* Trik untuk **convert jpg to text** secara efisien. +* Kesulitan umum dan cara menghindarinya. + +Jika Anda sudah memiliki lingkungan pengembangan .NET yang siap, Anda dapat langsung memulai. Jika tidak, bagian prasyarat di bawah ini akan membantu Anda memulai. + +## Prasyarat + +| Requirement | Why it matters | +|-------------|----------------| +| .NET 6.0 SDK (or newer) | Menyediakan runtime untuk aplikasi konsol. | +| Visual Studio 2022 atau VS Code | Mempermudah pengeditan dan debugging. | +| Koneksi internet (pada run pertama) | NuGet perlu mengunduh Aspose.OCR. | +| Gambar JPEG yang ingin Anda proses (mis., `ukrainian_sign.jpg`) | File sumber untuk mesin OCR. | + +> **Pro tip:** Jika Anda menggunakan Linux atau macOS, kode yang sama dapat dijalankan dengan .NET CLI (`dotnet new console`), jadi silakan lewati IDE yang berat. + +## Langkah 1 – Instal Aspose.OCR via NuGet + +Buka terminal Anda (atau Package Manager Console) dan jalankan: + +```bash +dotnet add package Aspose.OCR +``` + +Baris tunggal itu mengunduh binari Aspose.OCR terbaru beserta semua dependensi transitifnya. Tidak diperlukan penanganan DLL manual. + +## Langkah 2 – Buat OCR Engine (Inti dari Ekstraksi) + +Setelah perpustakaan tersedia, kita dapat membuat instance `OcrEngine`. Objek ini bertanggung jawab untuk **extracting text from image** data. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Mengapa ini penting:** Engine mengenkapsulasi algoritma OCR, model bahasa, dan opsi konfigurasi. Membuatnya sekali dan menggunakannya kembali pada beberapa gambar sekaligus efisien dalam memori dan cepat. + +## Langkah 3 – Muat Gambar untuk OCR (Dan Atur Bahasa) + +Langkah berikutnya adalah memberi tahu engine gambar mana yang akan dibaca. Di sinilah frasa **load image for OCR** berperan. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Kasus khusus:** Jika file tidak ada, `Image.FromFile` akan melempar `FileNotFoundException`. Bungkus pemanggilan tersebut dalam blok try‑catch untuk kode produksi. + +## Langkah 4 – Lakukan OCR dan Ekstrak Teks + +Dengan gambar dimuat, engine kini dapat **extract text from image**. Metode `Recognize` melakukan pekerjaan berat. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Jika semuanya berjalan lancar, `recognizedText` akan berisi representasi teks biasa dari semua yang dapat dibaca oleh engine OCR. + +## Langkah 5 – Konversi JPG ke Teks (Menggabungkan Semua) + +Kode yang telah kami buat sejauh ini sudah **convert jpg to text**, tetapi mari kita bungkus dalam metode rapi yang dapat Anda panggil berulang kali. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Sekarang Anda cukup melakukan: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Output yang diharapkan** (dipotong untuk singkat): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Jika gambar berisi teks bahasa Inggris, ubah `OcrLanguage.English` dan Anda akan melihat output yang sesuai. + +## Langkah 6 – Menangani Pertanyaan Umum “How to OCR Image” + +### 6.1 Apakah Saya Bisa OCR PNG atau BMP? + +Tentu saja. Metode `Image.FromFile` mendukung semua format yang dikenali oleh System.Drawing, jadi cukup arahkan path ke file `.png` atau `.bmp` dan sisanya tetap sama. + +### 6.2 Bagaimana jika gambar beresolusi rendah? + +Akurasi OCR menurun drastis di bawah 300 dpi. Solusi cepat adalah memperbesar gambar dengan `Graphics` sebelum memberi ke engine: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Apakah Saya Membutuhkan Lisensi untuk Aspose.OCR? + +Aspose menawarkan percobaan gratis dengan watermark. Untuk penggunaan produksi, beli lisensi dan tambahkan: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +## Contoh Lengkap yang Berfungsi + +Berikut adalah aplikasi konsol lengkap yang siap dijalankan yang mendemonstrasikan **how to OCR image**, **load image for OCR**, dan **convert jpg to text** dalam satu paket rapi. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Cara menjalankannya** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Anda akan melihat teks yang diekstrak tercetak di konsol, mengonfirmasi bahwa Anda telah berhasil **extract text from image** menggunakan C#. + +## Kesulitan Umum & Pro Tips + +| Masalah | Mengapa terjadi | Solusi | +|---------|----------------|--------| +| Output kosong | Gambar terlalu gelap atau kontras rendah. | Pralakukan dengan `Bitmap` untuk meningkatkan kecerahan. | +| Bahasa salah | Properti `Language` dibiarkan pada default Inggris. | Secara eksplisit set `ocrEngine.Language = OcrLanguage.Ukrainian;` (atau target Anda). | +| Kesalahan kehabisan memori | Gambar sangat besar dimuat tanpa dibuang. | Bungkus `Image.FromFile` dalam blok `using` (seperti yang ditunjukkan). | +| Watermark lisensi | Menjalankan versi percobaan tanpa lisensi. | Terapkan lisensi yang dibeli di awal `Main`. | + +## Kesimpulan + +Kami baru saja membahas semua yang Anda perlukan untuk **extract text from image** di C#—dari menginstal Aspose.OCR, **loading image for OCR**, hingga **convert jpg to text** dan menangani skenario multibahasa. Program contoh lengkap menggabungkan semua bagian, memberikan fondasi yang dapat diandalkan untuk proyek apa pun yang terkait OCR. + +Selanjutnya, Anda mungkin ingin menjelajahi: + +* **How to OCR image** aliran alih-alih file (gunakan `MemoryStream`). +* Menambahkan **c# image to text** pasca‑pemrosesan seperti pemeriksaan ejaan. +* Mengintegrasikan langkah OCR ke dalam pipeline yang lebih besar (mis., menyimpan hasil ke basis data). + +Silakan bereksperimen dengan berbagai bahasa, format gambar, dan trik pra‑pemrosesan. OCR adalah seni sekaligus ilmu, dan semakin Anda bermain, semakin baik hasilnya. + +Selamat coding, semoga gambar Anda selalu dapat dibaca! + +## Tutorial Terkait + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Ekstrak Teks dari Gambar – Optimasi OCR dengan Aspose.OCR untuk .NET](/ocr/english/net/ocr-optimization/) +- [Cara Ekstrak Teks dari Gambar dengan Menyiapkan Persegi Panjang dalam OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/indonesian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..c9446217d --- /dev/null +++ b/ocr/indonesian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: Cara menggunakan OCR di C# untuk mengekstrak teks dari file gambar. Pelajari + cara mengenali karakter Cina dari file JPG menggunakan Aspose.OCR dalam beberapa + langkah sederhana. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: id +og_description: Cara menggunakan OCR di C# untuk mengekstrak teks dari file gambar. + Panduan ini menunjukkan cara mengenali karakter Cina dari file JPG menggunakan Aspose.OCR. +og_title: Cara Menggunakan OCR di C# – Mengenali Teks Cina dari JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Cara Menggunakan OCR di C# – Mengenali Teks Cina dari JPG +url: /id/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cara Menggunakan OCR di C# – Mengenali Teks Cina dari JPG + +Pernah bertanya-tanya **bagaimana cara menggunakan OCR** untuk mengambil kata‑kata dari foto yang Anda ambil dengan ponsel? Anda tidak sendirian. Dalam banyak proyek dunia nyata—seperti pemindai kwitansi, aplikasi terjemahan, atau entri data otomatis—Anda akan perlu **mengekstrak teks dari gambar** dengan cepat dan dapat diandalkan. + +Dalam tutorial ini kita akan melewati contoh lengkap yang dapat dijalankan yang **mengenali teks dari file JPG** dan bahkan menangani kasus rumit **mengenali karakter Cina** menggunakan paket bahasa **OCR Chinese Simplified**. Pada akhir tutorial, Anda akan memiliki aplikasi konsol mandiri yang mencetak string yang terdeteksi ke konsol, tanpa perlu mengunduh apa pun secara manual. + +> **Catatan cepat:** Kode ini bekerja dengan Aspose.OCR ≥ 23.7, yang secara otomatis mengunduh sumber daya bahasa pada penggunaan pertama. Jika Anda menggunakan versi yang lebih lama, Anda harus menambahkan bahasa secara manual. + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki: + +- .NET 6.0 SDK atau yang lebih baru (contoh ini menargetkan .NET 6, tetapi .NET 5 juga dapat digunakan) +- Versi terbaru Visual Studio 2022 atau VS Code dengan ekstensi C# +- Koneksi internet untuk pengunduhan bahasa pertama kali +- Gambar JPG yang berisi teks Cina Sederhana (kami akan menyebutnya `chinese_sign.jpg`) + +Itu saja—tanpa mesin OCR berat, tanpa harus mengatur DLL native. Hanya beberapa perintah NuGet dan beberapa baris kode. + +## Langkah 1: Instal Aspose.OCR via NuGet + +Hal pertama yang harus dilakukan: kita memerlukan pustaka OCR. Buka terminal di folder proyek Anda dan jalankan: + +```bash +dotnet add package Aspose.OCR +``` + +Atau, jika Anda lebih suka UI Visual Studio, klik kanan **Dependencies → Manage NuGet Packages**, cari “Aspose.OCR”, dan klik **Install**. + +> **Pro tip:** Jaga paket Anda tetap terbaru. Paket bahasa baru dan perbaikan performa dirilis pada setiap rilis minor. + +## Langkah 2: Buat Proyek Konsol Baru (Jika Belum) + +Jika Anda memulai dari nol, buat aplikasi konsol baru: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Sekarang Anda memiliki file `Program.cs` yang siap untuk kode OCR. + +## Langkah 3: Tulis Kode OCR – Mengenali Chinese Simplified dari JPG + +Buka `Program.cs` dan ganti isinya dengan yang berikut. Setiap baris diberi anotasi sehingga Anda dapat melihat *mengapa* kami melakukan setiap langkah, bukan hanya *apa* yang kami lakukan. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Apa yang terjadi di balik layar? + +- **`OcrEngine.Language`** memberi tahu Aspose kamus mana yang akan dipakai. Dengan memilih `ChineseSimplified`, kami memberi tahu engine untuk menggunakan paket bahasa Chinese Simplified. +- **Unduhan pertama kali**: Ketika `Recognize` dijalankan, SDK akan menghubungi CDN Aspose, mengunduh file bahasa ≈6 MB, menyimpannya secara lokal, lalu melanjutkan OCR. Panggilan selanjutnya akan langsung selesai. +- **`Image.FromFile`** bekerja dengan format raster apa pun yang dapat didekode .NET—JPG, PNG, BMP—sehingga Anda dapat **mengekstrak teks dari gambar** dalam banyak tipe, tidak hanya JPG. + +## Langkah 4: Jalankan Aplikasi dan Verifikasi Output + +Bangun dan jalankan: + +```bash +dotnet run +``` + +Anda seharusnya melihat sesuatu seperti: + +``` +=== Recognized Text === +欢迎光临 +``` + +Jika konsol menampilkan karakter acak atau string kosong, periksa kembali bahwa: + +1. Gambar memang berisi karakter Cina yang jelas dan kontras tinggi. +2. Jalur file sudah benar (tidak ada spasi berlebih atau ekstensi yang hilang). +3. Mesin Anda dapat mengakses `https://download.aspose.com` untuk mengunduh paket bahasa. + +## Langkah 5: Menangani Kasus Tepi dan Kesalahan Umum + +### 5.1 Menghadapi Gambar Berkualitas Rendah + +Akurasi OCR menurun ketika gambar sumber blur, berisik, atau pencahayaannya buruk. Solusi cepat adalah memproses gambar terlebih dahulu: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Menjalankan di Lingkungan Tanpa GUI + +Jika Anda men-deploy ke kontainer Linux tanpa antarmuka grafis, pastikan pustaka `libgdiplus` (yang diperlukan untuk `System.Drawing`) terpasang: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Menyimpan Paket Bahasa Secara Manual + +Anda dapat mengunduh file bahasa sekali saja dan mengarahkan Aspose ke sana melalui API `License`, yang menghilangkan panggilan jaringan satu kali. Ini berguna untuk skenario offline. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Contoh Lengkap yang Berfungsi (Semua dalam Satu) + +Berikut adalah program *lengkap* yang dapat Anda salin‑tempel ke `Program.cs`. Tidak ada bagian tersembunyi, tidak ada skrip eksternal. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Output yang Diharapkan + +Jika JPG berisi frasa “欢迎光临”, konsol akan mencetak: + +``` +=== Recognized Text === +欢迎光临 +``` + +Silakan ganti gambar dengan tanda Cina Sederhana lainnya, nama jalan, atau label produk—engine akan melakukan yang terbaik. + +## Kesimpulan + +Kita baru saja membahas **cara menggunakan OCR** di C# untuk **mengekstrak teks dari gambar**, khususnya mengatasi tantangan **mengenali karakter Cina** dalam sebuah **JPG**. Dengan memanfaatkan unduhan bahasa on‑the‑fly dari Aspose.OCR, Anda dapat menjaga deployment tetap ringan sambil tetap mendukung **OCR Chinese Simplified** secara langsung. + +Apa selanjutnya? Coba ide‑ide berikut: + +- **Pemrosesan batch**: Loop melalui folder gambar dan tulis setiap hasil ke CSV. +- **Gabungkan dengan API terjemahan**: Kirim string yang dikenali ke Azure Translator untuk aplikasi multibahasa waktu nyata. +- **Jelajahi bahasa lain**: Ganti `OcrLanguage.ChineseSimplified` dengan `Japanese` atau `Arabic` dan lihat bagaimana kode yang sama beradaptasi. + +Punya pertanyaan tentang optimasi performa, lisensi, atau integrasi OCR ke layanan web? Tinggalkan komentar di bawah—selamat coding! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + + +## Tutorial Terkait + +- [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/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/indonesian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/indonesian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..f95b859c0 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Pelajari cara melakukan OCR teks Rusia di C# dan mengekstrak teks dari + gambar dengan Aspose OCR. Kode langkah demi langkah untuk mengubah gambar menjadi + teks C# dengan cepat. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: id +og_description: OCR teks Rusia di C# menjadi mudah. Pelajari cara mengekstrak teks + dari gambar, mengonversi gambar menjadi teks C#, dan memuat gambar untuk OCR dengan + Aspose OCR. +og_title: OCR Teks Rusia di C# – Panduan Lengkap Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR Teks Rusia di C# – Panduan Lengkap Menggunakan Aspose OCR +url: /id/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Teks Rusia dalam C# – Panduan Lengkap Menggunakan Aspose OCR + +Pernah perlu melakukan OCR teks Rusia di C# tetapi tidak yakin pustaka mana yang dapat dipercaya? Anda tidak sendirian. Mendapatkan karakter yang bersih dan dapat dibaca dari gambar Cyrillic dapat terasa seperti memecahkan pesan rahasia—terutama jika Anda belum mengatur model bahasa yang tepat. + +Dalam tutorial ini kami akan membimbing Anda melalui contoh praktis yang menunjukkan cara **extract text from image** file, mengonversi *image to text C#* style, dan menangani nuansa pengenalan bahasa Rusia dengan Aspose OCR. Pada akhir tutorial Anda akan memiliki aplikasi console siap‑jalankan yang memuat gambar untuk OCR, mencetak string yang dikenali, dan memberi Anda dasar yang kuat untuk skenario yang lebih maju. + +## Apa yang Akan Anda Pelajari + +- Cara menginstal dan mengonfigurasi **Aspose OCR C#** untuk dukungan bahasa Rusia. +- Langkah‑langkah tepat untuk **load image for OCR** dan memanggil engine. +- Tips untuk menangani jebakan umum seperti sumber daya bahasa yang hilang atau pemindaian yang buram. +- Cara memperluas solusi, seperti pemrosesan batch banyak file atau menyesuaikan ambang kepercayaan. + +Tidak diperlukan pengalaman sebelumnya dengan Aspose; cukup dengan pemahaman dasar tentang C# dan .NET Anda sudah dapat memulai. + +## Prasyarat + +Sebelum kita mulai, pastikan Anda memiliki hal‑hal berikut: + +1. **.NET 6.0** (atau lebih baru) SDK terinstal – kode ini bekerja pada .NET Core dan .NET Framework. +2. **Visual Studio 2022** (atau IDE apa pun yang Anda sukai). +3. Paket NuGet **Aspose.OCR for .NET** – Anda dapat mengambil kunci percobaan gratis dari situs web Aspose. +4. File **model bahasa Rusia** (`rus.traineddata`) – unduh dari halaman sumber Aspose dan letakkan di folder yang akan Anda referensikan nanti. +5. Contoh gambar (`russian_doc.png`) yang berisi teks Cyrillic yang jelas. + +Sudah semua? Bagus—mari kita mulai. + +## Langkah 1: Siapkan Proyek dan Instal Aspose OCR + +First, create a new console project: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Now add the Aspose OCR package: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Jika Anda menggunakan lisensi percobaan, simpan file `Aspose.Total.lic` yang siap pakai; Anda akan memuatnya dalam kode untuk menghindari watermark. + +Setelah paket terinstal, buka `Program.cs`. Anda akan melihat metode `Main` default—ganti isinya dengan kerangka yang akan kami bangun. + +## Langkah 2: Konfigurasikan OCR Engine untuk Bahasa Rusia + +Inti dari operasi ini adalah objek `OcrEngine`. Kita perlu memberi tahu dua hal: bahasa apa yang akan dikenali dan di mana menemukan file model bahasa. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Mengapa ini penting:** Jika Anda melewatkan pengaturan `Language = OcrLanguage.Russian`, engine akan default ke bahasa Inggris, dan karakter Cyrillic akan muncul sebagai simbol yang kacau. `ResourceFolder` menunjuk ke direktori yang berisi file `rus.traineddata`; tanpa itu, Aspose akan melemparkan pengecualian *resource not found*. + +## Langkah 3: Muat Gambar untuk OCR + +Sekarang kita perlu **load image for OCR**. Aspose OCR bekerja dengan `System.Drawing.Image`, jadi Anda dapat memberikan format apa pun yang didukung (PNG, JPEG, BMP, dll.). Pastikan jalur file benar; jalur relatif baik-baik saja jika Anda menempatkan gambar di samping executable. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Kasus khusus:** Jika gambar berukuran besar (lebih dari 5 MB) Anda mungkin ingin memperkecilnya terlebih dahulu. Akurasi OCR menurun ketika DPI terlalu rendah, tetapi file besar dapat menyebabkan tekanan memori. Pengubahan ukuran cepat dapat dilakukan dengan `Graphics` jika diperlukan. + +## Langkah 4: Kenali Teks – Dari Gambar ke Teks Gaya C# + +Dengan engine dikonfigurasi dan gambar dimuat, pengenalan sebenarnya adalah satu panggilan: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +When you run the program (`dotnet run`), you should see something like: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +If the output looks like gibberish, double‑check that: + +- File `rus.traineddata` ada di `ResourceFolder`. +- Gambar tidak terlalu buram; pertimbangkan menerapkan filter binarisasi sederhana sebelum OCR. +- Pengaturan bahasa memang `OcrLanguage.Russian`. + +## Langkah 5: Penyempurnaan dan Jebakan Umum + +### Menyesuaikan Ambang Kepercayaan + +Aspose OCR returns a confidence value per character internally. While the API doesn’t expose it directly, you can enable **detailed output** to see which words were low‑confidence: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +If you notice frequent mis‑recognitions, try: + +- **Pre‑processing**: Konversi gambar ke grayscale, tingkatkan kontras, atau terapkan filter median. +- **Pengaturan DPI**: Pastikan gambar setidaknya 300 DPI untuk skrip Cyrillic. + +### Pemrosesan Batch Banyak Gambar + +If you need to **extract text from image** files in bulk, wrap the recognition logic in a loop: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Sekarang setiap PNG mendapatkan pasangan `.txt`‑nya sendiri—praktis untuk pengarsipan dokumen. + +### Menangani Output Unicode + +Cyrillic characters are Unicode, so make sure your console encoding can display them: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Letakkan baris ini tepat setelah metode `Main` dimulai. Tanpa itu, Anda mungkin melihat tanda tanya (`?`) alih‑alih huruf Rusia. + +## Contoh Lengkap yang Berfungsi + +Below is the complete, ready‑to‑run code. Copy‑paste it into `Program.cs`, adjust the paths, and you’re good to go. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Output yang diharapkan** (asumsi gambar contoh berisi “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Jika Anda melihat hal lain, tinjau kembali tips pemecahan masalah di Langkah 5. + +## Kesimpulan + +Anda kini memiliki contoh lengkap, ujung‑ke‑ujung tentang cara **ocr russian text** di C# menggunakan Aspose OCR. Dari menginstal pustaka, mengonfigurasi model bahasa Rusia, hingga memuat gambar dan mengonversinya menjadi teks Unicode yang bersih, semua bagian telah dibahas. + +Ingat, kunci OCR yang handal adalah bahan sumber yang baik: font yang jelas, DPI yang memadai, dan sumber daya bahasa yang tepat. Setelah Anda menguasai dasar‑dasarnya, Anda dapat memperluas ke pemrosesan batch, mengintegrasikan dengan penyimpanan cloud, atau bahkan menggabungkan dengan AI post‑processing untuk pemeriksaan ejaan. + +### Apa Selanjutnya? + +- Jelajahi opsi lanjutan **aspose ocr c#** seperti analisis tata letak atau output PDF. +- Gabungkan ini dengan alur kerja **extract text from image** di Azure Functions untuk pemrosesan serverless. +- Coba bahasa lain—cukup ganti `OcrLanguage.Russian` ke `OcrLanguage.English` atau kode lain yang didukung. + +Ada pertanyaan atau gambar sulit yang tidak mau bekerja? Tinggalkan komentar di bawah, dan selamat coding! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + +## Tutorial Terkait + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [mengenali gambar teks dengan Aspose OCR untuk banyak bahasa](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Ekstrak Teks dari Gambar Menggunakan Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/indonesian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..c2eeba520 --- /dev/null +++ b/ocr/indonesian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-25 +description: Mengenali teks dari gambar menggunakan Aspose OCR di C#. Pelajari cara + memuat gambar untuk OCR, mengatur bahasa OCR, membuat mesin OCR, dan mengekstrak + teks dari TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: id +og_description: Mengenali teks dari gambar menggunakan Aspose OCR di C#. Tutorial + ini menunjukkan cara membuat mesin OCR, memuat gambar untuk OCR, mengatur bahasa + OCR, dan mengekstrak teks dari TIFF. +og_title: Mengenali teks dari gambar dengan Aspose OCR – Panduan Lengkap C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Mengenali Teks dari Gambar dengan Aspose OCR – Panduan Lengkap C# +url: /id/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# mengenali teks dari gambar dengan Aspose OCR – Panduan Lengkap C# + +Pernah butuh **mengenali teks dari gambar** tetapi tidak yakin perpustakaan mana yang memberikan kecepatan dan akurasi? Anda tidak sendirian. Dalam banyak proyek pemrosesan faktur atau arsip, titik sakit terbesar adalah mendapatkan teks bersih yang dapat dicari dari file TIFF tanpa menulis parser khusus. + +Begini: Aspose OCR untuk .NET membuat seluruh alur kerja menjadi sangat mudah. Dalam panduan ini kami akan membahas semua yang Anda perlukan—menginstal paket, **membuat OCR engine**, memuat TIFF, mengatur bahasa OCR, dan akhirnya **mengekstrak teks dari TIFF**. Pada akhir tutorial Anda akan memiliki aplikasi konsol siap jalankan yang dapat **mengenali teks dari gambar** dalam sekejap. + +## Prasyarat + +- .NET 6.0 atau lebih baru (kode ini juga bekerja dengan .NET Core dan .NET Framework) +- Visual Studio 2022 (atau IDE apa pun yang Anda sukai) +- Aspose.OCR NuGet package (dukungan GPU memerlukan add‑on `Aspose.OCR.Gpu`) +- GPU dengan dukungan CUDA jika Anda menginginkan kecepatan ekstra (opsional namun disarankan) + +> **Tips Pro:** Jika Anda tidak memiliki GPU, cukup hapus baris `GpuDevice` dan engine akan beralih ke CPU secara otomatis. + +## Langkah 1: Instal Aspose OCR dan Buat OCR Engine + +Pertama, tambahkan paket yang diperlukan melalui NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Sekarang kita dapat **membuat OCR engine**. Objek ini adalah inti dari proses; ia menyimpan konfigurasi seperti perangkat yang digunakan dan batas memori. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Mengapa ini penting:** Dengan mengaitkan engine ke GPU, Anda secara signifikan mengurangi waktu yang dibutuhkan untuk **mengenali teks dari gambar**, terutama untuk batch besar TIFF beresolusi tinggi. + +## Langkah 2: Muat Gambar untuk OCR + +Selanjutnya, kita perlu **memuat gambar untuk OCR**. Aspose.OCR bekerja dengan `System.Drawing.Image`, jadi format apa pun yang didukung GDI+ (termasuk TIFF multi‑halaman) dapat digunakan. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Jika Anda menangani TIFF multi‑halaman, Anda dapat melakukan loop melalui halaman menggunakan `image.SelectActiveFrame`, tetapi untuk kebanyakan skenario satu panggilan sudah cukup. + +## Langkah 3: Atur Bahasa OCR + +Engine tidak secara otomatis mengetahui bahasa yang Anda pindai. **Atur bahasa OCR** sebelum menjalankan recognizer; jika tidak, Anda akan mendapatkan output yang berantakan. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Tahukah Anda?** Mengganti bahasa saat runtime tidak memakan biaya—Anda bahkan dapat memproses dokumen campuran bahasa dengan mengubah properti ini antar halaman. + +## Langkah 4: Lakukan Pengakuan – Mengenali Teks dari Gambar + +Sekarang bagian yang menyenangkan: sebenarnya **mengenali teks dari gambar**. Metode `Recognize` mengembalikan string biasa dengan semua karakter yang terdeteksi. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Jika Anda memerlukan skor kepercayaan atau kotak pembatas, Anda dapat menggunakan overload yang mengembalikan objek `OcrResult`, tetapi untuk kebanyakan tugas ekstraksi string biasa sudah cukup. + +## Langkah 5: Ekstrak Teks dari TIFF (dan tangani file multi‑halaman) + +Ketika sumbernya adalah TIFF yang berisi beberapa halaman, Anda perlu mengulangi langkah 2‑4 untuk setiap frame. Berikut loop cepat yang **mengekstrak teks dari TIFF** halaman demi halaman: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Kode di atas mencetak teks yang diekstrak untuk setiap halaman, memudahkan untuk mengalirkan hasil ke basis data atau indeks pencarian. + +## Langkah 6: Tampilkan atau Simpan Teks yang Diekstrak + +Akhirnya, mari **tampilkan teks yang diekstrak** dan opsional menuliskannya ke file untuk pemrosesan selanjutnya. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Menjalankan program harus menampilkan karakter yang dikenali dan membuat `extracted_text.txt` di samping TIFF sumber Anda. + +--- + +## Pertanyaan Umum & Kasus Tepi + +- **Bagaimana jika GPU saya tidak terdeteksi?** + Hapus baris `GpuDevice`; engine akan otomatis beralih ke mode CPU. Performa akan lebih lambat tetapi hasil tetap akurat. + +- **Apakah saya dapat memproses file PNG atau JPEG?** + Tentu—`Image.FromFile` bekerja dengan format apa pun yang didukung System.Drawing, jadi Anda dapat **memuat gambar untuk OCR** terlepas dari ekstensi. + +- **Bagaimana cara menangani pemindaian beresolusi rendah?** + Tingkatkan `ocrEngine.PreprocessOptions.Dpi` sebelum memanggil `Recognize`. DPI yang lebih tinggi memberi engine lebih banyak piksel untuk diproses, meningkatkan akurasi. + +- **Apakah ada batas ukuran TIFF?** + Properti `GpuMemoryLimit` membatasi penggunaan GPU. Jika batas tercapai, engine akan beralih ke CPU untuk halaman yang tersisa. + +## Kesimpulan + +Anda sekarang memiliki potongan kode lengkap, siap produksi yang **mengenali teks dari gambar** menggunakan Aspose OCR dalam C#. Tutorial ini mencakup cara **membuat OCR engine**, **memuat gambar untuk OCR**, **mengatur bahasa OCR**, dan **mengekstrak teks dari TIFF**—semua sambil memanfaatkan percepatan GPU untuk kecepatan. + +Dari sini Anda dapat: + +- Bereksperimen dengan bahasa berbeda (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, dll). +- Mengintegrasikan output ke dalam indeks ElasticSearch yang dapat dicari. +- Menambahkan pasca‑pemrosesan (pemeriksaan ejaan, pembersihan regex) untuk meningkatkan kualitas data. + +Cobalah pada batch faktur Anda sendiri, sesuaikan batas memori, dan saksikan kinerja OCR melambung. Selamat coding! + +## Tutorial Terkait + +- [Ekstrak teks gambar C# dengan pemilihan bahasa menggunakan Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Cara Mengekstrak Teks dari Gambar dengan Menyiapkan Persegi Panjang di OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Ekstrak Teks dari Gambar – Mengenali Garis dengan Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..d8b32329e 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. +### [Crea motore OCR in C# – Guida completa](./create-ocr-engine-in-c-complete-guide/) +Scopri come creare e configurare un motore OCR in C# con Aspose.OCR, passo dopo passo, per estrarre testo da immagini. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/italian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..74df166a9 --- /dev/null +++ b/ocr/italian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Crea un motore OCR in C# e scopri come verificare la modalità di valutazione + e lo stato della licenza in poche righe di codice. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: it +og_description: Crea un motore OCR in C# e visualizza immediatamente come rilevare + la modalità di valutazione e lo stato della licenza. +og_title: Crea un motore OCR in C# – Guida passo‑a‑passo +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Crea un motore OCR in C# – Guida completa +url: /it/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crea un motore OCR in C# – Guida completa + +Ti sei mai chiesto come **create OCR engine** oggetti in C# senza dover setacciare infinite documentazioni? Non sei l'unico. Molti sviluppatori si trovano bloccati quando devono avviare un OCR engine, verificare se è in modalità di prova e mostrare lo stato della licenza agli utenti. + +In questo tutorial percorreremo un esempio conciso, end‑to‑end, che **creates an OCR engine**, verifica la sua **OCR engine evaluation mode**, e stampa un messaggio amichevole sullo stato della licenza. Alla fine avrai un'app console pronta da eseguire e un chiaro modello mentale per gestire le licenze OCR nei tuoi progetti. + +## Cosa imparerai + +- Come istanziare un `OcrEngine` (il nucleo di qualsiasi flusso di lavoro OCR). +- Perché rilevare **evaluation mode** è importante per la conformità e l'esperienza utente. +- Il modo migliore per **check OCR license** lo stato e reagire a situazioni inattese. +- Problemi comuni—riferimenti nulli, gestione delle eccezioni e incompatibilità di versione. + +Nessuno strumento esterno è necessario oltre all'OCR SDK già installato. Se ti trovi a tuo agio con la sintassi base di C#, sei pronto. + +## Prerequisiti + +- .NET 6.0 o successivo (il codice si compila con .NET Core e .NET Framework). +- Un OCR SDK che espone una classe `OcrEngine` con una proprietà `IsEvaluation` (ad esempio, l'ipotetico `MyOcrSdk`). +- Un editor di testo o IDE (Visual Studio, VS Code, Rider—scegli il tuo preferito). + +È tutto. Immergiamoci. + +## Passo 1: Configura un nuovo progetto console + +Per prima cosa, crea una nuova app console così da poter eseguire il codice in isolamento. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Apri il file `Program.cs`. Sostituiremo il suo contenuto con un esempio completo che **creates OCR engine** istanze e gestisce le licenze. + +## Passo 2: Importa lo spazio dei nomi dell'OCR SDK + +Supponendo che l'SDK sia referenziato tramite NuGet (`MyOcrSdk` è un segnaposto), aggiungi la direttiva using in cima al file. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Se non hai ancora aggiunto il pacchetto, esegui: + +```bash +dotnet add package MyOcrSdk +``` + +> **Consiglio:** Mantieni la tua versione SDK aggiornata; le versioni più recenti spesso migliorano il rilevamento della modalità di valutazione. + +## Passo 3: Crea l'istanza dell'OCR Engine + +Ora finalmente **create OCR engine** oggetti. Questo è il cuore di qualsiasi flusso di lavoro OCR—pensalo come il cervello che in seguito leggerà le immagini. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Perché questo passo è cruciale? L'`OcrEngine` incapsula tutta la configurazione, i pacchetti linguistici e i dati di licenza. Senza di esso, non puoi elaborare immagini né interrogare il flag di valutazione. + +> **Nota a margine:** Alcuni SDK consentono di passare un oggetto di configurazione al costruttore (ad esempio, lingua, DPI). Se ti servono impostazioni personalizzate, modifica la riga di conseguenza. + +## Passo 4: Determina la modalità di valutazione dell'OCR Engine + +La maggior parte dei fornitori OCR fornisce una versione di prova che funziona in **evaluation mode** finché non viene fornita una chiave di licenza valida. Sapere se sei in modalità di prova ti permette di mostrare indicazioni UI appropriate o limitare alcune funzionalità. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +La proprietà `IsEvaluation` restituisce `true` quando il motore è non licenziato o utilizza una prova a tempo limitato. È un modo rapido e affidabile per proteggere le funzionalità premium. + +### Cosa succede se la proprietà è assente? + +Versioni più vecchie dell'SDK potrebbero esporre un metodo come `GetLicenseInfo()` invece. In tal caso, ispezioneresti l'oggetto restituito per un flag `IsTrial`. Consulta sempre il changelog dell'SDK quando effettui l'upgrade. + +## Passo 5: Visualizza lo stato attuale della licenza + +Infine, mostriamo all'utente se il motore è licenziato o ancora in prova. Una semplice console write‑line fa al caso, ma puoi adattarla per app GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +L'operatore ternario mantiene il codice ordinato, e i messaggi sono sufficientemente chiari per gli utenti finali o gli sviluppatori che leggono i log. + +## Esempio completo funzionante + +Mettendo tutto insieme, ecco un programma autonomo che puoi copiare‑incollare in `Program.cs` ed eseguire con `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Output previsto + +- **Build di prova:** + `Running in evaluation mode – limited functionality.` + +- **Build licenziata:** + `Licensed – full OCR capabilities enabled.` + +Se l'SDK lancia un'eccezione (ad esempio, DLL nativa mancante), il blocco catch stamperà un messaggio di errore utile invece di far crashare l'intera app. + +## Gestione dei casi limite e delle insidie comuni + +### 1. Istanze di engine nulle + +Anche se il costruttore di solito restituisce un oggetto valido, alcuni SDK possono restituire `null` se le dipendenze native richieste mancano. Proteggiti da questo: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Scadenza della licenza durante l'esecuzione + +Una licenza di prova può scadere a metà sessione. Interroga periodicamente `IsEvaluation` se la tua app rimane attiva per molto tempo. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Nomi di proprietà diversi tra versioni + +Le versioni più vecchie potrebbero esporre `engine.EvaluationMode` o `engine.License.IsTrial`. Quando effettui l'upgrade, cerca nelle note di rilascio dell'SDK eventuali breaking changes. + +### 4. Scenari multi‑thread + +Se avvii diversi worker OCR, istanzia **one OCR engine per thread** a meno che l'SDK supporti esplicitamente la condivisione thread‑safe. Condividere un unico engine può portare a condizioni di race e letture errate della licenza. + +## Consigli professionali per l'uso in produzione + +- **Cache the licensing status** dopo il primo controllo per evitare chiamate di proprietà non necessarie. +- **Log the license key** (mascherata) all'avvio per tracciamenti di audit—aiuta i team di supporto a diagnosticare problemi di licenza. +- **Provide a UI toggle** che informa gli utenti che sono in modalità di prova e offre un pulsante “Buy License”. +- **Automate license renewal** usando l'API di attivazione dell'SDK, se disponibile, per mantenere un'esperienza utente fluida. + +## Conclusione + +Abbiamo appena **created OCR engine** oggetti in poche righe, ispezionato la **OCR engine evaluation mode**, e stampato un chiaro messaggio di **OCR licensing status**. L'esempio completo funziona subito, gestisce gli errori in modo elegante e evidenzia il “perché” di ogni passo—così puoi adattarlo a scenari desktop, web o server. + +Successivamente, potresti esplorare: + +- Alimentare immagini in `engine.Recognize` e gestire il supporto multilingua. +- Usare le API **check OCR license** per attivare programmaticamente una chiave acquistata. +- Integrare con framework UI (WinForms, WPF, MAUI) per mostrare badge di licenza. + +Provali e avrai una solida base OCR pronta per qualsiasi applicazione. Buon coding! + +## Tutorial correlati + +- [Come estrarre OCR – Configurazione OCR](/ocr/english/net/ocr-configuration/) +- [Come ottenere risultati OCR con Aspose.OCR per .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Come fare OCR su PDF in .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/ocr-optimization/_index.md b/ocr/italian/net/ocr-optimization/_index.md index 483493b48..21bf80bac 100644 --- a/ocr/italian/net/ocr-optimization/_index.md +++ b/ocr/italian/net/ocr-optimization/_index.md @@ -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. +### [Preelabora immagine per OCR – Guida completa Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Scopri come pre‑elaborare le immagini per migliorare l'OCR con Aspose in C#, includendo filtri, binarizzazione e correzione dell'orientamento. ## Domande Frequenti diff --git a/ocr/italian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/italian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..60e358974 --- /dev/null +++ b/ocr/italian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Preprocessa l'immagine per l'OCR con Aspose per migliorare l'accuratezza + dell'OCR ed esegui l'OCR su file JPEG. Scopri come estrarre il testo usando Aspose + in un tutorial chiaro, passo dopo passo. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: it +og_description: Preelabora l'immagine per OCR con Aspose per aumentare la precisione + dell'OCR. Segui questa guida per eseguire l'OCR su JPEG ed estrarre il testo usando + Aspose in C#. +og_title: Preelaborazione dell'immagine per OCR – Tutorial Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Preelaborazione dell'immagine per OCR – Guida completa Aspose C# +url: /it/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Preprocessa l'immagine per OCR – Guida completa Aspose C# + +Ti sei mai chiesto come **preprocessare l'immagine per OCR** in modo che il testo risulti pulito ogni volta? Non sei l'unico: gli sviluppatori combattono costantemente scansioni rumorose, JPEG a basso contrasto e illuminazione imprevedibile. La buona notizia? Con qualche piccolo aggiustamento puoi **migliorare la precisione OCR** in modo notevole, e Aspose lo rende indolore. + +In questo tutorial percorreremo un esempio reale che ti mostra come **eseguire OCR su JPEG**, applicare una pipeline di elaborazione immagine personalizzata e, infine, **estrarre il testo usando Aspose**. Alla fine avrai a disposizione uno snippet C# pronto da incollare in qualsiasi progetto .NET. + +## Cosa imparerai + +- Perché la pre‑elaborazione è importante e quali filtri offrono il maggior vantaggio. +- Come configurare `ImageProcessingOptions` di Aspose.OCR per deskew, denoise, binarizzazione e potenziamento del contrasto. +- Il codice esatto necessario per **eseguire OCR su JPEG** e recuperare testo pulito. +- Suggerimenti e insidie per mantenere la tua pipeline OCR robusta in produzione. + +Non è necessaria alcuna esperienza pregressa con Aspose; basta una conoscenza di base di C# e Visual Studio (o il tuo IDE preferito). Iniziamo. + +![Esempio di preprocessare l'immagine per OCR](preprocess-ocr.png "Preprocessa l'immagine per OCR") + +## Passo 1: Configura il motore Aspose.OCR – Preprocessa l'immagine per OCR + +Prima di tutto. Abbiamo bisogno di un'istanza `OcrEngine` e dobbiamo indicare quale lingua ci aspettiamo. Nella maggior parte dei casi l'inglese è quello predefinito, ma puoi cambiarlo con `OcrLanguage` per francese, tedesco, ecc. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Perché è importante:** Il motore è il cuore dell'operazione; senza di esso non puoi applicare nessuno dei filtri immagine che realmente **preprocessano l'immagine per OCR**. Pensalo come la cucina dove tutti gli ingredienti vengono mescolati. + +## Passo 2: Costruisci una pipeline di elaborazione immagine personalizzata – Migliora la precisione OCR + +Ora arriva la parte più interessante. Aspose ti permette di concatenare diversi filtri. Qui abilitiamo quattro dei più efficaci: + +1. **Deskew** – raddrizza documenti inclinati (max 5° di default). +2. **Denoise** – leviga gli sfondi granulosi. +3. **Binarize** – converte l'immagine in bianco‑nero usando una soglia. +4. **ContrastBoost** – fa risaltare i caratteri più deboli. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Consiglio da esperto:** Se le tue immagini di origine sono già nitide, puoi ridurre il valore `Strength` o disattivare completamente un filtro. Un'elaborazione eccessiva può talvolta cancellare i caratteri più deboli, quindi sperimenta con campioni reali. + +## Passo 3: Carica il JPEG (o qualsiasi immagine) ed esegui OCR – Esegui OCR su JPEG + +Aspose funziona con qualsiasi formato immagine leggibile da .NET—JPEG, PNG, BMP, quello che vuoi. Ecco come fornire un file JPEG al motore e avviare il processo di riconoscimento. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Perché JPEG?** La compressione JPEG introduce spesso artefatti che confondono l'OCR. La nostra pipeline di pre‑elaborazione, in particolare i passaggi denoise e binarize, mitiga questi problemi, permettendoti di **eseguire OCR su JPEG** con fiducia. + +## Passo 4: Output del testo riconosciuto – Estrai testo usando Aspose + +Infine, scriviamo semplicemente il testo sulla console, su un file o su qualsiasi servizio a valle. Per scopi dimostrativi, la console è sufficiente. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Quando esegui il programma, dovresti vedere qualcosa di simile: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Se l'output appare confuso, torna al **Passo 2** e regola le impostazioni dei filtri. Piccoli aggiustamenti spesso producono grandi miglioramenti nella **migliorare la precisione OCR**. + +## Casi limite comuni e come gestirli + +| Situazione | Regolazione consigliata | +|-----------|--------------------------| +| **Immagini molto scure** | Aumenta `ContrastBoost.Level` a 1.5 o più. | +| **Inclinazione > 5°** | Alza `DeskewOptions.MaxAngle` (es. 10.0) o ruota manualmente l'immagine prima. | +| **Testo colorato su sfondo colorato** | Usa `BinarizeOptions` con una soglia personalizzata o passa a `AdaptiveBinarizeOptions`. | +| **File di grandi dimensioni ( > 5 MB )** | Carica l'immagine in un `MemoryStream` prima per evitare problemi di lock del file. | + +Questi aggiustamenti mantengono la pipeline flessibile e pronta per il futuro, specialmente quando devi **estrarre testo usando Aspose** da sorgenti diverse. + +## Esempio completo funzionante – Tutti i passaggi in un unico posto + +Di seguito trovi il programma completo, pronto per il copia‑incolla. Compila con .NET 6+ e richiede solo il pacchetto NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Salva questo file come `Program.cs`, aggiungi il pacchetto Aspose.OCR (`dotnet add package Aspose.OCR`) e avvia `dotnet run`. Vedrai il testo pulito stampato sulla console. + +## Riepilogo – Perché questo approccio funziona + +- **Preprocessa l'immagine per OCR**: la pipeline elimina le fonti di errore più comuni (inclinazione, rumore, basso contrasto). +- **Migliora la precisione OCR**: ogni filtro è tarato per aumentare il rapporto segnale‑rumore percepito dal motore. +- **Esegui OCR su JPEG**: anche le immagini compresse diventano leggibili dopo deskew e binarizzazione. +- **Estrai testo usando Aspose**: il metodo `Recognize` restituisce una stringa semplice, pronta per qualsiasi logica a valle. + +Insieme, questi passaggi ti offrono una soluzione OCR affidabile e pronta per la produzione in poche righe di codice. + +## Prossimi passi e argomenti correlati + +- **Elaborazione batch** – Scorri una cartella di immagini e scrivi ogni risultato in un file `.txt`. +- **Pacchetti lingua** – Sostituisci `OcrLanguage.English` con `OcrLanguage.Spanish` o aggiungi dizionari personalizzati. +- **Estrazione da PDF** – Combina Aspose.OCR con Aspose.PDF per estrarre testo direttamente da PDF scansionati. +- **Ottimizzazione delle prestazioni** – Esegui il motore in parallelo usando `Parallel.ForEach` per carichi di lavoro elevati. + +Sentiti libero di sperimentare con i valori dei filtri, provare formati immagine diversi o concatenare filtri aggiuntivi di Aspose come `SharpnessOptions`. Il cielo è il limite una volta che hai padroneggiato le basi. + +--- + +*Buon coding! Se incontri difficoltà, lascia un commento qui sotto e risolveremo insieme.* + +## Tutorial correlati + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/italian/net/text-recognition/_index.md b/ocr/italian/net/text-recognition/_index.md index 346402ba4..d496169c6 100644 --- a/ocr/italian/net/text-recognition/_index.md +++ b/ocr/italian/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Migliora le tue applicazioni .NET con Aspose.OCR per un efficiente riconosciment Sblocca il potenziale dell'OCR in .NET con Aspose.OCR. Estrai testo dai PDF senza sforzo. Scaricalo ora per un'esperienza di integrazione perfetta. ### [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. +### [Riconosci testo da immagine con Aspose OCR – Guida completa C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Scopri come riconoscere testo da immagini usando Aspose OCR in C#, con esempi completi e passaggi dettagliati. +### [Come usare OCR in C# – Riconoscere testo cinese da JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Scopri come utilizzare Aspose.OCR in C# per riconoscere testo cinese da immagini JPG con facilità e precisione. +### [OCR Testo Russo in C# – Guida completa con Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Scopri come riconoscere testo russo da immagini usando Aspose OCR in C#, con esempi dettagliati e passaggi chiari. +### [Estrai testo da immagine in C# – Guida completa Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Scopri come estrarre testo da immagini con Aspose OCR in C#, passo passo, con esempi pratici. +### [Estrai testo da immagine in ASP.NET Core Minimal API – Guida completa](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Scopri come estrarre testo da immagini usando ASP.NET Core Minimal API, con esempi passo passo e integrazione completa di Aspose OCR. +### [Tutorial OCR C#: Estrai testo da ricevute PNG con Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Scopri come utilizzare Aspose OCR in C# per estrarre testo da ricevute in formato PNG, passo passo con esempi pratici. +### [Converti TIFF in Testo in C# – Guida Completa per OCR Batch](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Scopri come convertire file TIFF in testo usando Aspose.OCR in C#, con una guida passo passo per l'elaborazione batch. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/italian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..61ce96501 --- /dev/null +++ b/ocr/italian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: Tutorial OCR in C# che mostra come caricare un file immagine in C# e + riconoscere il testo PNG da una ricevuta usando Aspose OCR – guida passo‑passo. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: it +og_description: Tutorial OCR in C# che ti guida nel caricamento di un file immagine + in C# e nel riconoscimento del testo PNG da una ricevuta usando Aspose OCR. +og_title: Tutorial OCR C# – Estrai il testo dalle ricevute PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# tutorial OCR: estrarre testo da ricevute PNG con Aspose' +url: /it/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tutorial c# OCR – Estrai Testo da Ricevute PNG con Aspose + +Hai mai avuto bisogno di un **c# OCR tutorial** che effettivamente faccia il lavoro senza infinite ricerche su Google? Sei nel posto giusto. In questa guida **load image file c#**, **recognize png text**, e **read receipt OCR** risultati, il tutto mostrando come **perform OCR image** con Aspose OCR. + +Inizieremo installando il pacchetto NuGet necessario, esamineremo ogni riga di codice e termineremo con un dump JSON ordinato che potrai inviare direttamente al tuo prossimo data‑pipeline. Nessuna perdita di tempo, solo una soluzione pratica e pronta all'uso. + +## Cosa Imparerai + +- Come configurare Aspose OCR in un progetto .NET 6 (o successivo). +- I passaggi esatti per **load an image file c#** e passarli al motore. +- Come **recognize png text** da un'immagine di ricevuta e catturare il risultato. +- Modi per **read receipt OCR** l'output in JSON formattato bene. +- Suggerimenti per le operazioni **perform OCR image** su diversi tipi di file e la gestione di problemi comuni. + +**Prerequisiti** +- Visual Studio 2022 (o qualsiasi IDE preferisci). +- .NET 6 SDK o versioni più recenti. +- Un'immagine PNG di una ricevuta a disposizione (la chiameremo `receipt.png`). + +Se li hai, immergiamoci. + +![Screenshot del tutorial c# OCR](ocr-demo.png "Risultato del tutorial c# OCR che mostra l'output JSON") + +## Tutorial c# OCR – Configurazione del Motore Aspose OCR + +Per prima cosa, abbiamo bisogno della libreria Aspose OCR. Apri il terminale nella cartella della soluzione ed esegui: + +```bash +dotnet add package Aspose.OCR +``` + +Quel singolo comando scarica tutto il necessario, inclusi i binari nativi per la decodifica delle immagini. Una volta installato, crea un nuovo progetto console o aggiungi il codice a uno esistente. + +### Perché Aspose? + +Aspose OCR supporta oltre 30 lingue, funziona offline e restituisce un ricco oggetto `OcrResult` — perfetto per le attività **perform OCR image** in cui serve più del semplice testo. + +## Carica file immagine c# e Prepara la Ricevuta + +Ora che la libreria è pronta, **load image file c#**. La classe `System.Drawing.Image` si occupa del lavoro pesante, ma puoi anche usare `SkiaSharp` se preferisci un'alternativa cross‑platform. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Consiglio professionale:** Avvolgi l'`Image` in una dichiarazione `using` (come mostrato) per liberare rapidamente le risorse native — particolarmente importante quando **perform OCR image** su molti file in un ciclo. + +## Riconosci testo PNG con Aspose + +Con l'immagine in memoria, il motore può ora **recognize png text**. Aspose restituisce un `OcrResult` che contiene sia la stringa grezza sia dati dettagliati su ogni parola riconosciuta. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Perché chiamare `RecognizeWithResult` invece del più semplice `Recognize`? Il primo ti dà accesso a punteggi di confidenza, bounding box e interruzioni di riga — utile se in seguito devi **read receipt OCR** per l'estrazione delle righe. + +## Leggi il risultato OCR della ricevuta come JSON + +La maggior parte dei sistemi a valle ama JSON, quindi serializziamo l'`OcrResult`. Il serializer `System.Text.Json` gestisce gli oggetti complessi con eleganza, e abiliteremo l'indentazione per una migliore leggibilità. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Il JSON risultante appare più o meno così (troncato per brevità): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Ora puoi inviare `jsonResult` a un database, a una coda di messaggi, o semplicemente registrarlo per il debug. + +## Esegui l'elaborazione OCR dell'immagine e visualizza l'output + +Infine, stampa il JSON sulla console. In un'applicazione reale probabilmente lo scriveresti su un file o lo invieresti via HTTP, ma la console rende facile verificare che tutto abbia funzionato. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Esegui il programma (`dotnet run`) e dovresti vedere il JSON formattato correttamente stampato. Se l'immagine della ricevuta è chiara, il testo sarà preciso; altrimenti, considera di aumentare la risoluzione dell'immagine o applicare un filtro di pre‑elaborazione (ad es., scala di grigi, aumento del contrasto) prima di passarla al motore. + +### Gestione dei casi limite comuni + +| Situazione | Cosa fare | +|-----------|------------| +| **Image is blurry** | Pre‑process con `System.Drawing` per aumentare la nitidezza o il DPI. | +| **Receipt contains multiple languages** | Imposta `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Large batch processing** | Riutilizza una singola istanza di `OcrEngine`; cambia solo l'`Image` ad ogni iterazione. | +| **Memory pressure** | Rilascia rapidamente gli oggetti `Image` e considera `await Task.Run` per pipeline asincrone. | + +Queste modifiche mantengono il tuo **perform OCR image** flusso di lavoro robusto anche quando l'input non è perfetto. + +## Conclusione + +Congratulazioni — hai appena completato un **c# OCR tutorial** che carica un'immagine, **recognizes png text**, e **reads receipt OCR** l'output come JSON pulito. I passaggi fondamentali (configurazione del motore, caricamento dell'immagine, esecuzione OCR, serializzazione e visualizzazione) costituiscono una solida base che puoi estendere a fatture, passaporti o qualsiasi altro documento scansionato. + +### Cosa c'è dopo? + +- Sperimenta con **load image file c#** usando `SkiaSharp` per un vero supporto cross‑platform. +- Approfondisci `OcrResult.Words` per estrarre voci di riga, prezzi e date — perfetto per le app di tracciamento delle spese. +- Combina questo tutorial con Azure Functions o AWS Lambda per creare un'API serverless di elaborazione delle ricevute. + +Sentiti libero di modificare il codice, aggiungere altre immagini o persino cambiare pacchetto linguistico. Il mondo dell'OCR è pieno di sorprese, e ora hai gli strumenti per esplorarle. + +Buon coding, e che le tue ricevute siano sempre leggibili! + +## Tutorial correlati + +- [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 – Ottimizzazione OCR con Aspose.OCR per .NET](/ocr/english/net/ocr-optimization/) +- [Come usare OCR - Riconosci immagine senza rilevamento dell'area di testo](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/italian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..160edb352 --- /dev/null +++ b/ocr/italian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Converti TIFF in testo usando Aspose.OCR in C#. Impara la conversione + batch di immagini in testo ed estrai il testo dai file TIFF in modo efficiente. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: it +og_description: Converti TIFF in testo con Aspose.OCR. Questa guida mostra la conversione + batch di immagini in testo e come estrarre il testo da file TIFF in poche righe + di C#. +og_title: Converti TIFF in testo in C# – Guida completa all'OCR batch +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Converti TIFF in Testo con C# – Guida Completa all'OCR Batch +url: /it/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertire TIFF in Testo in C# – Guida Completa all'OCR in Batch + +Ti è mai capitato di dover **convertire TIFF in testo** ma non sapevi da dove cominciare? Non sei solo—molti sviluppatori si imbattono nell'OCR batch quando lavorano con documenti scansionati. In questo tutorial ti guideremo passo passo attraverso una soluzione pratica che **estrae testo da file TIFF** usando Aspose.OCR, e lo faremo in parallelo così le cartelle grandi terminano in pochi secondi. + +Tratteremo anche le migliori pratiche per la **conversione batch di immagini in testo**, così alla fine avrai uno snippet riutilizzabile che trasforma un'intera directory di immagini scansionate in ordinati file *.txt*—perfetti per indicizzare, cercare o alimentare analisi successive. + +## Cosa Ti Serve + +- **.NET 6.0** o versioni successive (il codice compila anche su .NET Framework) +- **Aspose.OCR for .NET** NuGet package (`Install-Package Aspose.OCR`) +- Una cartella contenente uno o più file *.tif* (il classico formato di scansione TIFF) +- Il tuo IDE preferito (Visual Studio, VS Code, Rider—quello che preferisci) + +È tutto. Nessun servizio esterno, nessuna chiave API, solo puro C# e Aspose. + +![Screenshot di un file TIFF in elaborazione e del file di testo risultante](/images/ocr-result.png "Risultato OCR che mostra l'output del TIFF convertito in testo") + +*(Testo alternativo: Screenshot che mostra l'output del TIFF convertito in testo sullo schermo)* + +## Passo 1: Configurare il Motore OCR – Convertire TIFF in Testo + +Prima di tutto, abbiamo bisogno di un'istanza di `OcrEngine` che sappia leggere caratteri inglesi. Il motore è il cuore della conversione; configurarlo correttamente garantisce risultati affidabili. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Perché è importante:* +Aspose.OCR supporta decine di lingue. Se lavori con scansioni multilingue, basta cambiare `OcrLanguage.English` con il valore enum appropriato. Lasciare la lingua non definita costringe il motore in modalità auto‑rilevamento, che può essere più lenta e meno accurata. + +## Passo 2: Raccogliere Tutti i File TIFF – Estrarre Testo da TIFF in Modo Efficiente + +Successivamente raccogliamo tutti i file *.tif* da una cartella specificata. Usare `Directory.GetFiles` ci fornisce un array pulito da passare al processore batch. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Consiglio professionale:* Il flag `SearchOption.AllDirectories` può essere usato se le tue scansioni sono annidate in sottocartelle. Ricorda solo che una ricorsione più profonda può aumentare l'uso di memoria durante il passaggio batch. + +## Passo 3: Eseguire OCR in Parallelo – Conversione Batch di Immagini in Testo + +Ora la parte divertente. Aspose.OCR fornisce un helper statico `BatchOcr.RecognizeAll` che accetta un array di percorsi file, un motore e un suggerimento `parallelism`. Avvieremo quattro thread, che su un laptop moderno quad‑core offrono un'accelerazione quasi lineare. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Perché il parallelismo?* +Scansionare un batch di TIFF ad alta risoluzione può richiedere molta CPU. Distribuendo il lavoro su più thread manteniamo tutti i core occupati, riducendo drasticamente il tempo totale di esecuzione. Se lo esegui su un server con più core, aumenta di conseguenza il valore `parallelism`. + +## Passo 4: Scrivere l'Output – Convertire le Immagini Scansionate in File TXT + +Infine iteriamo sul dizionario e scriviamo ogni blocco di testo in un file *.txt* che condivide il nome base originale. Questo è il momento in cui **convert scanned images txt** diventa realtà. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Cosa fa il codice, in italiano semplice + +1. **Crea** un motore OCR impostato per l'inglese. +2. **Raccogli** ogni file TIFF dalla cartella di destinazione. +3. **Esegui** `BatchOcr.RecognizeAll` con quattro thread, trasformando ogni immagine in una stringa. +4. **Itera** sui risultati, sostituendo l'estensione `.tif` con `.txt` e scrivendo la stringa su disco. + +Questo è l'intero flusso di lavoro per **convertire TIFF in testo** in meno di 50 righe di codice. + +## Gestire i Casi Limite – Quando le Cose Non Vanno Liscie + +- **TIFF mancanti o corrotti** – `BatchOcr` solleverà un `OcrException`. Avvolgi la chiamata in un `try / catch` se hai bisogno di una degradazione graduale. +- **Documenti non‑inglesi** – cambia `OcrLanguage.English` in `OcrLanguage.Spanish`, `OcrLanguage.French`, ecc., o usa `OcrLanguage.AutoDetect`. +- **Immagini molto grandi** – considera di ridurre il DPI prima dell'OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) per risparmiare memoria, anche se potresti perdere un po' di precisione. +- **Codifica dell'output** – se ti serve una pagina di codice specifica (es., Windows‑1252), passala a `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Consigli Pro per Conversioni Batch Affidabili + +- **Registra i fallimenti**: crea una `List failedFiles` e aggiungi ogni file che genera un'eccezione; scrivi la lista in un log dopo il ciclo. +- **Riutilizza il motore**: la stessa istanza di `OcrEngine` può essere riutilizzata per molti file; non istanziarla dentro il ciclo. +- **Valida il risultato**: un rapido `if (string.IsNullOrWhiteSpace(extractedText))` può segnalare scansioni vuote o illeggibili. +- **Combina con PDF**: se la tua sorgente è un PDF multi‑pagina, converti prima ogni pagina in TIFF (Aspose.PDF lo fa) e poi esegui questo batch. + +## Prossimi Passi – Oltre la Semplice Conversione + +Ora che puoi **estrarre testo da TIFF** in blocco, potresti voler: + +- Inserire i file *.txt* in un indice di ricerca (Elasticsearch, Azure Cognitive Search). +- Eseguire il rilevamento della lingua su ogni risultato per indirizzare i documenti a pipeline specifiche per locale. +- Generare PDF ricercabili sovrapponendo il testo OCR alle immagini originali (di nuovo Aspose.PDF). + +Tutti questi scenari si basano sulla stessa idea fondamentale: **la conversione batch di immagini in testo** è un blocco fondamentale per sistemi di elaborazione documenti più grandi. + +--- + +### Conclusione + +Hai appena imparato come **convertire TIFF in testo** usando Aspose.OCR, elaborare un'intera cartella in parallelo e salvare ogni risultato in un pulito file *.txt*. La soluzione è leggera, completamente configurabile e pronta per la produzione—che tu stia digitalizzando fatture legacy, archiviando contratti scansionati o alimentando un motore di ricerca testuale. + +Provala, regola il parallelismo e inizia a inserire questi nuovi file di testo nel flusso di lavoro di cui hai bisogno. Buon OCR! + +--- + +## Tutorial Correlati + +- [Estrarre Testo da Immagini Usando l'Operazione OCR su Cartelle](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Estrarre Testo da Immagine – Ottimizzazione OCR con Aspose.OCR per .NET](/ocr/english/net/ocr-optimization/) +- [Estrarre 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/italian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..40a25f475 --- /dev/null +++ b/ocr/italian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-05-25 +description: Scopri come estrarre testo da un'immagine con una API ASP.NET Core minimale. + Carica l'immagine via POST, leggi i dati multipart del form ed esegui l'OCR sull'immagine. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: it +og_description: Estrai il testo da un'immagine usando un'API minimal di ASP.NET Core. + Questa guida mostra come caricare l'immagine tramite POST, leggere i dati multipart/form + e eseguire l'OCR sull'immagine. +og_title: Estrai testo da un'immagine in ASP.NET Core – Passo dopo passo +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Estrai testo da un'immagine in ASP.NET Core Minimal API – Guida completa +url: /it/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Estrarre Testo da Immagine in ASP.NET Core Minimal API – Guida Completa + +Ti sei mai chiesto come **estrarre testo da un'immagine** senza impazzire con framework ingombranti? Non sei l'unico. Molti sviluppatori hanno bisogno di un modo rapido per far caricare all'utente una foto e ottenere subito i caratteri grezzi, sia per la scansione di ricevute, la digitalizzazione di appunti scritti a mano o per alimentare un indice di ricerca. + +In questo tutorial creeremo una piccola ASP.NET Core Minimal API che **carica l'immagine via POST**, analizza il payload *multipart/form‑data* e poi **esegue OCR sull'immagine** usando un singleton `OcrEngine`. Alla fine avrai un'app completamente funzionante che potrai inserire in qualsiasi progetto .NET 8 e iniziare subito a estrarre testo da immagine. + +## Cosa Costruirai + +- Un'app web minimale che ascolta su `/ocr`. +- Un endpoint che accetta un file immagine inviato con una richiesta POST `multipart/form-data`. +- Una logica che legge il file caricato, lo passa al motore OCR e restituisce il risultato in testo semplice. +- Un frammento opzionale per l'accelerazione GPU (commentato) per chi dispone di una scheda compatibile. + +**Prerequisiti** +- .NET 8 SDK (o successivo). +- Familiarità di base con C# e la riga di comando. +- Una libreria OCR che espone una classe `OcrEngine` (l'esempio presuppone un pacchetto NuGet ipotetico). + +Se hai tutto questo, immergiamoci. + +## Passo 1: Configura il Progetto e Aggiungi il Pacchetto OCR + +Per prima cosa, crea un nuovo progetto web e includi la libreria OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Suggerimento:** Mantieni le dipendenze aggiornate. Le versioni più recenti spesso introducono miglioramenti di prestazioni, soprattutto per l'inferenza accelerata da GPU. + +## Passo 2: Registra un Singleton OCR Engine (Servizio Principale) + +Vogliamo un'unica istanza di `OcrEngine` per tutta l'app—non è necessario creare un nuovo motore per ogni richiesta. Registrala nel contenitore dei servizi del builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Perché un singleton?** +Creare un motore OCR può essere costoso—pensa al caricamento dei pesi della rete neurale in memoria. Riutilizzando la stessa istanza risparmi cicli CPU e RAM, il che si traduce in tempi di risposta più rapidi per ogni chiamata a `/ocr`. + +## Passo 3: Costruisci l'Applicazione + +Ora materializziamo l'oggetto `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Quella riga sembra quasi magica, ma dietro le quinte collega il routing, il middleware e il contenitore DI che abbiamo appena configurato. + +## Passo 4: Definisci l'Endpoint POST – “Carica Immagine via POST” + +Ecco il cuore del tutorial: un endpoint che **carica immagine via POST**, legge il payload multipart e passa i dati al motore OCR. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Analisi della Logica + +| Passo | Cosa Succede | Perché è Importante | +|------|--------------|----------------------| +| **ReadFormAsync** | Analizza la richiesta *multipart/form-data* in arrivo. | Senza questo non è possibile accedere ai file caricati. | +| **form.Files["image"]** | Recupera il file il cui nome del campo è `image`. | Garantisce un contratto prevedibile per chi chiama l'endpoint. | +| **Controllo Content‑type** | Verifica che il file sia un'immagine (es. `image/png`). | Impedisce al motore OCR di bloccarsi su dati non‑immagine. | +| **Image.FromStream** | Converte lo stream grezzo in un `System.Drawing.Image`. | La libreria OCR si aspetta un oggetto `Image`, non un array di byte. | +| **ocr.Recognize(img)** | Chiama il motore OCR per **riconoscere testo da immagine**. | Questo è il passaggio centrale per **eseguire OCR sull'immagine**. | +| **Results.Text** | Restituisce la risposta in testo semplice. | Un formato semplice e facilmente consumabile da altri servizi. | + +## Passo 5: Avvia l'API + +Infine, avvia il server web. + +```csharp +app.Run(); +``` + +Quando esegui `dotnet run`, l'API ascolterà su `http://localhost:5000` (o su una porta a tua scelta). Puoi testarla con `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Output previsto:** la console stamperà i caratteri riconosciuti, ad esempio: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Se l'immagine è sfocata o la lingua non è supportata, il motore OCR restituirà una stringa vuota o un messaggio di errore—gestisci questi casi nel codice di produzione. + +## Casi Limite & Buone Pratiche + +### 1. File di grandi dimensioni + +Il limite predefinito del corpo della richiesta è 30 MB. Per scansioni più grandi potresti doverlo modificare: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR Asincrono + +Alcune librerie OCR espongono metodi async (`RecognizeAsync`). Se la tua lo fa, sostituisci `ocr.Recognize(img)` con `await ocr.RecognizeAsync(img)` e marca il lambda come `async`. + +### 3. Considerazioni di Sicurezza + +- **Valida la dimensione del file** prima di caricarlo in memoria. +- **Sanitizza il nome del file** se lo scrivi su disco. +- **Limita la frequenza** delle richieste per evitare attacchi di denial‑of‑service. + +### 4. Accelerazione GPU + +Se decommenti la riga `engine.GpuDevice = new GpuDevice(0);` e il tuo hardware supporta CUDA o DirectML, noterai un notevole aumento di velocità, soprattutto con immagini ad alta risoluzione. + +## Esempio Completo + +Di seguito trovi il file `Program.cs` completo da copiare‑incollare in un nuovo progetto Minimal API. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Salva, esegui `dotnet run` e sei pronto a **estrarre testo da immagine** su richiesta. + +## Conclusione + +Abbiamo percorso una **soluzione completa, end‑to‑end** per estrarre testo da immagine usando ASP.NET Core Minimal API. Partendo dallo scaffolding del progetto, abbiamo **registrato un singleton OCR engine**, costruito un endpoint che **carica immagine via POST**, **legge i dati multipart** e infine **esegue OCR sull'immagine** restituendo testo pulito. + +Da qui puoi: + +- Aggiungere wrapper JSON per risposte più ricche. +- Collegare un database per memorizzare il testo estratto. +- Estendere il supporto a più lingue (`OcrLanguage.Spanish`, ecc.). + +Il pattern scala bene—basta inserire lo stesso endpoint in un microservizio più grande o esporlo dietro un API gateway. + +Hai domande su come gestire PDF, elaborazione batch o ottimizzazione GPU? Lascia un commento, e buona programmazione! + +## Tutorial Correlati + +- [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/italian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/italian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..63dd69ee4 --- /dev/null +++ b/ocr/italian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: Estrai il testo da un'immagine usando C# e Aspose OCR. Scopri come convertire + JPG in testo, caricare l'immagine per l'OCR e ottenere risultati affidabili rapidamente. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: it +og_description: Estrai testo da un'immagine con C#. Questa guida mostra come convertire + jpg in testo, caricare l'immagine per OCR e gestire contenuti multilingue. +og_title: Estrai testo da immagine in C# – Tutorial OCR di Aspose +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Estrai il testo da un'immagine in C# – Guida completa all'OCR di Aspose +url: /it/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Estrai Testo da Immagine in C# – Guida Completa Aspose OCR + +Ti sei mai chiesto come **extract text from image** usando puro codice C#? Non sei l'unico. Che tu stia digitalizzando ricevute, scansionando cartelli o semplicemente curioso dell'OCR, la capacità di estrarre caratteri da una foto è una competenza utile. In questo tutorial percorreremo un esempio completo e eseguibile che mostra esattamente come **extract text from image** con Aspose.OCR, e tratteremo anche come **convert jpg to text**, **load image for OCR**, e risponderemo una volta per tutte alla classica domanda “**how to ocr image**”. + +Alla fine di questa guida avrai un'app console autonoma che legge un file JPEG, riconosce l'ucraino (o qualsiasi altra lingua supportata) e stampa il risultato sulla console. Nessun riferimento vago, nessun pezzo mancante—solo una soluzione completa che puoi copiare‑incollare ed eseguire. + +--- + +## Cosa Imparerai + +* Come installare il pacchetto NuGet Aspose.OCR. +* Il codice esatto necessario per **load image for OCR** in C#. +* Come impostare la lingua e realmente **extract text from image**. +* Trucchi per **convert jpg to text** in modo efficiente. +* Problemi comuni e come evitarli. + +Se hai già un ambiente di sviluppo .NET configurato, sei pronto per immergerti. Altrimenti, la sezione dei prerequisiti qui sotto ti metterà al passo. + +--- + +## Prerequisiti + +| Requisito | Perché è importante | +|-------------|----------------| +| .NET 6.0 SDK (or newer) | Fornisce il runtime per l'app console. | +| Visual Studio 2022 or VS Code | Rende più facile l'editing e il debug. | +| Internet connection (first run) | NuGet deve scaricare Aspose.OCR. | +| A JPEG image you want to process (e.g., `ukrainian_sign.jpg`) | Il file sorgente per il motore OCR. | + +> **Consiglio:** Se sei su Linux o macOS, lo stesso codice funziona con la .NET CLI (`dotnet new console`), quindi sentiti libero di saltare l'IDE pesante. + +--- + +## Passo 1 – Installa Aspose.OCR via NuGet + +Apri il tuo terminale (o la Console di Gestione Pacchetti) ed esegui: + +```bash +dotnet add package Aspose.OCR +``` + +Quella singola riga scarica gli ultimi binari di Aspose.OCR e tutte le dipendenze transitive. Non è necessario gestire manualmente le DLL. + +--- + +## Passo 2 – Crea il Motore OCR (Il Cuore dell'Estrazione) + +Ora che la libreria è a posto, possiamo creare un'istanza di `OcrEngine`. Questo oggetto è responsabile per **extracting text from image** dati. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Perché è importante:** Il motore incapsula gli algoritmi OCR, i modelli linguistici e le opzioni di configurazione. Instanziarlo una volta e riutilizzarlo su più immagini è sia efficiente in termini di memoria sia veloce. + +--- + +## Passo 3 – Carica Immagine per OCR (E Imposta la Lingua) + +Il passo successivo è indicare al motore quale immagine leggere. È qui che entra in gioco la frase **load image for OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Caso limite:** Se il file non esiste, `Image.FromFile` lancia una `FileNotFoundException`. Avvolgi la chiamata in un blocco try‑catch per il codice di produzione. + +--- + +## Passo 4 – Esegui OCR ed Estrai Testo + +Con l'immagine caricata, il motore può ora **extract text from image**. Il metodo `Recognize` fa il lavoro pesante. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Se tutto va bene, `recognizedText` conterrà la rappresentazione in testo semplice di tutto ciò che il motore OCR è riuscito a leggere. + +--- + +## Passo 5 – Converti JPG in Testo (Mettendo Tutto Insieme) + +Il codice che abbiamo costruito finora già **convert jpg to text**, ma avvolgiamolo in un metodo ordinato che puoi chiamare ripetutamente. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Ora puoi semplicemente fare: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Output previsto** (troncato per brevità): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Se l'immagine contiene testo in inglese, cambia `OcrLanguage.English` e vedrai l'output corrispondente. + +--- + +## Passo 6 – Gestire le Domande Comuni “How to OCR Image” + +### 6.1 Posso fare OCR su PNG o BMP? + +Assolutamente. Il metodo `Image.FromFile` supporta tutti i formati riconosciuti da System.Drawing, quindi basta puntare il percorso a un file `.png` o `.bmp` e il resto del codice rimane identico. + +### 6.2 E se l'immagine è a bassa risoluzione? + +L'accuratezza dell'OCR diminuisce drasticamente sotto i 300 dpi. Una soluzione rapida è aumentare la risoluzione dell'immagine con `Graphics` prima di passarla al motore: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Ho bisogno di una licenza per Aspose.OCR? + +Aspose offre una prova gratuita con watermark. Per l'uso in produzione, acquista una licenza e aggiungi: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Esempio Completo Funzionante + +Di seguito trovi un'app console completa, pronta‑da‑eseguire, che dimostra **how to OCR image**, **load image for OCR**, e **convert jpg to text** in un unico pacchetto ordinato. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Come eseguirla** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Dovresti vedere il testo estratto stampato sulla console, confermando che hai estratto con successo **extract text from image** usando C#. + +--- + +## Problemi Comuni & Consigli Pro + +| Problema | Perché succede | Soluzione | +|-------|----------------|-----| +| Output vuoto | Immagine troppo scura o a basso contrasto. | Pre‑processare con `Bitmap` per aumentare la luminosità. | +| Lingua errata | Proprietà `Language` lasciata al valore predefinito English. | Impostare esplicitamente `ocrEngine.Language = OcrLanguage.Ukrainian;` (o la tua lingua target). | +| Errore out‑of‑memory | Immagini molto grandi caricate senza rilascio. | Avvolgere `Image.FromFile` in un blocco `using` (come mostrato). | +| Watermark della licenza | Esecuzione in prova senza licenza. | Applicare una licenza acquistata all'inizio di `Main`. | + +--- + +## Conclusione + +Abbiamo appena coperto tutto ciò di cui hai bisogno per **extract text from image** in C#—dall'installazione di Aspose.OCR, **loading image for OCR**, alla **convert jpg to text** e alla gestione di scenari multilingue. Il programma di esempio completo unisce tutti i componenti, fornendoti una base affidabile per qualsiasi progetto legato all'OCR. + +Successivamente, potresti esplorare: + +* **How to OCR image** stream invece di file (usa `MemoryStream`). +* Aggiungere **c# image to text** post‑processing come il controllo ortografico. +* Integrare il passo OCR in una pipeline più ampia (ad esempio, memorizzare i risultati in un database). + +Sentiti libero di sperimentare con diverse lingue, formati di immagine e trucchi di pre‑elaborazione. L'OCR è tanto un'arte quanto una scienza, e più ti diverti, migliori saranno i risultati. + +Buon coding, e che le tue immagini siano sempre leggibili! + +## Tutorial Correlati + +- [Estrai testo immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Estrai Testo da Immagine – Ottimizzazione OCR con Aspose.OCR per .NET](/ocr/english/net/ocr-optimization/) +- [Come Estrarre Testo da Immagine Preparando Rettangoli in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/italian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..0519ce9f4 --- /dev/null +++ b/ocr/italian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-05-25 +description: Come utilizzare l'OCR in C# per estrarre testo da file immagine. Impara + a riconoscere i caratteri cinesi da un JPG usando Aspose.OCR in pochi semplici passaggi. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: it +og_description: Come utilizzare l'OCR in C# per estrarre testo da file immagine. Questa + guida mostra come riconoscere i caratteri cinesi da un JPG usando Aspose.OCR. +og_title: Come utilizzare l'OCR in C# – Riconoscere il testo cinese da JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Come utilizzare l'OCR in C# – Riconoscere il testo cinese da JPG +url: /it/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Come usare l'OCR in C# – Riconoscere testo cinese da JPG + +Ti sei mai chiesto **come usare l'OCR** per estrarre parole da una foto scattata con il tuo telefono? Non sei l'unico. In molti progetti reali—pensa a scanner di ricevute, app di traduzione o inserimento dati automatizzato—avrai bisogno di **estrarre testo da file immagine** in modo rapido e affidabile. + +In questo tutorial percorreremo un esempio completo e funzionante che **riconosce testo da file JPG** e gestisce anche il caso difficile di **riconoscere caratteri cinesi** usando il pacchetto linguistico **OCR Chinese Simplified**. Alla fine avrai un'app console autonoma che stampa la stringa rilevata nella console, senza download manuali aggiuntivi. + +> **Nota veloce:** Il codice funziona con Aspose.OCR ≥ 23.7, che scarica automaticamente le risorse linguistiche al primo utilizzo. Se usi una versione più vecchia, dovrai aggiungere la lingua manualmente. + +## Prerequisiti + +Prima di iniziare, assicurati di avere: + +- .NET 6.0 SDK o successivo (l'esempio è mirato a .NET 6, ma .NET 5 funziona altrettanto) +- Una versione recente di Visual Studio 2022 o VS Code con l'estensione C# +- Una connessione internet per il primo download della lingua +- Un'immagine JPG che contiene testo cinese semplificato (la chiameremo `chinese_sign.jpg`) + +Tutto qui—nessun motore OCR pesante, nessuna gestione di DLL native. Solo qualche comando NuGet e un paio di righe di codice. + +## Passo 1: Installare Aspose.OCR via NuGet + +Prima di tutto: ci serve la libreria OCR. Apri un terminale nella cartella del progetto e esegui: + +```bash +dotnet add package Aspose.OCR +``` + +Oppure, se preferisci l'interfaccia di Visual Studio, fai clic destro su **Dependencies → Manage NuGet Packages**, cerca “Aspose.OCR” e premi **Install**. + +> **Consiglio professionale:** Mantieni i pacchetti aggiornati. Nuovi pacchetti linguistici e miglioramenti di performance arrivano ad ogni rilascio minore. + +## Passo 2: Creare un nuovo progetto Console (se non l'hai già fatto) + +Se parti da zero, crea una nuova app console: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Ora hai un file `Program.cs` pronto per il codice OCR. + +## Passo 3: Scrivere il codice OCR – Riconoscere Chinese Simplified da un JPG + +Apri `Program.cs` e sostituisci il contenuto con il seguente. Ogni riga è commentata così puoi vedere *perché* facciamo ogni passaggio, non solo *cosa* facciamo. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Cosa succede dietro le quinte? + +- **`OcrEngine.Language`** indica ad Aspose quale dizionario usare. Scegliendo `ChineseSimplified`, istruiamo il motore a cercare il pacchetto linguistico cinese semplificato. +- **Download al primo avvio**: quando `Recognize` viene eseguito, l'SDK contatta il CDN di Aspose, scarica il file linguistico di ≈6 MB, lo memorizza nella cache locale e poi procede con l'OCR. Le chiamate successive sono istantanee. +- **`Image.FromFile`** funziona con qualsiasi formato raster che .NET può decodificare—JPG, PNG, BMP—quindi puoi **estrarre testo da file immagine** di molti tipi, non solo JPG. + +## Passo 4: Eseguire l'applicazione e verificare l'output + +Compila ed esegui: + +```bash +dotnet run +``` + +Dovresti vedere qualcosa del genere: + +``` +=== Recognized Text === +欢迎光临 +``` + +Se la console stampa caratteri incomprensibili o una stringa vuota, ricontrolla che: + +1. L'immagine contenga realmente caratteri cinesi chiari e ad alto contrasto. +2. Il percorso del file sia corretto (nessuno spazio superfluo o estensione mancante). +3. La tua macchina possa raggiungere `https://download.aspose.com` per il pacchetto linguistico. + +## Passo 5: Gestire casi limite e problemi comuni + +### 5.1 Gestire immagini di bassa qualità + +L'accuratezza dell'OCR diminuisce quando l'immagine di origine è sfocata, rumorosa o con scarsa illuminazione. Una soluzione rapida è pre‑processare l'immagine: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Esecuzione in un ambiente headless + +Se distribuisci in un container Linux senza GUI, assicurati che la libreria `libgdiplus` (necessaria per `System.Drawing`) sia installata: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Cache manuale del pacchetto linguistico + +Puoi scaricare il file della lingua una volta e indicare ad Aspose di usarlo tramite l'API `License`, eliminando la chiamata di rete una tantum. Questo è utile per scenari offline. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Esempio completo (tutto in uno) + +Di seguito trovi il programma *completo* che puoi copiare‑incollare in `Program.cs`. Nessun pezzo nascosto, nessuno script esterno. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Output previsto + +Se il JPG contiene la frase “欢迎光临”, la console stamperà: + +``` +=== Recognized Text === +欢迎光临 +``` + +Sentiti libero di sostituire l'immagine con qualsiasi altro segnale cinese semplificato, nome di strada o etichetta prodotto—il motore farà del suo meglio. + +## Conclusione + +Abbiamo appena coperto **come usare l'OCR** in C# per **estrarre testo da file immagine**, affrontando specificamente la sfida di **riconoscere caratteri cinesi** in un **JPG**. Sfruttando il download on‑the‑fly del pacchetto linguistico di Aspose.OCR, puoi mantenere il tuo deployment leggero supportando **OCR Chinese Simplified** fin da subito. + +Qual è il prossimo passo? Prova queste idee: + +- **Elaborazione batch**: cicla su una cartella di immagini e scrivi ogni risultato in un CSV. +- **Combina con API di traduzione**: passa la stringa riconosciuta ad Azure Translator per app multilingue in tempo reale. +- **Esplora altre lingue**: sostituisci `OcrLanguage.ChineseSimplified` con `Japanese` o `Arabic` e osserva come lo stesso codice si adatta. + +Hai domande su ottimizzazione delle prestazioni, licenze o integrazione dell'OCR in un servizio web? Lascia un commento qui sotto—buona programmazione! + +--- + +![Screenshot dell'output della console che mostra come usare l'OCR in C# per riconoscere testo cinese da un'immagine JPG](ocr-chinese-demo.png "output della console OCR") + +## Tutorial correlati + +- [Estrai testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Riconosci testo immagine con Aspose OCR per più lingue](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Come estrarre testo da immagine preparando rettangoli in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/italian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/italian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..c94e08c56 --- /dev/null +++ b/ocr/italian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Impara come eseguire l'OCR di testo russo in C# ed estrarre il testo + da un'immagine con Aspose OCR. Codice passo‑passo per convertire rapidamente un'immagine + in testo C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: it +og_description: OCR del testo russo in C# reso facile. Impara a estrarre il testo + da un'immagine, convertire l'immagine in testo C# e caricare l'immagine per l'OCR + con Aspose OCR. +og_title: OCR del testo russo in C# – Guida completa ad Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR di testo russo in C# – Guida completa all'uso di Aspose OCR +url: /it/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Testo Russo in C# – Guida Completa con Aspose OCR + +Hai mai dovuto fare OCR su testo russo in C# ma non sapevi quale libreria fosse affidabile? Non sei solo. Ottenere caratteri puliti e leggibili da un'immagine cirillica può sembrare decodificare messaggi segreti—soprattutto se non hai impostato il modello linguistico corretto. + +In questo tutorial percorreremo un esempio pratico che mostra come **estrarre testo da immagine** file, convertire *image to text C#* e gestire le sfumature del riconoscimento della lingua russa con Aspose OCR. Alla fine avrai un’app console pronta all’uso che carica un’immagine per OCR, stampa la stringa riconosciuta e ti fornisce una solida base per scenari più avanzati. + +## Cosa Imparerai + +- Come installare e configurare **Aspose OCR C#** per il supporto della lingua russa. +- I passaggi esatti per **caricare immagine per OCR** e chiamare il motore. +- Suggerimenti per gestire problemi comuni come risorse linguistiche mancanti o scansioni sfocate. +- Modi per estendere la soluzione, ad esempio elaborazione batch di più file o regolazione delle soglie di confidenza. + +Non è necessaria alcuna esperienza pregressa con Aspose; basta una familiarità di base con C# e .NET per iniziare. + +## Prerequisiti + +Prima di immergerci, assicurati di avere quanto segue: + +1. **.NET 6.0** (o successivo) SDK installato – il codice funziona sia su .NET Core che su .NET Framework. +2. **Visual Studio 2022** (o qualsiasi IDE preferisci). +3. Un pacchetto NuGet **Aspose.OCR for .NET** – puoi ottenere una chiave di prova gratuita dal sito Aspose. +4. Un file **modello linguistico russo** (`rus.traineddata`) – scaricalo dalla pagina delle risorse Aspose e posizionalo in una cartella che farai riferimento più tardi. +5. Un’immagine di esempio (`russian_doc.png`) contenente testo cirillico chiaro. + +Hai tutto? Ottimo—iniziamo. + +## Passo 1: Configura il Progetto e Installa Aspose OCR + +Per prima cosa, crea un nuovo progetto console: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Ora aggiungi il pacchetto Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Se utilizzi una licenza di prova, tieni a portata di mano il file `Aspose.Total.lic`; lo caricherai nel codice per evitare filigrane. + +Una volta installato il pacchetto, apri `Program.cs`. Vedrai il metodo `Main` predefinito—sostituisci il suo contenuto con lo scheletro che costruiremo. + +## Passo 2: Configura il Motore OCR per la Lingua Russa + +Il cuore dell’operazione è l’oggetto `OcrEngine`. Dobbiamo dirgli due cose: quale lingua riconoscere e dove trovare i file del modello linguistico. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Perché è importante:** Se ometti di impostare `Language = OcrLanguage.Russian`, il motore usa l’inglese per impostazione predefinita e tutti i caratteri cirillici appariranno come simboli incomprensibili. `ResourceFolder` punta alla directory che contiene il file `rus.traineddata`; senza di esso Aspose genera un’eccezione *resource not found*. + +## Passo 3: Carica l'Immagine per OCR + +Ora dobbiamo **caricare immagine per OCR**. Aspose OCR lavora con `System.Drawing.Image`, quindi puoi passare qualsiasi formato supportato (PNG, JPEG, BMP, ecc.). Assicurati che il percorso del file sia corretto; i percorsi relativi vanno bene se mantieni l’immagine accanto all’eseguibile. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Caso limite:** Se l’immagine è grande (oltre 5 MB) potresti volerla ridimensionare prima. L’accuratezza dell’OCR diminuisce quando il DPI è troppo basso, ma file enormi possono causare pressione sulla memoria. Un rapido ridimensionamento può essere eseguito con `Graphics` se necessario. + +## Passo 4: Riconosci il Testo – Da Immagine a Testo Stile C# + +Con il motore configurato e l’immagine caricata, il riconoscimento vero e proprio è una singola chiamata: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Quando esegui il programma (`dotnet run`), dovresti vedere qualcosa del genere: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Se l’output appare incomprensibile, ricontrolla che: + +- Il file `rus.traineddata` sia presente in `ResourceFolder`. +- L’immagine non sia troppo sfocata; considera l’applicazione di un filtro di binarizzazione semplice prima dell’OCR. +- L’impostazione della lingua sia effettivamente `OcrLanguage.Russian`. + +## Passo 5: Ottimizzazione e Problemi Comuni + +### Regolazione della Soglia di Confidenza + +Aspose OCR restituisce un valore di confidenza per ogni carattere internamente. Sebbene l’API non lo esponga direttamente, puoi abilitare **output dettagliato** per vedere quali parole hanno bassa confidenza: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Se noti frequenti errori di riconoscimento, prova a: + +- **Pre‑processare**: Converti l’immagine in scala di grigi, aumenta il contrasto o applica un filtro mediano. +- **Impostazioni DPI**: Assicurati che l’immagine sia almeno a 300 DPI per script cirillici. + +### Elaborazione Batch di Più Immagini + +Se devi **estrarre testo da immagine** in blocco, avvolgi la logica di riconoscimento in un ciclo: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Ora ogni PNG ottiene il proprio file `.txt` corrispondente—utile per l’archiviazione di documenti. + +### Gestione dell'Output Unicode + +I caratteri cirillici sono Unicode, quindi assicurati che la codifica della console possa visualizzarli: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Inserisci questa riga subito dopo l’inizio del metodo `Main`. Senza di essa potresti vedere punti interrogativi (`?`) al posto delle lettere russe. + +## Esempio Completo Funzionante + +Di seguito trovi il codice completo, pronto da eseguire. Copialo in `Program.cs`, regola i percorsi e sei a posto. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Output previsto** (supponendo che l’immagine di esempio contenga “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Se vedi qualcos’altro, rivedi i suggerimenti di risoluzione dei problemi al Passo 5. + +## Conclusione + +Ora disponi di un esempio solido, end‑to‑end, su come **ocr russian text** in C# usando Aspose OCR. Dall’installazione della libreria, alla configurazione del modello linguistico russo, al caricamento dell’immagine e alla conversione in testo Unicode pulito, ogni passaggio è coperto. + +Ricorda, la chiave per un OCR affidabile è materiale di partenza di buona qualità: caratteri chiari, DPI adeguato e risorse linguistiche corrette. Una volta padroneggiati i concetti base, puoi espandere a elaborazione batch, integrazione con storage cloud o persino combinare con post‑processing AI per il controllo ortografico. + +### Cosa Fare Dopo? + +- Esplora le opzioni avanzate di **aspose ocr c#** come l’analisi del layout o l’output PDF. +- Combina questo con flussi di lavoro **extract text from image** in Azure Functions per elaborazione serverless. +- Prova altre lingue—basta cambiare `OcrLanguage.Russian` in `OcrLanguage.English` o in un altro codice supportato. + +Hai domande o un’immagine ostinata che non collabora? Lascia un commento qui sotto, e buona programmazione! + +![esempio di testo OCR russo](ocr-russian-example.png){alt="esempio di testo OCR russo"} + +## Tutorial Correlati + +- [Estrai testo da immagine C# con selezione della lingua usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Riconosci testo da immagine con Aspose OCR per più lingue](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Estrai Testo da Immagine Usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/italian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..301b8782b --- /dev/null +++ b/ocr/italian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: Riconoscere il testo da un'immagine usando Aspose OCR in C#. Scopri come + caricare l'immagine per l'OCR, impostare la lingua dell'OCR, creare il motore OCR + ed estrarre il testo da un TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: it +og_description: Riconoscere il testo da un'immagine usando Aspose OCR in C#. Questo + tutorial mostra come creare il motore OCR, caricare l'immagine per l'OCR, impostare + la lingua OCR ed estrarre il testo da un TIFF. +og_title: Riconosci il testo da un'immagine con Aspose OCR – Guida completa C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Riconoscere il testo da un'immagine con Aspose OCR – Guida completa C# +url: /it/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# riconoscere testo da immagine con Aspose OCR – Guida completa C# + +Hai mai dovuto **riconoscere testo da immagine** ma non sapevi quale libreria ti offrisse sia velocità che precisione? Non sei solo. In molti progetti di elaborazione fatture o archiviazione il problema più grande è ottenere testo pulito e ricercabile da file TIFF senza dover scrivere un parser personalizzato. + +Ecco la questione: Aspose OCR per .NET rende tutta la pipeline un gioco da ragazzi. In questa guida vedremo tutto ciò di cui hai bisogno—installare il pacchetto, **creare il motore OCR**, caricare un TIFF, impostare la lingua OCR e infine **estrarre testo da TIFF**. Alla fine avrai un’app console pronta all’uso che può **riconoscere testo da immagine** in un attimo. + +## Prerequisiti + +- .NET 6.0 o successivo (il codice funziona anche con .NET Core e .NET Framework) +- Visual Studio 2022 (o qualsiasi IDE tu preferisca) +- Pacchetto NuGet Aspose.OCR (il supporto GPU richiede l’add‑on `Aspose.OCR.Gpu`) +- Una GPU con supporto CUDA se desideri la massima velocità (opzionale ma consigliato) + +> **Pro tip:** Se non hai una GPU, basta omettere la riga `GpuDevice` e il motore tornerà automaticamente alla CPU. + +## Step 1: Installare Aspose OCR e creare il motore OCR + +Per prima cosa, aggiungi i pacchetti necessari tramite NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Ora possiamo **creare il motore OCR**. Questo oggetto è il cuore del processo; contiene configurazioni come il dispositivo su cui eseguire e i limiti di memoria. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Perché è importante:** Legando il motore a una GPU riduci drasticamente il tempo necessario per **riconoscere testo da immagine**, soprattutto per grandi lotti di TIFF ad alta risoluzione. + +## Step 2: Caricare l’immagine per OCR + +Successivamente, dobbiamo **caricare l’immagine per OCR**. Aspose.OCR lavora con `System.Drawing.Image`, quindi qualsiasi formato supportato da GDI+ (inclusi i TIFF multi‑pagina) va bene. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Se stai gestendo un TIFF multi‑pagina puoi iterare le pagine usando `image.SelectActiveFrame`, ma per **la maggior parte degli scenari** una singola chiamata è sufficiente. + +## Step 3: Impostare la lingua OCR + +Il motore non sa magicamente quale lingua stai scansionando. **Imposta la lingua OCR** prima di eseguire il riconoscitore; altrimenti otterrai un sacco di output incomprensibile. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Lo sapevi?** Cambiare lingua a runtime è poco costoso—puoi persino elaborare un documento multilingue modificando questa proprietà tra le pagine. + +## Step 4: Eseguire il riconoscimento – Riconoscere testo da immagine + +Ora la parte **divertente**: effettivamente **riconoscere testo da immagine**. Il metodo `Recognize` restituisce una stringa semplice con tutti i caratteri rilevati. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Se ti servono punteggi di confidenza o riquadri delimitanti, puoi usare la sovraccarico che restituisce un oggetto `OcrResult`, ma per la maggior parte delle attività di estrazione la stringa semplice è sufficiente. + +## Step 5: Estrarre testo da TIFF (e gestire file multi‑pagina) + +Quando la sorgente è un TIFF contenente più pagine, dovrai ripetere i passaggi 2‑4 per ogni frame. Ecco un rapido ciclo che **estrae testo da TIFF** pagina per pagina: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Il codice sopra stampa il testo estratto per ogni pagina, rendendo banale l’invio dei risultati a un database o a un indice di ricerca. + +## Step 6: Visualizzare o salvare il testo estratto + +Infine, **visualizziamo il testo estratto** e, opzionalmente, lo scriviamo su file per un’elaborazione successiva. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Eseguire il programma dovrebbe stampare i caratteri riconosciuti e creare `extracted_text.txt` accanto al tuo TIFF di origine. + +--- + +## Domande frequenti e casi particolari + +- **E se la mia GPU non viene rilevata?** + Rimuovi la riga `GpuDevice`; il motore passerà automaticamente alla modalità CPU. Le prestazioni saranno più lente, ma i risultati rimarranno accurati. + +- **Posso elaborare file PNG o JPEG?** + Assolutamente—`Image.FromFile` funziona con qualsiasi formato supportato da System.Drawing, quindi puoi **caricare l’immagine per OCR** indipendentemente dall’estensione. + +- **Come gestire scansioni a bassa risoluzione?** + Incrementa `ocrEngine.PreprocessOptions.Dpi` prima di chiamare `Recognize`. Un DPI più alto fornisce al motore più pixel su cui lavorare, migliorando la precisione. + +- **C’è un limite alle dimensioni del TIFF?** + La proprietà `GpuMemoryLimit` limita l’uso della GPU. Se raggiungi il limite, il motore passerà alla CPU per le pagine rimanenti. + +--- + +## Conclusione + +Ora disponi di uno snippet completo, pronto per la produzione, che **riconosce testo da immagine** usando Aspose OCR in C#. Il tutorial ha coperto come **creare il motore OCR**, **caricare l’immagine per OCR**, **impostare la lingua OCR** e **estrarre testo da TIFF**—tutto sfruttando l’accelerazione GPU per la velocità. + +Da qui potresti: + +- Sperimentare con lingue diverse (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, ecc.). +- Integrare l’output in un indice ElasticSearch ricercabile. +- Aggiungere post‑processing (controllo ortografico, pulizia con regex) per migliorare la qualità dei dati. + +Provalo sul tuo lotto di fatture, regola i limiti di memoria e osserva le prestazioni OCR decollare. Buon coding! + +## Tutorial correlati + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..7a2a52e3e 100644 --- a/ocr/japanese/net/ocr-configuration/_index.md +++ b/ocr/japanese/net/ocr-configuration/_index.md @@ -61,6 +61,7 @@ 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# で OCR エンジンを作成する – 完全ガイド](./create-ocr-engine-in-c-complete-guide/) ### 一般的なユースケース - **Extract text images** スキャンした請求書からテキストを抽出し、会計業務を自動化。 @@ -104,4 +105,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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/japanese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..a52d4ec2b --- /dev/null +++ b/ocr/japanese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-25 +description: C#でOCRエンジンを作成し、数行のコードで評価モードとライセンス状態の確認方法を学びましょう。 +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: ja +og_description: C#でOCRエンジンを作成し、評価モードの検出方法とライセンス状態の表示をすぐに確認できます。 +og_title: C#でOCRエンジンを作成する – ステップバイステップガイド +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: C#でOCRエンジンを作成する – 完全ガイド +url: /ja/net/ocr-configuration/create-ocr-engine-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#** で作成したいと思ったことはありませんか? あなただけではありません。多くの開発者が、OCR エンジンを起動し、トライアルモードかどうかを確認し、ライセンス状態をユーザーに表示する際に壁にぶつかります。 + +このチュートリアルでは、**OCR エンジンを作成し**、その **OCR エンジン評価モード** をチェックし、ライセンス状態に関するフレンドリーなメッセージを出力する、簡潔なエンドツーエンドの例を順に解説します。最後まで読めば、すぐに実行できるコンソールアプリが手に入り、独自プロジェクトで OCR ライセンスを扱うための明確な考え方が身につきます。 + +## 学べること + +- `OcrEngine`(OCR ワークフローの核)をインスタンス化する方法。 +- **評価モード** の検出がコンプライアンスとユーザー体験にとって重要な理由。 +- **OCR ライセンス** の状態を確認し、予期しない状態に対処するベストプラクティス。 +- よくある落とし穴—null 参照、例外処理、バージョン不一致。 + +必要なのは、すでにインストール済みの OCR SDK だけです。基本的な C# 文法に慣れていればすぐに始められます。 + +## 前提条件 + +- .NET 6.0 以降(コードは .NET Core と .NET Framework の両方でコンパイル可能)。 +- `OcrEngine` クラスと `IsEvaluation` プロパティを公開する OCR SDK(例として仮想の `MyOcrSdk`)。 +- テキストエディタまたは IDE(Visual Studio、VS Code、Rider などお好みで)。 + +以上です。さっそく始めましょう。 + +## 手順 1: 新しいコンソールプロジェクトを作成 + +まず、コードを単体で実行できるように新しいコンソールアプリを作成します。 + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +生成された `Program.cs` を開きます。内容を **OCR エンジン** のインスタンス作成とライセンス処理の完全例に置き換えます。 + +## 手順 2: OCR SDK の名前空間をインポート + +SDK が NuGet で参照されていると仮定し(`MyOcrSdk` はプレースホルダーです)、ファイルの先頭に using ディレクティブを追加します。 + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +まだパッケージを追加していない場合は、次のコマンドを実行してください。 + +```bash +dotnet add package MyOcrSdk +``` + +> **プロのコツ:** SDK のバージョンは常に最新に保ちましょう。新しいリリースは評価モード検出の改善が含まれることが多いです。 + +## 手順 3: OCR エンジン インスタンスを作成 + +いよいよ **OCR エンジン** オブジェクトを **作成** します。これはすべての OCR ワークフローの中心であり、画像を読み取る「脳」に相当します。 + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +なぜこのステップが重要かというと、`OcrEngine` はすべての設定、言語パック、ライセンス情報をカプセル化しています。これがなければ画像処理も評価フラグの取得もできません。 + +> **サイドノート:** 一部の SDK ではコンストラクタに設定オブジェクト(例: 言語、DPI)を渡すことができます。カスタム設定が必要な場合はこの行を調整してください。 + +## 手順 4: OCR エンジンの評価モードを判定 + +多くの OCR ベンダーは有効なライセンスキーが提供されるまで **評価モード**(トライアル)で動作します。トライアルかどうかを把握すれば、適切な UI 表示や機能制限が可能です。 + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation` プロパティは、エンジンが未ライセンスまたは時間制限付きトライアルの場合に `true` を返します。プレミアム機能を保護するシンプルかつ確実な方法です。 + +### プロパティが存在しない場合は? + +古い SDK では `GetLicenseInfo()` のようなメソッドが提供されていることがあります。その場合は返却オブジェクトの `IsTrial` フラグを確認してください。バージョンアップ時は必ず SDK の変更ログを確認しましょう。 + +## 手順 5: 現在のライセンス状態を表示 + +最後に、エンジンがライセンス済みかトライアルかをユーザーに示します。コンソールへの一行出力で十分ですが、GUI アプリ向けに応用も可能です。 + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +三項演算子を使うことでコードがすっきりし、メッセージはエンドユーザーや開発者がログを見る際にも分かりやすくなります。 + +## 完全動作サンプル + +すべてをまとめた、`Program.cs` に貼り付けて `dotnet run` で実行できる自己完結型プログラムです。 + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### 期待される出力 + +- **トライアルビルド:** + `Running in evaluation mode – limited functionality.` + +- **ライセンスビルド:** + `Licensed – full OCR capabilities enabled.` + +SDK が例外(例: ネイティブ DLL が見つからない)をスローした場合は、catch ブロックがクラッシュせずに有用なエラーメッセージを出力します。 + +## エッジケースと一般的な落とし穴の対処 + +### 1. Null エンジン インスタンス + +コンストラクタは通常有効なオブジェクトを返しますが、必須のネイティブ依存関係が欠如していると `null` が返る SDK もあります。以下のようにガードしましょう。 + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. 実行中のライセンス期限切れ + +トライアルライセンスはセッション途中で期限切れになることがあります。長時間稼働するアプリでは定期的に `IsEvaluation` を再取得してください。 + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. バージョン間でのプロパティ名の違い + +古いリリースでは `engine.EvaluationMode` や `engine.License.IsTrial` が使用されることがあります。アップグレード時は SDK のリリースノートで破壊的変更を検索しましょう。 + +### 4. マルチスレッドシナリオ + +複数の OCR ワーカーを起動する場合、SDK が明示的にスレッドセーフ共有をサポートしていない限り、**スレッドごとに 1 つの OCR エンジンをインスタンス化**してください。単一エンジンの共有は競合状態や誤ったライセンス判定を招く可能性があります。 + +## 本番環境でのプロチップ + +- **ライセンス状態は最初のチェック後にキャッシュ** して、不要なプロパティ呼び出しを減らす。 +- **起動時にライセンスキー(マスク済み)をログ** に残すことで、監査トレイルが確保でき、サポートチームがライセンス問題を診断しやすくなる。 +- **UI トグル** を提供し、ユーザーにトライアルモードであることを通知しつつ「ライセンス購入」ボタンを表示する。 +- SDK が提供するアクティベーション API が利用可能なら **ライセンス自動更新** を実装し、シームレスなユーザー体験を実現する。 + +## 結論 + +数行のコードで **OCR エンジン** を作成し、**OCR エンジン評価モード** を確認し、明確な **OCR ライセンス状態** メッセージを出力する方法を学びました。完全なサンプルはすぐに動作し、エラーを優雅に処理し、各ステップの「なぜ」を示すことで、デスクトップ、Web、サービス側シナリオへ柔軟に適用できます。 + +次に挑戦できること: + +- `engine.Recognize` に画像を渡し、マルチランゲージ対応を試す。 +- **check OCR license** API を使って購入済みキーをプログラム的に有効化する。 +- UI フレームワーク(WinForms、WPF、MAUI)と統合し、ライセンスバッジを表示する。 + +ぜひ試してみて、あらゆるアプリケーションに対応できる堅牢な OCR 基盤を手に入れてください。ハッピーコーディング! + +## 関連チュートリアル + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/ocr-optimization/_index.md b/ocr/japanese/net/ocr-optimization/_index.md index 37e939040..951b15248 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 結果を文書として簡単に保存できます。 +### [OCR 用画像の前処理 – 完全な Aspose C# ガイド](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Aspose.OCR を使用して画像を前処理し、OCR の精度を最大化する方法をステップバイステップで解説します。 ## よくある質問 diff --git a/ocr/japanese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/japanese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..6b8622b24 --- /dev/null +++ b/ocr/japanese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,227 @@ +--- +category: general +date: 2026-05-25 +description: Aspose を使用して画像を前処理し、OCR の精度を向上させ、JPEG ファイルで OCR を実行します。Aspose を使ったテキスト抽出方法を、分かりやすいステップバイステップのチュートリアルで学びましょう。 +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: ja +og_description: Asposeで画像を前処理してOCR精度を向上させましょう。このガイドに従って、JPEGに対してOCRを実行し、C#でAsposeを使用してテキストを抽出します。 +og_title: OCR用画像前処理 – Aspose C# チュートリアル +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: OCR用画像前処理 – 完全なAspose C# ガイド +url: /ja/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR 用画像前処理 – 完全 Aspose C# ガイド + +画像からテキストを常にきれいに抽出できるように **OCR 用画像前処理** を行う方法をご存知ですか? 開発者はノイズの多いスキャン、コントラストの低い JPEG、予測できない照明条件と日々格闘しています。 良いニュースは、いくつかの賢い調整で **OCR の精度を大幅に向上** させられ、Aspose がそれを簡単にしてくれることです。 + +このチュートリアルでは、実際の例を通して **JPEG 画像で OCR を実行** し、カスタム画像処理パイプラインを適用し、最終的に **Aspose を使用してテキストを抽出** する方法を解説します。 最後まで読めば、任意の .NET プロジェクトに貼り付けられる C# スニペットが手に入ります。 + +## 学べること + +- 前処理が重要な理由と、最大の効果をもたらすフィルタはどれか。 +- デスキュー、デノイズ、二値化、コントラスト強調のために Aspose.OCR の `ImageProcessingOptions` を設定する方法。 +- **JPEG ファイルで OCR を実行** し、クリーンなテキストを取得するための正確なコード。 +- 本番環境で OCR パイプラインを堅牢に保つためのコツと落とし穴。 + +Aspose の事前知識は不要です。C# の基本と Visual Studio(またはお好みの IDE)があれば始められます。さあ、始めましょう。 + +![OCR 用画像前処理の例](preprocess-ocr.png "OCR 用画像前処理") + +## Step 1: Aspose.OCR エンジンのセットアップ – Preprocess Image for OCR + +まず最初に `OcrEngine` インスタンスを作成し、対象言語を指定します。ほとんどの場合デフォルトは英語ですが、`OcrLanguage` 列挙体を変更すればフランス語やドイツ語などに切り替えられます。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**なぜ重要か:** エンジンは処理の中心です。エンジンがなければ、実際に **OCR 用画像前処理** を行う画像フィルタを適用できません。すべての材料が混ざるキッチンと考えてください。 + +## Step 2: カスタム画像処理パイプラインの構築 – Improve OCR Accuracy + +ここからが本番です。Aspose では複数のフィルタをチェーンできます。以下の 4 つが最も効果的です。 + +1. **Deskew** – 傾いた文書を真っ直ぐにします(デフォルト最大 5°)。 +2. **Denoise** – 粒状の背景を滑らかにします。 +3. **Binarize** – しきい値で画像を白黒に変換します。 +4. **ContrastBoost** – 薄い文字を際立たせます。 + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**プロのコツ:** ソース画像がすでに鮮明な場合は `Strength` を下げるか、フィルタ自体をオフにできます。過剰な処理は薄い文字を消してしまうことがあるので、実サンプルで試行錯誤してください。 + +## Step 3: JPEG(または任意の画像)を読み込んで OCR を実行 – Run OCR on JPEG + +Aspose は .NET が読み込めるすべての画像形式に対応しています—JPEG、PNG、BMP など。以下は JPEG ファイルをエンジンに渡し、認識プロセスを開始する方法です。 + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**なぜ JPEG?** JPEG 圧縮は OCR を混乱させるアーティファクトを生むことが多いです。特にデノイズと二値化のステップがそれらの問題を緩和し、**JPEG で OCR を実行** できるようにします。 + +## Step 4: 認識結果のテキストを出力 – Extract Text Using Aspose + +最後に、テキストをコンソール、ファイル、または任意の下流サービスに書き出します。デモとしてはコンソール出力で十分です。 + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +プログラムを実行すると、次のような出力が得られます。 + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +出力が文字化けしている場合は **Step 2** に戻り、フィルタ設定を調整してください。小さな調整が **OCR 精度の向上** に大きく寄与します。 + +## よくあるケースと対処法 + +| 状況 | 推奨調整 | +|-----------|----------------------| +| **非常に暗い画像** | `ContrastBoost.Level` を 1.5 以上に上げる | +| **傾きが 5° 超** | `DeskewOptions.MaxAngle` を 10.0 などに上げるか、事前に画像を回転させる | +| **背景と文字が同系色** | カスタムしきい値で `BinarizeOptions` を使用するか、`AdaptiveBinarizeOptions` に切り替える | +| **大容量ファイル(> 5 MB)** | `MemoryStream` に読み込んでから処理し、ファイルロックを回避する | + +これらの調整により、さまざまなソースから **Aspose を使用してテキストを抽出** する際にもパイプラインが柔軟かつ将来にわたって安定します。 + +## 完全動作サンプル – All Steps in One Place + +以下はコピー&ペーストでそのまま使える完全版プログラムです。.NET 6+ でコンパイルでき、`Aspose.OCR` NuGet パッケージだけが必要です。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +`Program.cs` として保存し、`dotnet add package Aspose.OCR` でパッケージを追加、`dotnet run` を実行してください。クリーンなテキストがコンソールに表示されます。 + +## まとめ – なぜこの手法が有効か + +- **OCR 用画像前処理**: パイプラインが最も一般的なエラー要因(傾き、ノイズ、低コントラスト)を除去します。 +- **OCR 精度の向上**: 各フィルタがエンジンが見る信号対雑音比を高めます。 +- **JPEG で OCR を実行**: 圧縮画像でもデスキューと二値化で可読性が向上します。 +- **Aspose を使用してテキストを抽出**: `Recognize` メソッドがプレーン文字列を返し、任意の下流ロジックにすぐ利用可能です。 + +これらの手順を組み合わせるだけで、数行のコードで信頼性の高い本番レベル OCR ソリューションが構築できます。 + +## 次のステップと関連トピック + +- **バッチ処理** – フォルダー内の画像をループし、各結果を `.txt` ファイルに書き出す。 +- **言語パック** – `OcrLanguage.English` を `OcrLanguage.Spanish` に変更したり、カスタム辞書を追加したりする。 +- **PDF 抽出** – Aspose.OCR と Aspose.PDF を組み合わせて、スキャン PDF から直接テキストを取得。 +- **パフォーマンスチューニング** – 大量処理では `Parallel.ForEach` を使ってエンジンを並列実行。 + +フィルタ値をいじったり、別の画像形式を試したり、`SharpnessOptions` などの追加フィルタをチェーンしたりして、自由に実験してください。基本をマスターすれば、可能性は無限です。 + +--- + +*Happy coding! If you hit any snags, drop a comment below and we’ll troubleshoot together.* + +## 関連チュートリアル + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/japanese/net/text-recognition/_index.md b/ocr/japanese/net/text-recognition/_index.md index 5738b2ecf..6ce509100 100644 --- a/ocr/japanese/net/text-recognition/_index.md +++ b/ocr/japanese/net/text-recognition/_index.md @@ -54,10 +54,25 @@ Aspose.OCR を使用して .NET アプリケーションを強化し、画像テ ### [OCR画像認識でPDFを認識する](./recognize-pdf/) Aspose.OCR を使用して、.NET での OCR の可能性を解き放ちます。 PDF からテキストを簡単に抽出します。今すぐダウンロードして、シームレスな統合エクスペリエンスを体験してください。 ### [OCR画像認識でのテーブルの認識](./recognize-table/) -OCR 画像認識におけるテーブルの認識に関する包括的なガイドを使用して、Aspose.OCR for .NET の可能性を解き放ちます。 +OCR 画像認識におけるテーブルの認識に関する包括的なガイドを使用して、Aspose.OCR for .NET の可能性を解放します。 +### [Aspose OCR で画像からテキストを認識する – 完全 C# ガイド](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Aspose OCR と C# を使って画像からテキストを抽出する手順を詳しく解説します。初心者でもすぐに実装可能です。 +### [C# で画像からテキストを抽出する – 完全 Aspose OCR ガイド](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Aspose OCR と C# を使用して、画像からテキストを抽出する手順を詳しく解説します。初心者でもすぐに実装可能です。 +### [C# で OCR を使用する – JPG から中国語テキストを認識する](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Aspose.OCR と C# を使用して、JPG 画像から中国語テキストを抽出する手順をステップバイステップで解説します。 +### [C# で OCR ロシア語テキスト – 完全ガイド](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Aspose OCR と C# を使用して、画像からロシア語テキストを抽出する手順をステップバイステップで解説します。 +### [ASP.NET Core Minimal API で画像からテキストを抽出する – 完全ガイド](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Aspose OCR と ASP.NET Core Minimal API を使用して、画像からテキストを抽出する手順を詳しく解説します。初心者でもすぐに実装可能です。 +### [C# OCR チュートリアル – PNG レシートからテキストを抽出する](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Aspose OCR と C# を使用して、PNG 形式のレシート画像からテキストを抽出する手順を詳しく解説します。初心者でもすぐに実装可能です。 +### [C# で TIFF をテキストに変換する – 完全バッチ OCR ガイド](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Aspose.OCR を使用して、TIFF 画像をバッチ処理でテキストに変換する手順をステップバイステップで解説します。 + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/japanese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..90ae55097 --- /dev/null +++ b/ocr/japanese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-25 +description: C# OCRチュートリアル:画像ファイルをC#で読み込み、Aspose OCRを使用してレシートのPNGテキストを認識する方法をステップバイステップで解説。 +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: ja +og_description: C# OCRチュートリアルで、画像ファイルの読み込みからレシートのPNGテキストをAspose OCRで認識する方法をステップバイステップで解説します。 +og_title: c# OCR チュートリアル – PNG領収書からテキストを抽出 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR チュートリアル: Aspose を使用した PNG レシートからテキストを抽出' +url: /ja/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR チュートリアル – Aspose を使用した PNG レシートからのテキスト抽出 + +実際に作業を完了できる **c# OCR tutorial** が必要だったことはありませんか? 無限に検索する必要はありません。ここが正しい場所です。このガイドでは **load image file c#**、**recognize png text**、そして **read receipt OCR** の結果を取得し、Aspose OCR を使用した **perform OCR image** 処理のやり方も紹介します。 + +まず必要な NuGet パッケージをインストールし、コードの各行を順に解説し、次のデータパイプラインに直接流し込める整った JSON ダンプで締めくくります。余計な説明は省き、実用的ですぐに実行できるソリューションです。 + +## 学べること + +- .NET 6(またはそれ以降)プロジェクトで Aspose OCR をセットアップする方法。 +- **load an image file c#** の正確な手順とエンジンへの渡し方。 +- レシート画像から **recognize png text** し、結果を取得する方法。 +- **read receipt OCR** の出力を見やすい JSON 形式にする方法。 +- さまざまなファイルタイプで **perform OCR image** 操作を行うコツと一般的な落とし穴への対処法。 + +**Prerequisites** +- Visual Studio 2022(またはお好みの IDE)。 +- .NET 6 SDK 以上。 +- 手元に PNG のレシート画像(`receipt.png` と呼びます)。 + +これらが揃っていれば、さっそく始めましょう。 + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR チュートリアル – Aspose OCR エンジンのセットアップ + +まず最初に、Aspose OCR ライブラリが必要です。ソリューションフォルダーでターミナルを開き、次のコマンドを実行してください: + +```bash +dotnet add package Aspose.OCR +``` + +この単一コマンドで、画像デコード用のネイティブバイナリを含むすべての必要なものが取得されます。インストールが完了したら、新しいコンソールプロジェクトを作成するか、既存のプロジェクトにコードを追加してください。 + +### なぜ Aspose なのか? + +Aspose OCR は 30 以上の言語をサポートし、オフラインでも動作し、リッチな `OcrResult` オブジェクトを返します。プレーンテキスト以上の情報が必要な **perform OCR image** タスクに最適です。 + +## Load image file c# とレシートの準備 + +ライブラリの準備ができたので、**load image file c#** を行いましょう。`System.Drawing.Image` クラスが主な処理を担当しますが、クロスプラットフォームの代替として `SkiaSharp` を使用することも可能です。 + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** `Image` を `using` 文でラップ(上記参照)して、ネイティブリソースを速やかに解放しましょう。特に多数のファイルをループで **perform OCR image** する場合に重要です。 + +## Aspose で PNG テキストを認識する + +画像がメモリ上にある状態で、エンジンは **recognize png text** を実行できます。Aspose は、生の文字列と認識された各単語の詳細データを含む `OcrResult` を返します。 + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +`Recognize` の代わりに `RecognizeWithResult` を呼び出す理由は何でしょうか? 前者は信頼度スコア、バウンディングボックス、改行情報にアクセスでき、後で **read receipt OCR** を使用して項目抽出を行う際に便利です。 + +## レシート OCR 結果を JSON として読む + +多くの下流システムは JSON を好むため、`OcrResult` をシリアライズしましょう。`System.Text.Json` シリアライザーは複雑なオブジェクトをうまく処理し、可読性のためにインデントを有効にします。 + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +生成された JSON は以下のようになります(簡略化しています)。 + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +これで `jsonResult` をデータベースやメッセージキューに流し込んだり、デバッグ用にログ出力したりできます。 + +## OCR 画像処理を実行し、出力を表示する + +最後に、JSON をコンソールに出力します。実際のアプリではファイルに書き込んだり HTTP で送信したりすることが多いですが、コンソール出力ならすべてが正しく動作したか簡単に確認できます。 + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +プログラムを実行(`dotnet run`)すると、整形された JSON が表示されます。レシート画像が鮮明であればテキストは正確に認識されますが、そうでない場合は画像解像度を上げるか、エンジンに渡す前に前処理フィルタ(例:グレースケール、コントラスト強化)を適用することを検討してください。 + +### 一般的なエッジケースへの対処 + +| Situation | What to do | +|-----------|------------| +| **画像がぼやけている** | `System.Drawing` で前処理し、シャープ化または DPI を上げます。 | +| **レシートに複数言語が含まれる** | `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` を設定します。 | +| **大量バッチ処理** | `OcrEngine` のインスタンスを再利用し、各イテレーションで `Image` のみを差し替えます。 | +| **メモリ負荷** | `Image` オブジェクトを速やかに破棄し、非同期パイプラインでは `await Task.Run` の使用を検討します。 | + +これらの調整により、入力が完璧でなくても **perform OCR image** ワークフローを堅牢に保てます。 + +## まとめ + +おめでとうございます。画像をロードし、**recognizes png text** を行い、**reads receipt OCR** の出力をクリーンな JSON として取得する **c# OCR tutorial** を完了しました。エンジンのセットアップ、画像の読み込み、OCR の実行、シリアライズ、表示という基本的な手順は、請求書やパスポート、その他のスキャン文書へ拡張できる堅実な基盤となります。 + +### 次のステップは? + +- `SkiaSharp` を使用した **load image file c#** を試して、真のクロスプラットフォームサポートを実現しましょう。 +- `OcrResult.Words` をさらに掘り下げ、項目、価格、日付を抽出します。経費管理アプリに最適です。 +- このチュートリアルを Azure Functions や AWS Lambda と組み合わせ、サーバーレスのレシート処理 API を構築しましょう。 + +コードを自由に調整したり、画像を追加したり、別の言語パックに切り替えても構いません。OCR の世界は驚きに満ちており、今やそれらを探求するツールが手に入っています。 + +コーディングを楽しんで、レシートが常に読み取れる状態でありますように! + +## 関連チュートリアル + +- [Aspose.OCR を使用した言語選択付き画像テキスト抽出 C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [画像からテキスト抽出 – .NET 用 Aspose.OCR の OCR 最適化](/ocr/english/net/ocr-optimization/) +- [OCR の使い方 - テキスト領域検出なしで画像を認識](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/japanese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..57fd3bef8 --- /dev/null +++ b/ocr/japanese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,201 @@ +--- +category: general +date: 2026-05-25 +description: C#で Aspose.OCR を使用して TIFF をテキストに変換します。バッチ画像からテキストへの変換方法を学び、TIFF ファイルから効率的にテキストを抽出しましょう。 +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: ja +og_description: Aspose.OCRでTIFFをテキストに変換します。このガイドでは、バッチ画像からテキストへの変換方法と、C# の数行で TIFF + ファイルからテキストを抽出する方法を示します。 +og_title: C#でTIFFをテキストに変換 – 完全バッチOCRガイド +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: C#でTIFFをテキストに変換 – 完全バッチOCRガイド +url: /ja/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#でTIFFをテキストに変換 – 完全バッチOCRガイド + +Ever needed to **convert TIFF to text** but weren’t sure where to start? You’re not alone—many developers stumble over batch OCR when dealing with scanned documents. In this tutorial we’ll walk through a hands‑on solution that **extracts text from TIFF** files using Aspose.OCR, and we’ll do it in parallel so large folders finish in seconds. + +You’ll also touch on **batch image to text conversion** best practices, so by the end you’ll have a reusable snippet that turns a whole directory of scanned images into neat *.txt* files—perfect for indexing, searching, or feeding into downstream analytics. + +## 必要なもの + +- **.NET 6.0** 以上 (コードは .NET Framework でもコンパイル可能) +- **Aspose.OCR for .NET** NuGet パッケージ (`Install-Package Aspose.OCR`) +- *.tif* ファイルが1つ以上含まれるフォルダー (従来の TIFF スキャン形式) +- お好みの IDE (Visual Studio、VS Code、Rider など好きなもの) + +以上です。外部サービスや API キーは不要で、純粋な C# と Aspose だけです。 + +![TIFF ファイルが処理され、結果のテキストファイルが生成されるスクリーンショット](/images/ocr-result.png "OCR 結果:変換された TIFF からテキストへの出力") + +*(Alt text: 画面上で変換された TIFF からテキストへの出力を示すスクリーンショット)* + +## ステップ 1: OCR エンジンの設定 – TIFF をテキストに変換 + +まず最初に、英字を読み取ることを認識した `OcrEngine` インスタンスが必要です。エンジンは変換の中心であり、正しく構成することで信頼できる結果が得られます。 + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*この点が重要な理由:* +Aspose.OCR は数十の言語をサポートしています。多言語のスキャンを扱う場合は、`OcrLanguage.English` を適切な enum 値に変更するだけです。言語を未定義のままにすると、エンジンは自動検出モードになり、速度が遅くなり精度も低下する可能性があります。 + +## ステップ 2: すべての TIFF ファイルを取得 – TIFF からテキストを効率的に抽出 + +次に、指定したフォルダーからすべての *.tif* ファイルを取得します。`Directory.GetFiles` を使用すると、バッチプロセッサに渡せるクリーンな配列が得られます。 + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro tip:* スキャンがサブフォルダーに入れ子になっている場合は、`SearchOption.AllDirectories` フラグを使用できます。ただし、再帰が深くなるとバッチ処理中のメモリ使用量が増加する可能性があることを覚えておいてください。 + +## ステップ 3: 並列 OCR の実行 – バッチ画像からテキストへの変換 + +さあ、楽しいパートです。Aspose.OCR には、ファイルパスの配列、エンジン、`parallelism` ヒントを受け取る静的ヘルパー `BatchOcr.RecognizeAll` が用意されています。4つのスレッドを起動しますが、最新のクアッドコアラップトップではほぼ線形の速度向上が得られます。 + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*なぜ並列処理なのか?* +高解像度の TIFF バッチをスキャンすると CPU に負荷がかかります。作業を複数のスレッドに分散させることで、すべてのコアを稼働させ、総実行時間を大幅に短縮できます。コア数が多いサーバーで実行する場合は、`parallelism` の値をそれに応じて増やしてください。 + +## ステップ 4: 出力を書き込む – スキャン画像の TXT ファイルに変換 + +最後に、ディクショナリをループし、各テキストを元のベース名と同じ *.txt* ファイルに書き込みます。これが **convert scanned images txt** が実現する瞬間です。 + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### コードが行うこと(平易な英語で) + +1. **Create** 英語用に設定された OCR エンジンを作成します。 +2. **Collect** 対象フォルダーからすべての TIFF ファイルを収集します。 +3. **Run** `BatchOcr.RecognizeAll` を4スレッドで実行し、各画像を文字列に変換します。 +4. **Loop** 結果をループし、`.tif` 拡張子を `.txt` に置き換えて文字列をディスクに書き込みます。 + +これが 50 行未満のコードで実現する **convert TIFF to text** ワークフロー全体です。 + +## エッジケースの処理 – うまくいかないとき + +- **Missing or corrupted TIFFs** – `BatchOcr` は `OcrException` をスローします。グレースフルにダウングレードする必要がある場合は、呼び出しを `try / catch` でラップしてください。 +- **Non‑English documents** – `OcrLanguage.English` を `OcrLanguage.Spanish`、`OcrLanguage.French` などに変更するか、`OcrLanguage.AutoDetect` を使用してください。 +- **Very large images** – OCR 前に DPI を下げること(`ocrEngine.ImagePreprocessing.Dpi = 200`)を検討してメモリを節約できますが、精度が低下する可能性があります。 +- **Output encoding** – 特定のコードページが必要な場合(例: Windows‑1252)、`File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))` に渡してください。 + +## 安定したバッチ変換のためのプロチップ + +- **Log failures**: `List failedFiles` を作成し、例外が発生したファイルを追加します。ループ後にリストをログに書き出してください。 +- **Reuse the engine**: 同じ `OcrEngine` インスタンスを多数のファイルで再利用できます。ループ内でインスタンス化しないでください。 +- **Validate the result**: 簡単な `if (string.IsNullOrWhiteSpace(extractedText))` で、空白または読めないスキャンをフラグ付けできます。 +- **Combine with PDF**: ソースがマルチページ PDF の場合、まず各ページを TIFF に変換します(Aspose.PDF が対応)。その後、このバッチを実行します。 + +## 次のステップ – シンプルな変換を超えて + +大量に **extract text from TIFF** ファイルを抽出できるようになったので、次のことを検討したくなるかもしれません: + +- *.txt* ファイルを検索インデックス(Elasticsearch、Azure Cognitive Search)に投入する。 +- 各結果に対して言語検出を実行し、文書をロケール固有のパイプラインにルーティングする。 +- OCR テキストを元画像に重ね合わせて検索可能な PDF を生成する(再び Aspose.PDF を使用)。 + +これらすべてのシナリオは同じコアアイデアに基づいています:**batch image to text conversion** は、より大規模な文書処理システムの構成要素です。 + +--- + +### 結論 + +あなたは Aspose.OCR を使用して **convert TIFF to text** を行い、フォルダー全体を並列処理し、各結果をきれいな *.txt* ファイルとして保存する方法を学びました。このソリューションは軽量で、完全に構成可能で、プロダクションにすぐに使用できます—レガシー請求書のデジタル化、スキャンした契約書のアーカイブ、テキスト検索エンジンの構築など、あらゆる用途に適しています。 + +実際に試してみて、parallelism を調整し、作成したテキストファイルを必要なワークフローに流し込みましょう。OCRを楽しんでください! + +--- + +## 関連チュートリアル + +- [フォルダー上で OCR 操作を使用して画像からテキストを抽出](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [画像からテキストを抽出 – 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/japanese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/japanese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..f1e5f647a --- /dev/null +++ b/ocr/japanese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: 最小限の ASP.NET Core API で画像からテキストを抽出する方法を学びましょう。POST で画像をアップロードし、マルチパートフォームデータを読み取って画像に + OCR を実行します。 +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: ja +og_description: 最小限の ASP.NET Core API を使用して画像からテキストを抽出します。このガイドでは、POST で画像をアップロードし、マルチパートフォームデータを読み取り、画像に対して + OCR を実行する方法を示します。 +og_title: ASP.NET Coreで画像からテキストを抽出する – ステップバイステップ +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: ASP.NET Core Minimal APIで画像からテキストを抽出する – 完全ガイド +url: /ja/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ASP.NET Core Minimal APIで画像からテキストを抽出する – 完全ガイド + +重厚なフレームワークと格闘せずに **画像からテキストを抽出** したいと思ったことはありませんか? あなたは一人ではありません。多くの開発者が、ユーザーが画像をドロップして生の文字列を取得できる迅速な方法を必要としています。レシートのスキャン、手書きメモのデジタル化、検索インデックスの構築など、さまざまな用途があります。 + +このチュートリアルでは、**POSTで画像をアップロード**し、*multipart/form‑data* ペイロードを解析し、シングルトンの `OcrEngine` を使って **画像上で OCR を実行** する小さな ASP.NET Core Minimal API を作成します。最後までで、任意の .NET 8 プロジェクトに組み込んですぐに画像からテキストを抽出できる、完全に実行可能なアプリが手に入ります。 + +## 作成するもの + +- `/ocr` をリッスンするミニマルな Web アプリ。 +- `multipart/form-data` の POST リクエストで送信された画像ファイルを受け取るエンドポイント。 +- アップロードされたファイルを読み取り、OCR エンジンに渡してプレーンテキストの結果を返すロジック。 +- 対応カードを持つ方向けの、GPU 加速スニペット(コメントアウト済み)オプション。 + +**前提条件** +- .NET 8 SDK(またはそれ以降)。 +- C# とコマンドラインの基本的な知識。 +- `OcrEngine` クラスを提供する OCR ライブラリ(サンプルでは仮想の NuGet パッケージを想定)。 + +これらが揃っているなら、さっそく始めましょう。 + +## ステップ 1: プロジェクトのセットアップと OCR パッケージの追加 + +First, create a new web project and pull in the OCR library. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **プロのコツ:** 依存関係は常に最新に保ちましょう。新しいバージョンは、特に GPU 加速推論においてパフォーマンス向上をもたらすことが多いです。 + +## ステップ 2: シングルトン OCR エンジンの登録(主要サービス) + +We want a single `OcrEngine` instance for the whole app—no need to spin up a new engine per request. Register it in the builder’s service container. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**なぜシングルトンか?** +OCR エンジンの作成はコストがかかります—例えばニューラルネットワークの重みをメモリにロードすることを考えてください。同じインスタンスを再利用することで CPU サイクルと RAM の両方を節約でき、すべての `/ocr` 呼び出しの応答時間が速くなります。 + +## ステップ 3: アプリケーションの構築 + +Now we materialize the `WebApplication` object. + +```csharp +var app = builder.Build(); +``` + +この行はほぼ魔法のように見えますが、内部ではルーティング、ミドルウェア、そして先ほど設定した DI コンテナを接続しています。 + +## ステップ 4: POST エンドポイントの定義 – “POST で画像をアップロード” + +Here’s the heart of the tutorial: an endpoint that **upload image via POST**, reads the multipart payload, and hands the data to the OCR engine. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### ロジックの分解 + +| ステップ | 何が起こるか | 重要な理由 | +|------|--------------|----------------| +| **ReadFormAsync** | 受信した *multipart/form-data* リクエストを解析します。 | これがなければ、アップロードされたファイルにアクセスできません。 | +| **form.Files["image"]** | フィールド名が `image` のファイルを取得します。 | 呼び出し側に予測可能な契約を保証します。 | +| **Content‑type check** | ファイルが画像かどうか(例: `image/png`)を確認します。 | 画像でないデータで OCR エンジンがエラーになるのを防ぎます。 | +| **Image.FromStream** | 生のストリームを `System.Drawing.Image` に変換します。 | OCR ライブラリはバイト配列ではなく `Image` オブジェクトを期待します。 | +| **ocr.Recognize(img)** | OCR エンジンを呼び出して **画像からテキストを認識** します。 | これが **画像上で OCR を実行** する核心のステップです。 | +| **Results.Text** | プレーンテキストのレスポンスを返します。 | 下流サービスが扱いやすいシンプルな形式です。 | + +## ステップ 5: API の実行 + +Finally, start the web server. + +```csharp +app.Run(); +``` + +When you execute `dotnet run`, the API will listen on `http://localhost:5000` (or a port of your choosing). You can test it with `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Expected output:** The console will print the recognized characters, e.g.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +If the image is blurry or the language isn’t supported, the OCR engine will return an empty string or an error message—handle those cases in production code. + +## エッジケースとベストプラクティス + +### 1. 大きなファイル + +The default request body limit is 30 MB. For larger scans you might need to adjust: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. 非同期 OCR + +Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the lambda as `async`. + +### 3. セキュリティ上の考慮点 + +- メモリにロードする前に **ファイルサイズを検証** する。 +- ディスクに書き込む場合は **ファイル名をサニタイズ** する。 +- **レートリミット** を設定し、DoS 攻撃を防止する。 + +### 4. GPU 加速 + +If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially on high‑resolution images. + +## 完全動作例 + +Below is the complete `Program.cs` you can copy‑paste into a fresh Minimal API project. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Save, run `dotnet run`, and you’re ready to **extract text from image** on demand. + +## 結論 + +We’ve walked through a **complete, end‑to‑end solution** for extracting text from image using ASP.NET Core Minimal API. Starting from project scaffolding, we **registered a singleton OCR engine**, built an endpoint that **uploads image via POST**, **read multipart form data**, and finally **perform OCR on image** to return clean plain‑text. + +From here you can: + +- よりリッチなレスポンスのために JSON ラッパーを追加。 +- 抽出したテキストを保存するデータベースを組み込む。 +- 複数言語(`OcrLanguage.Spanish` など)への対応を拡張。 + +The pattern scales nicely—just drop the same endpoint into a larger microservice or expose it behind an API gateway. + +Got questions about handling PDFs, batch processing, or GPU tuning? Drop a comment, and happy coding! + +## 関連チュートリアル + +- [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/japanese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/japanese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..c7859766f --- /dev/null +++ b/ocr/japanese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,310 @@ +--- +category: general +date: 2026-05-25 +description: C# と Aspose OCR を使用して画像からテキストを抽出します。JPG をテキストに変換する方法、OCR 用に画像を読み込む方法、そして高速で信頼性の高い結果を得る方法を学びましょう。 +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: ja +og_description: C#で画像からテキストを抽出する。このガイドでは、jpgをテキストに変換する方法、OCR用に画像を読み込む方法、そして多言語コンテンツを扱う方法を示します。 +og_title: C#で画像からテキストを抽出 – Aspose OCRチュートリアル +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: C#で画像からテキストを抽出する – 完全なAspose OCRガイド +url: /ja/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で画像からテキストを抽出 – 完全 Aspose OCR ガイド + +プレーンな C# コードで **画像からテキストを抽出** する方法を考えたことはありませんか? あなただけではありません。領収書をデジタル化したり、看板をスキャンしたり、単に OCR に興味があるだけでも、画像から文字を取り出す能力は便利なスキルです。このチュートリアルでは、Aspose.OCR を使って **画像からテキストを抽出** する方法を示す、完全に実行可能なサンプルを順を追って解説し、さらに **jpg をテキストに変換**、**OCR 用に画像をロード**、そして古典的な “**画像を OCR する方法**” の質問に一挙に答えます。 + +このガイドの最後まで読むと、JPEG ファイルを読み込み、ウクライナ語(または他のサポートされている言語)を認識し、結果をコンソールに出力する自己完結型のコンソール アプリが手に入ります。曖昧な参照や不足している部分は一切なく、コピー&ペーストしてすぐに実行できる完全なソリューションが提供されます。 + +--- + +## 学べること + +* Aspose.OCR NuGet パッケージのインストール方法。 +* C# で **OCR 用に画像をロード** するために必要な正確なコード。 +* 言語を設定して実際に **画像からテキストを抽出** する方法。 +* **jpg をテキストに変換** を効率的に行うコツ。 +* よくある落とし穴とその回避策。 + +すでに .NET 開発環境が整っているなら、すぐに取り掛かれます。まだの場合は、以下の前提条件セクションで環境を整えてください。 + +--- + +## 前提条件 + +| 要件 | 重要な理由 | +|------|------------| +| .NET 6.0 SDK(またはそれ以降) | コンソール アプリのランタイムを提供します。 | +| Visual Studio 2022 または VS Code | 編集とデバッグが容易になります。 | +| インターネット接続(初回実行時) | NuGet が Aspose.OCR をダウンロードする必要があります。 | +| 処理したい JPEG 画像(例:`ukrainian_sign.jpg`) | OCR エンジンのソースファイルです。 | + +> **Pro tip:** Linux や macOS を使用している場合でも、同じコードは .NET CLI(`dotnet new console`)で動作するので、重い IDE をスキップしても問題ありません。 + +--- + +## ステップ 1 – NuGet で Aspose.OCR をインストール + +ターミナル(またはパッケージ マネージャ コンソール)を開き、次のコマンドを実行します: + +```bash +dotnet add package Aspose.OCR +``` + +この一行で最新の Aspose.OCR バイナリとすべてのトランジティブ依存関係が取得されます。手動で DLL を操作する必要はありません。 + +--- + +## ステップ 2 – OCR エンジンの作成(抽出の中心) + +ライブラリが用意できたので、`OcrEngine` のインスタンスを作成します。このオブジェクトが **画像からテキストを抽出** する役割を担います。 + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Why this matters:** エンジンは OCR アルゴリズム、言語モデル、設定オプションをカプセル化しています。インスタンスを一度作成して複数の画像で再利用すれば、メモリ効率と速度の両方が向上します。 + +--- + +## ステップ 3 – OCR 用に画像をロード(言語設定) + +次にエンジンに読み込む画像を指示します。ここで **OCR 用に画像をロード** というフレーズが登場します。 + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Edge case:** ファイルが存在しない場合、`Image.FromFile` は `FileNotFoundException` をスローします。実運用コードでは try‑catch でラップしてください。 + +--- + +## ステップ 4 – OCR を実行してテキストを抽出 + +画像がロードされたら、エンジンは **画像からテキストを抽出** できます。`Recognize` メソッドが本格的な処理を行います。 + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +すべてが正常に進めば、`recognizedText` に OCR エンジンが読み取れたテキストのプレーンテキスト表現が格納されます。 + +--- + +## ステップ 5 – JPG をテキストに変換(全体をまとめる) + +これまでに作成したコードはすでに **JPG をテキストに変換** していますが、繰り返し呼び出せるように整ったメソッドにまとめましょう。 + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +これでシンプルに次のように呼び出せます: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**期待される出力**(簡略化): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +画像が英語テキストを含む場合は `OcrLanguage.English` に変更すれば、対応する出力が得られます。 + +--- + +## ステップ 6 – 一般的な “画像を OCR する方法” の質問への対処 + +### 6.1 PNG や BMP でも OCR できる? + +もちろんです。`Image.FromFile` は System.Drawing が認識できるすべてのフォーマットをサポートしているので、パスを `.png` や `.bmp` に変えるだけでコードはそのまま動作します。 + +### 6.2 画像が低解像度だったら? + +300 dpi 未満になると OCR 精度が大幅に低下します。簡単な対策として、エンジンに渡す前に `Graphics` で画像を拡大すると効果的です。 + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Aspose.OCR のライセンスは必要? + +Aspose は透かし付きの無料トライアルを提供しています。商用利用の場合はライセンスを購入し、次のコードを追加してください。 + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## 完全動作サンプル + +以下は **画像を OCR する方法**、**OCR 用に画像をロード**、**JPG をテキストに変換** をすべてひとつにまとめた、実行可能なコンソール アプリの全コードです。 + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**実行方法** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +コンソールに抽出されたテキストが表示されれば、C# で **画像からテキストを抽出** できたことが確認できます。 + +--- + +## よくある問題点とプロのコツ + +| 問題点 | 発生理由 | 対策 | +|--------|----------|------| +| 空白の出力 | 画像が暗すぎる、またはコントラストが低い。 | `Bitmap` で明るさを上げる前処理を行う。 | +| 言語が間違っている | `Language` プロパティがデフォルトの英語のまま。 | `ocrEngine.Language = OcrLanguage.Ukrainian;`(または目的の言語)を明示的に設定。 | +| メモリ不足エラー | 非破棄のまま非常に大きな画像をロードしている。 | `Image.FromFile` を `using` ブロックで囲む(例参照)。 | +| ライセンス透かし | ライセンス未取得のトライアルで実行している。 | `Main` の冒頭で購入したライセンスを適用。 | + +--- + +## 結論 + +C# で **画像からテキストを抽出** するために必要なすべてを網羅しました—Aspose.OCR のインストール、**OCR 用に画像をロード**、**JPG をテキストに変換**、多言語対応まで。完全なサンプル プログラムがすべての要素を結びつけ、OCR 関連プロジェクトの信頼できる基盤を提供します。 + +次に試すべきこと: + +* ファイルではなく **画像を OCR する方法** としてストリーム(`MemoryStream`)を使用する。 +* **c# image to text** の後処理としてスペルチェックを組み込む。 +* OCR ステップをパイプライン全体に統合し、結果をデータベースに保存する。 + +さまざまな言語、画像形式、前処理テクニックを試してみてください。OCR は科学であると同時に芸術でもあり、試行錯誤すればするほど結果は向上します。 + +Happy coding, and may your images always be readable! + +## 関連チュートリアル + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/japanese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..cd54dca14 --- /dev/null +++ b/ocr/japanese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-05-25 +description: C#でOCRを使用して画像ファイルからテキストを抽出する方法。Aspose.OCRを使ってJPGから中国語文字を認識する簡単な手順をご紹介します。 +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: ja +og_description: C#でOCRを使用して画像ファイルからテキストを抽出する方法。このガイドでは、Aspose.OCRを使ってJPGから中国語文字を認識する手順を示します。 +og_title: C#でOCRを使用する方法 – JPGから中国語テキストを認識する +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: C#でOCRを使用する方法 – JPGから中国語テキストを認識する +url: /ja/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# で OCR を使用する方法 – JPG から中国語テキストを認識する + +スマートフォンで撮影した画像から文字を取り出す **how to use OCR** について考えたことはありませんか? あなたは一人ではありません。レシートスキャナー、翻訳アプリ、または自動データ入力など、実際のプロジェクトでは **extract text from image** ファイルを迅速かつ確実に取得する必要があります。 + +このチュートリアルでは、**recognizes text from JPG** ファイルを認識し、さらに **recognize Chinese characters** の難しいケースを **OCR Chinese Simplified** 言語パックを使用して処理する、完全で実行可能な例を順に解説します。最後まで実行すれば、検出された文字列をコンソールに出力する自己完結型のコンソールアプリが手に入り、追加の手動ダウンロードは不要です。 + +> **Quick note:** このコードは Aspose.OCR ≥ 23.7 で動作し、初回使用時に言語リソースを自動的に取得します。古いバージョンを使用している場合は、言語を手動で追加する必要があります。 + +## 前提条件 + +始める前に、以下が揃っていることを確認してください: + +- .NET 6.0 SDK 以降(この例は .NET 6 を対象としていますが、.NET 5 でも動作します) +- Visual Studio 2022 または C# 拡張機能がインストールされた VS Code の最新バージョン +- 最初の言語ダウンロードのためのインターネット接続 +- 簡体字中国語テキストを含む JPG 画像(ここでは `chinese_sign.jpg` と呼びます) + +以上です—重厚な OCR エンジンやネイティブ DLL の操作は不要です。NuGet コマンドを数回実行し、数行のコードを書くだけです。 + +## 手順 1: NuGet で Aspose.OCR をインストールする + +まず最初に、OCR ライブラリが必要です。プロジェクトフォルダーでターミナルを開き、次のコマンドを実行します: + +```bash +dotnet add package Aspose.OCR +``` + +あるいは Visual Studio の UI が好きな場合は、**Dependencies → Manage NuGet Packages** を右クリックし、“Aspose.OCR” を検索して **Install** をクリックします。 + +> **Pro tip:** パッケージは常に最新の状態に保ちましょう。新しい言語パックやパフォーマンス向上がマイナーバージョンごとに追加されます。 + +## 手順 2: 新しいコンソールプロジェクトを作成する(まだ作成していない場合) + +ゼロから始める場合は、新しいコンソールアプリを作成します: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +これで OCR コードを記述できる `Program.cs` ファイルが用意できました。 + +## 手順 3: OCR コードを書く – JPG から簡体字中国語を認識する + +`Program.cs` を開き、内容を以下に置き換えます。各行に注釈が付いているので、*何を* しているかだけでなく、*なぜ* それを行うのかが分かります。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 背後で何が起きているか? + +- **`OcrEngine.Language`** は Aspose にどの辞書を使用するかを指示します。`ChineseSimplified` を選択することで、エンジンは簡体字中国語の言語パックを使用するよう指示します。 +- **First‑time download**: `Recognize` が実行されると、SDK は Aspose の CDN にアクセスし、約 6 MB の言語ファイルを取得してローカルにキャッシュし、その後 OCR を実行します。以降の呼び出しは瞬時に完了します。 +- **`Image.FromFile`** は .NET がデコードできる任意のラスタ形式(JPG、PNG、BMP など)で動作するため、**extract text from image** ファイルを多数のタイプから取得できます。JPG に限りません。 + +## 手順 4: アプリケーションを実行し、出力を確認する + +ビルドして実行します: + +```bash +dotnet run +``` + +以下のような出力が表示されるはずです: + +``` +=== Recognized Text === +欢迎光临 +``` + +コンソールに文字化けや空文字列が表示された場合は、次の点を再確認してください: + +1. 画像に実際に鮮明で高コントラストな中国語文字が含まれていること。 +2. ファイルパスが正しいこと(余分なスペースや拡張子の欠落がないか)。 +3. マシンが言語パック取得のために `https://download.aspose.com` にアクセスできること。 + +## 手順 5: エッジケースと一般的な落とし穴の対処 + +### 5.1 低品質画像への対処 + +ソース画像がぼやけていたり、ノイズが多かったり、照明が悪いと OCR の精度は低下します。簡単な対策として画像を前処理します: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 ヘッドレス環境での実行 + +GUI のない Linux コンテナにデプロイする場合は、`System.Drawing` に必要な `libgdiplus` ライブラリがインストールされていることを確認してください: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 言語パックを手動でキャッシュする + +言語ファイルを一度ダウンロードし、`License` API を介して Aspose に指定すれば、1 回限りのネットワーク呼び出しを省くことができます。オフライン環境で便利です。 + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## 完全動作例(オールインワン) + +以下は `Program.cs` にコピー&ペーストできる *完全* なプログラムです。隠し要素や外部スクリプトはありません。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 期待される出力 + +JPG にフレーズ “欢迎光临” が含まれている場合、コンソールは次のように出力します: + +``` +=== Recognized Text === +欢迎光临 +``` + +画像は他の簡体字中国語の看板、道路名、商品ラベルなどに自由に置き換えて構いません—エンジンは最善を尽くします。 + +## 結論 + +本稿では C# で **how to use OCR** を用いて **extract text from image** ファイルを処理し、特に **recognize Chinese characters** を **JPG** で実現する方法を取り上げました。Aspose.OCR のオンザフライ言語ダウンロードを活用すれば、軽量なデプロイを保ちつつ、**OCR Chinese Simplified** をすぐに利用できます。 + +次は何をすべきか?以下のアイデアを試してみてください: + +- **Batch processing**: 画像フォルダーをループし、各結果を CSV に書き出す。 +- **Combine with translation APIs**: 認識した文字列を Azure Translator に渡してリアルタイム多言語アプリを実現する。 +- **Explore other languages**: `OcrLanguage.ChineseSimplified` を `Japanese` や `Arabic` に置き換えて、同じコードがどのように動作するか確認する。 + +パフォーマンスチューニング、ライセンス、または OCR を Web サービスに統合することについて質問がありますか?以下にコメントを残してください—楽しいコーディングを! + +--- + +![C# で OCR を使用して JPG 画像から中国語テキストを認識する方法を示すコンソール出力のスクリーンショット](ocr-chinese-demo.png "OCR コンソール出力の使用方法") + +## 関連チュートリアル + +- [Aspose.OCR を使用した言語選択による画像テキスト抽出(C#)](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [複数言語対応の Aspose OCR で画像テキストを認識する](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [OCR で矩形を準備して画像からテキストを抽出する方法](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/japanese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/japanese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..3fcb3fc96 --- /dev/null +++ b/ocr/japanese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-05-25 +description: C#でロシア語テキストをOCRし、Aspose OCRを使用して画像からテキストを抽出する方法を学びましょう。画像をテキストに変換するC#のステップバイステップコードをすぐに実装できます。 +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: ja +og_description: C#でロシア語テキストのOCRを簡単に。画像からテキストを抽出し、画像をテキストに変換し、Aspose OCRで画像をOCRに読み込む方法を学びましょう。 +og_title: C#でロシア語テキストをOCR – 完全なAspose OCRガイド +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: C#でロシア語テキストをOCRする – Aspose OCRを使用した完全ガイド +url: /ja/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C# でロシア語テキストを OCR – Aspose OCR を使った完全ガイド + +C# でロシア語テキストを OCR したいけど、どのライブラリを信頼すべきか迷っていませんか? あなたは一人ではありません。キリル文字の画像からきれいで読みやすい文字を取得するのは、まるで暗号を解読するような感覚です—特に正しい言語モデルを設定していないと。 + +このチュートリアルでは、**画像からテキストを抽出**し、*image to text C#* スタイルで変換し、Aspose OCR を使ったロシア語認識の微妙なポイントを扱うハンズオン例を順を追って解説します。最後まで読めば、画像を OCR に読み込み、認識された文字列をコンソールに出力する実行可能なコンソールアプリが完成し、より高度なシナリオに取り組むための確固たる基盤が手に入ります。 + +## 学べること + +- **Aspose OCR C#** をロシア語サポート用にインストール・設定する方法。 +- **画像を OCR にロード**しエンジンを呼び出す正確な手順。 +- 言語リソースが見つからない、画像がぼやけているといった一般的な落とし穴への対処法。 +- 複数ファイルのバッチ処理や信頼度閾値の調整など、ソリューションを拡張する方法。 + +Aspose の事前知識は不要です。C# と .NET の基本的な知識があればすぐに始められます。 + +## 前提条件 + +作業を始める前に、以下を用意してください。 + +1. **.NET 6.0**(またはそれ以降)SDK がインストール済み – コードは .NET Core と .NET Framework のどちらでも動作します。 +2. **Visual Studio 2022**(またはお好みの IDE)。 +3. **Aspose.OCR for .NET** NuGet パッケージ – Aspose のウェブサイトから無料トライアルキーを取得できます。 +4. **ロシア語言語モデル** ファイル(`rus.traineddata`) – Aspose のリソースページからダウンロードし、後で参照するフォルダーに配置してください。 +5. 明瞭なキリル文字が含まれるサンプル画像(`russian_doc.png`)。 + +すべて揃いましたか? では、始めましょう。 + +## 手順 1: プロジェクトの作成と Aspose OCR のインストール + +まず、コンソールプロジェクトを新規作成します。 + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +次に Aspose OCR パッケージを追加します。 + +```bash +dotnet add package Aspose.OCR +``` + +> **プロのコツ:** トライアルライセンスを使用する場合は、`Aspose.Total.lic` ファイルを手元に置いておき、コード内でロードしてウォーターマークを回避してください。 + +パッケージがインストールされたら `Program.cs` を開きます。デフォルトの `Main` メソッドが表示されるので、内容を以下の骨格に置き換えます。 + +## 手順 2: ロシア語用に OCR エンジンを構成 + +操作の中心となるのは `OcrEngine` オブジェクトです。ここで設定すべきことは 2 つあります: 認識させる言語と、言語モデルファイルの所在場所です。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **なぜ重要か:** `Language = OcrLanguage.Russian` を設定しないと、エンジンはデフォルトで英語になり、キリル文字は文字化けしてしまいます。`ResourceFolder` は `rus.traineddata` が格納されたディレクトリを指す必要があり、これが無いと Aspose は *resource not found* 例外を投げます。 + +## 手順 3: OCR 用に画像をロード + +次に **画像を OCR にロード** します。Aspose OCR は `System.Drawing.Image` と連携するため、PNG、JPEG、BMP などのサポート形式であれば何でも渡せます。ファイルパスが正しいことを確認してください。相対パスでも、画像を実行ファイルと同じフォルダーに置いていれば問題ありません。 + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **エッジケース:** 画像が大きすぎる(5 MB 超)場合は、先に縮小した方が良いでしょう。DPI が低すぎると OCR 精度が落ちますが、巨大ファイルはメモリ圧迫の原因になります。必要に応じて `Graphics` を使ってリサイズしてください。 + +## 手順 4: テキストを認識 – Image to Text C# スタイル + +エンジンの構成と画像のロードが完了したら、実際の認識は以下の 1 行で完了します。 + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +プログラムを実行(`dotnet run`)すると、次のような出力が得られるはずです。 + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +出力が意味不明な文字列になった場合は、以下を再確認してください。 + +- `ResourceFolder` に `rus.traineddata` が存在するか。 +- 画像がぼやけていないか;必要なら OCR 前に単純な二値化フィルタを適用。 +- 言語設定が本当に `OcrLanguage.Russian` になっているか。 + +## 手順 5: 微調整と一般的な落とし穴 + +### 信頼度閾値の調整 + +Aspose OCR は内部で文字ごとに信頼度を返しますが、API では直接取得できません。**詳細出力** を有効にすれば、低信頼度の単語を確認できます。 + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +誤認識が頻発する場合は、次の対策を試してください。 + +- **前処理**: 画像をグレースケール化、コントラスト増加、またはメディアンフィルタ適用。 +- **DPI 設定**: キリル文字の場合、最低でも 300 DPI を確保してください。 + +### 複数画像のバッチ処理 + +大量の **画像からテキストを抽出** したい場合は、認識ロジックをループで回します。 + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +これで各 PNG に対して `.txt` が生成され、文書アーカイブに便利です。 + +### Unicode 出力の取り扱い + +キリル文字は Unicode です。コンソールのエンコーディングがそれを表示できるように設定してください。 + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +`Main` メソッドの開始直後にこの行を追加します。設定しないと、ロシア文字が `?` に置き換わってしまいます。 + +## 完全動作サンプル + +以下が完成形のコードです。`Program.cs` にコピペし、パスを調整すればすぐに実行できます。 + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**期待される出力**(サンプル画像に「Пример текста на русском языке.」と書かれている場合): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +別の結果が出た場合は、手順 5 のトラブルシューティングを再度確認してください。 + +## まとめ + +これで **C# でロシア語テキストを OCR** するための、Aspose OCR を用いたエンドツーエンドの例が完成しました。ライブラリのインストール、ロシア語モデルの設定、画像のロード、クリーンな Unicode テキストへの変換まで、すべて網羅しています。 + +信頼できる OCR の鍵は、良質な元画像です:はっきりしたフォント、十分な DPI、正しい言語リソース。基本をマスターしたら、バッチ処理やクラウドストレージとの統合、さらには AI を使ったスペルチェックなど、応用範囲は無限に広がります。 + +### 次のステップは? + +- **aspose ocr c#** のレイアウト解析や PDF 出力といった高度オプションを探求。 +- Azure Functions で **画像からテキストを抽出** ワークフローと組み合わせ、サーバーレス処理を実現。 +- 言語を変えてみる – `OcrLanguage.Russian` を `OcrLanguage.English` や他のサポート言語に切り替えるだけです。 + +質問や「この画像が認識できない」などのケースがあれば、下のコメント欄で教えてください。ハッピーコーディング! + +![ocr russian text example](ocr-russian-example.png){alt="OCRロシア語テキスト例"} + +## 関連チュートリアル + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/japanese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..e462c0f81 --- /dev/null +++ b/ocr/japanese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-25 +description: C#でAspose OCRを使用して画像からテキストを認識します。OCR用に画像を読み込む方法、OCR言語を設定する方法、OCRエンジンを作成する方法、そしてTIFFからテキストを抽出する方法を学びましょう。 +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: ja +og_description: C#でAspose OCRを使用して画像からテキストを認識します。このチュートリアルでは、OCRエンジンの作成、OCR用画像の読み込み、OCR言語の設定、そしてTIFFからテキストを抽出する方法を示します。 +og_title: Aspose OCRで画像からテキストを認識する – 完全C#ガイド +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Aspose OCRで画像からテキストを認識する – 完全なC#ガイド +url: /ja/net/text-recognition/recognize-text-from-image-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で画像からテキストを認識する – 完全なC#ガイド + +画像からテキストを**認識**したいけれど、速度と精度の両方を満たすライブラリがどれか分からないことはありませんか?請求書処理やアーカイブプロジェクトでは、TIFF ファイルからクリーンで検索可能なテキストを取得することが最大の課題です。 + +実は、Aspose OCR for .NET を使えば、その一連のパイプラインがとても簡単になります。このガイドでは、パッケージのインストール、**OCR エンジンの作成**、TIFF の読み込み、OCR 言語の設定、そして最終的に**TIFF からテキストを抽出**するまでの手順をすべて解説します。最後まで読めば、画像ファイルからテキストを瞬時に**認識**できるコンソールアプリが完成します。 + +## 前提条件 + +- .NET 6.0 以降(コードは .NET Core と .NET Framework でも動作します) +- Visual Studio 2022(またはお好みの IDE) +- Aspose.OCR NuGet パッケージ(GPU サポートには `Aspose.OCR.Gpu` アドオンが必要) +- 追加速度が欲しい場合は CUDA 対応 GPU(任意ですが推奨) + +> **プロのコツ:** GPU が無い場合は `GpuDevice` 行を省略すれば、エンジンは自動的に CPU にフォールバックします。 + +## 手順 1: Aspose OCR のインストールと OCR エンジンの作成 + +まず、NuGet で必要なパッケージを追加します。 + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +これで**OCR エンジンを作成**できます。このオブジェクトがプロセスの中心で、実行デバイスやメモリ制限などの設定を保持します。 + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**重要ポイント:** エンジンを GPU にバインドすると、特に高解像度の TIFF を大量に処理する場合、**画像からテキストを認識**する時間が大幅に短縮されます。 + +## 手順 2: OCR 用に画像を読み込む + +次に**OCR 用に画像を読み込む**必要があります。Aspose.OCR は `System.Drawing.Image` を使用するため、GDI+ がサポートする形式(マルチページ TIFF を含む)であれば問題ありません。 + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +マルチページ TIFF を扱う場合は `image.SelectActiveFrame` でページをループできますが、ほとんどのシナリオでは単一呼び出しで十分です。 + +## 手順 3: OCR 言語を設定する + +エンジンは自動で言語を判別しません。**OCR 言語を設定**してから認識を実行しないと、文字化けした出力が得られます。 + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **豆知識:** 実行時に言語を切り替えるコストは低く、ページごとにこのプロパティを変更すれば混在言語の文書も処理できます。 + +## 手順 4: 認識を実行 – 画像からテキストを認識する + +さあ、本番です。実際に**画像からテキストを認識**します。`Recognize` メソッドは検出された文字列をプレーンテキストで返します。 + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +信頼度スコアやバウンディングボックスが必要な場合は、`OcrResult` オブジェクトを返すオーバーロードを使用できますが、ほとんどの抽出タスクではプレーン文字列で十分です。 + +## 手順 5: TIFF からテキストを抽出(マルチページファイルの処理) + +ソースが複数ページの TIFF の場合、ステップ 2‑4 を各フレームで繰り返す必要があります。以下はページごとに**TIFF からテキストを抽出**する簡易ループです。 + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +上記コードは各ページの抽出テキストを出力するので、結果をデータベースや検索インデックスにパイプするのがとても簡単です。 + +## 手順 6: 抽出テキストを表示または永続化する + +最後に**抽出テキストを表示**し、必要に応じてファイルに書き出して後で処理できるようにします。 + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +プログラムを実行すると、認識された文字がコンソールに表示され、ソース TIFF と同じディレクトリに `extracted_text.txt` が作成されます。 + +--- + +## よくある質問とエッジケース + +- **GPU が検出されない場合は?** + `GpuDevice` 行を削除すれば、エンジンは自動的に CPU モードに切り替わります。速度は遅くなりますが、結果の精度は変わりません。 + +- **PNG や JPEG も処理できますか?** + もちろんです。`Image.FromFile` は System.Drawing がサポートするすべての形式に対応しているので、拡張子に関係なく**OCR 用に画像を読み込む**ことができます。 + +- **低解像度のスキャンはどう扱うべき?** + `ocrEngine.PreprocessOptions.Dpi` を `Recognize` 呼び出し前に上げてください。DPI を高くするとエンジンが利用できるピクセル数が増え、精度が向上します。 + +- **TIFF のサイズに上限はありますか?** + `GpuMemoryLimit` プロパティで GPU 使用量を制限できます。上限に達した場合、エンジンは残りのページを CPU にフォールバックします。 + +--- + +## 結論 + +これで、Aspose OCR を使って C# で**画像からテキストを認識**するための、実運用可能な完全コードが手に入りました。チュートリアルでは**OCR エンジンの作成**、**OCR 用に画像を読み込む**、**OCR 言語の設定**、そして**TIFF からテキストを抽出**する方法を解説し、GPU 加速による高速化も実現しました。 + +ここからは次のようなことに挑戦できます: + +- 異なる言語 (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` など) を試す +- 出力を検索可能な ElasticSearch インデックスに統合する +- 後処理(スペルチェック、正規表現によるクリーンアップ)を追加してデータ品質を向上させる + +自分の請求書バッチで試してみて、メモリ制限を調整しながら OCR パフォーマンスの向上を体感してください。Happy coding! + +## 関連チュートリアル + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..a879c5f9b 100644 --- a/ocr/korean/net/ocr-configuration/_index.md +++ b/ocr/korean/net/ocr-configuration/_index.md @@ -60,7 +60,8 @@ 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#에서 OCR 엔진 만들기 – 완전 가이드](./create-ocr-engine-in-c-complete-guide/) ### 일반적인 사용 사례 - **스캔된 청구서 이미지**에서 텍스트를 추출해 자동 회계 처리. @@ -101,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/korean/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/korean/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..96b744041 --- /dev/null +++ b/ocr/korean/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-25 +description: C#로 OCR 엔진을 만들고 몇 줄의 코드로 평가 모드와 라이선스 상태를 확인하는 방법을 배워보세요. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: ko +og_description: C#로 OCR 엔진을 만들고 즉시 평가 모드를 감지하는 방법과 라이선스 상태를 표시하는 방법을 확인하세요. +og_title: C#로 OCR 엔진 만들기 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: C#로 OCR 엔진 만들기 – 완전 가이드 +url: /ko/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 OCR 엔진 만들기 – 완전 가이드 + +끝없는 문서를 뒤져보지 않고 C#에서 **create OCR engine** 객체를 만드는 방법이 궁금했나요? 당신만 그런 것이 아닙니다. 많은 개발자들이 OCR 엔진을 시작하고, 트라이얼 모드인지 확인하며, 사용자에게 라이선스 상태를 표시해야 할 때 벽에 부딪히곤 합니다. + +이 튜토리얼에서는 **creates an OCR engine**, **OCR engine evaluation mode**를 확인하고 라이선스 상태에 대한 친절한 메시지를 출력하는 간결하고 엔드‑투‑엔드 예제를 단계별로 살펴봅니다. 끝까지 진행하면 바로 실행 가능한 콘솔 앱과 자체 프로젝트에서 OCR 라이선스를 처리하는 명확한 개념 모델을 얻게 됩니다. + +## 배울 내용 + +- `OcrEngine`을 인스턴스화하는 방법 (모든 OCR 워크플로의 핵심). +- **evaluation mode** 감지가 규정 준수와 사용자 경험에 왜 중요한지. +- **check OCR license** 상태를 확인하고 예상치 못한 상황에 대응하는 최선의 방법. +- 일반적인 함정—null 참조, 예외 처리, 버전 불일치. + +이미 설치한 OCR SDK 외에 별도의 도구가 필요하지 않습니다. 기본 C# 문법에 익숙하다면 바로 시작할 수 있습니다. + +## 사전 요구 사항 + +- .NET 6.0 이상 (코드는 .NET Core와 .NET Framework에서 모두 컴파일됩니다). +- `IsEvaluation` 속성을 가진 `OcrEngine` 클래스를 제공하는 OCR SDK (예: 가상의 `MyOcrSdk`). +- 텍스트 편집기 또는 IDE (Visual Studio, VS Code, Rider—선호하는 것을 선택하세요). + +이것으로 충분합니다. 시작해 봅시다. + +## 단계 1: 새 콘솔 프로젝트 설정 + +먼저, 코드를 격리된 환경에서 실행할 수 있도록 새 콘솔 앱을 생성합니다. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +생성된 `Program.cs`를 엽니다. 여기의 내용을 **creates OCR engine** 인스턴스를 만들고 라이선스를 처리하는 완전한 예제로 교체합니다. + +## 단계 2: OCR SDK 네임스페이스 가져오기 + +SDK가 NuGet(`MyOcrSdk`는 자리표시자)으로 참조된 것으로 가정하고, 파일 상단에 using 지시문을 추가합니다. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +아직 패키지를 추가하지 않았다면, 다음을 실행하세요: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** SDK 버전을 최신 상태로 유지하세요; 최신 릴리스는 평가 모드 감지를 개선하는 경우가 많습니다. + +## 단계 3: OCR 엔진 인스턴스 생성 + +이제 드디어 **create OCR engine** 객체를 생성합니다. 이는 모든 OCR 워크플로의 핵심이며, 나중에 이미지를 읽게 될 두뇌와 같습니다. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +왜 이 단계가 중요한가요? `OcrEngine`은 모든 설정, 언어 팩 및 라이선스 데이터를 캡슐화합니다. 이것이 없으면 이미지를 처리하거나 평가 플래그를 조회할 수 없습니다. + +> **Side note:** 일부 SDK는 생성자에 구성 객체(예: 언어, DPI)를 전달하도록 허용합니다. 사용자 지정 설정이 필요하면 해당 줄을 수정하세요. + +## 단계 4: OCR 엔진 평가 모드 결정 + +대부분의 OCR 공급업체는 유효한 라이선스 키가 제공될 때까지 **evaluation mode**로 실행되는 체험 버전을 제공합니다. 트라이얼 모드인지 여부를 알면 적절한 UI 표시를 하거나 특정 기능을 제한할 수 있습니다. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation` 속성은 엔진이 라이선스가 없거나 제한된 기간의 체험판을 사용할 때 `true`를 반환합니다. 프리미엄 기능을 보호하는 빠르고 신뢰할 수 있는 방법입니다. + +### 속성이 없을 경우는? + +구버전 SDK는 대신 `GetLicenseInfo()`와 같은 메서드를 제공할 수 있습니다. 이 경우 반환된 객체에서 `IsTrial` 플래그를 확인하면 됩니다. 업그레이드 시에는 항상 SDK 변경 로그를 참고하세요. + +## 단계 5: 현재 라이선스 상태 표시 + +마지막으로, 엔진이 라이선스가 있거나 아직 트라이얼인지 사용자에게 보여줍니다. 간단한 콘솔 write‑line으로 충분하지만, GUI 앱에 맞게 조정할 수도 있습니다. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +삼항 연산자를 사용하면 코드가 깔끔해지고, 메시지는 최종 사용자나 로그를 보는 개발자에게 충분히 명확합니다. + +## 전체 작동 예제 + +모두 합치면, `Program.cs`에 복사‑붙여넣기하고 `dotnet run`으로 실행할 수 있는 독립형 프로그램이 여기 있습니다. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### 예상 출력 + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +SDK가 예외를 발생시키면(예: 네이티브 DLL 누락), catch 블록이 전체 앱이 충돌하는 대신 도움이 되는 오류 메시지를 출력합니다. + +## 엣지 케이스 및 일반적인 함정 처리 + +### 1. Null 엔진 인스턴스 + +생성자는 일반적으로 유효한 객체를 반환하지만, 필수 네이티브 종속성이 없을 경우 일부 SDK는 `null`을 반환할 수 있습니다. 이를 방지하세요: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. 실행 중 라이선스 만료 + +트라이얼 라이선스는 세션 중간에 만료될 수 있습니다. 앱이 오래 실행되는 경우 `IsEvaluation`을 주기적으로 다시 조회하세요. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. 버전별 속성 이름 차이 + +구버전에서는 `engine.EvaluationMode` 또는 `engine.License.IsTrial`을 제공할 수 있습니다. 업그레이드 시 SDK 릴리스 노트에서 호환성 깨짐 변경 사항을 확인하세요. + +### 4. 다중 스레드 시나리오 + +여러 OCR 워커를 시작하는 경우, SDK가 명시적으로 스레드 안전 공유를 지원하지 않는 한 **스레드당 하나의 OCR 엔진을 인스턴스화**하십시오. 단일 엔진을 공유하면 레이스 컨디션 및 잘못된 라이선스 판독이 발생할 수 있습니다. + +## 프로덕션 사용을 위한 팁 + +- **Cache the licensing status** 첫 번째 확인 후 라이선스 상태를 캐시하여 불필요한 속성 호출을 방지합니다. +- **Log the license key** (마스킹) 를 시작 시 기록하여 감사 추적을 남기고, 지원 팀이 라이선스 문제를 진단하는 데 도움을 줍니다. +- **Provide a UI toggle** 로 사용자가 트라이얼 모드임을 알리고 “Buy License” 버튼을 제공합니다. +- **Automate license renewal** 를 위해 SDK의 활성화 API를 사용(가능한 경우)하여 사용자 경험을 원활하게 유지합니다. + +## 결론 + +우리는 이제 몇 줄의 코드로 **created OCR engine** 객체를 만들고, **OCR engine evaluation mode**를 검사하며, 명확한 **OCR licensing status** 메시지를 출력했습니다. 전체 예제는 바로 실행 가능하고, 오류를 우아하게 처리하며, 각 단계 뒤에 있는 “왜”를 강조하므로 데스크톱, 웹, 서비스‑사이드 시나리오에 적용할 수 있습니다. + +다음과 같은 항목들을 시도해 보세요. + +- 이미지를 `engine.Recognize`에 전달하고 다국어 지원을 처리하기. +- **check OCR license** API를 사용하여 구매한 키를 프로그래밍 방식으로 활성화하기. +- UI 프레임워크(WinForms, WPF, MAUI)와 통합하여 라이선스 배지를 표시하기. + +위 항목들을 시도해 보세요. 그러면 모든 애플리케이션에 사용할 수 있는 견고한 OCR 기반을 갖추게 됩니다. 즐거운 코딩 되세요! + +## 관련 튜토리얼 + +- [OCR 추출 방법 – OCR 구성](/ocr/english/net/ocr-configuration/) +- [Aspose.OCR for .NET으로 OCR 결과 얻는 방법](/ocr/english/net/text-recognition/get-recognition-result/) +- [Aspose.OCR을 사용한 .NET에서 PDF OCR 방법](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/ocr-optimization/_index.md b/ocr/korean/net/ocr-optimization/_index.md index 68a12ee39..123af0860 100644 --- a/ocr/korean/net/ocr-optimization/_index.md +++ b/ocr/korean/net/ocr-optimization/_index.md @@ -63,11 +63,13 @@ Aspose.OCR for .NET와 원활한 OCR 통합을 탐색하세요. 이미지에서 ### [Prepare Rectangles in OCR Image Recognition](./prepare-rectangles/) Aspose.OCR for .NET의 잠재력을 우리의 포괄적인 가이드와 함께 활용하세요. 이미지 인식을 위한 사각형 준비 방법을 단계별로 배우고, .NET 애플리케이션을 원활한 OCR 통합으로 향상시킵니다. ### [Preprocessing Filters for Image in OCR Image Recognition](./preprocessing-filters-for-image/) -Aspose.OCR for .NET를 탐색하세요. 전처리 필터로 OCR 정확도를 높이고, 지금 다운로드하여 원활한 통합을 경험하세요. +Aspose.OCR를 탐색하세요. 전처리 필터로 OCR 정확도를 높이고, 지금 다운로드하여 원활한 통합을 경험하세요. ### [Result Correction with Spell Checking in OCR Image Recognition](./result-correction-with-spell-checking/) -Aspose.OCR for .NET로 OCR 정확도를 향상시키세요. 철자를 교정하고, 사전을 사용자 정의하며, 오류 없는 텍스트 인식을 손쉽게 달성합니다. +Aspose.OCR로 OCR 정확도를 향상시키세요. 철자를 교정하고, 사전을 사용자 정의하며, 오류 없는 텍스트 인식을 손쉽게 달성합니다. ### [Save Multipage Result as Document in OCR Image Recognition](./save-multipage-result-as-document/) -Aspose.OCR for .NET의 잠재력을 활용하세요. 이 포괄적인 단계별 가이드를 통해 다중 페이지 OCR 결과를 문서로 손쉽게 저장합니다. +Aspose.OCR의 잠재력을 활용하세요. 이 포괄적인 단계별 가이드를 통해 다중 페이지 OCR 결과를 문서로 손쉽게 저장합니다. +### [OCR을 위한 이미지 전처리 – 완전한 Aspose C# 가이드](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Aspose.OCR를 사용해 이미지 전처리 과정을 단계별로 안내하며, OCR 정확도를 극대화하는 방법을 배웁니다. ## 자주 묻는 질문 diff --git a/ocr/korean/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/korean/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..9cb67b865 --- /dev/null +++ b/ocr/korean/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,229 @@ +--- +category: general +date: 2026-05-25 +description: Aspose를 사용하여 OCR을 위한 이미지를 전처리하고 OCR 정확도를 향상시키며 JPEG 파일에서 OCR을 실행합니다. + 명확하고 단계별 튜토리얼에서 Aspose를 사용한 텍스트 추출 방법을 배워보세요. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: ko +og_description: Aspose를 사용해 OCR 정확도를 높이기 위해 이미지를 전처리하세요. 이 가이드를 따라 JPEG에서 OCR을 실행하고 + C#에서 Aspose로 텍스트를 추출하세요. +og_title: OCR을 위한 이미지 전처리 – Aspose C# 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: OCR을 위한 이미지 전처리 – 완전한 Aspose C# 가이드 +url: /ko/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR용 이미지 전처리 – 완전한 Aspose C# 가이드 + +이미지를 **OCR용으로 전처리**하면 텍스트가 매번 깨끗하게 추출된다는 생각을 해본 적 있나요? 당신만 그런 것이 아닙니다—개발자들은 끊임없이 잡음이 많은 스캔, 저대비 JPEG, 예측할 수 없는 조명과 싸우고 있습니다. 좋은 소식은? 몇 가지 스마트한 조정만으로 **OCR 정확도**를 크게 향상시킬 수 있으며, Aspose가 이를 손쉽게 만들어 줍니다. + +이 튜토리얼에서는 실제 예제를 통해 **JPEG 이미지에 OCR을 실행**하고, 맞춤형 이미지 처리 파이프라인을 적용한 뒤 **Aspose를 사용해 텍스트를 추출**하는 방법을 단계별로 살펴봅니다. 마지막에는 .NET 프로젝트 어디에든 붙여넣을 수 있는 완전한 C# 스니펫을 제공할 것입니다. + +## 배울 내용 + +- 전처리가 왜 중요한지와 가장 큰 효과를 주는 필터는 무엇인지. +- Deskew, Denoise, Binarize, ContrastBoost 등을 위해 Aspose.OCR의 `ImageProcessingOptions`를 설정하는 방법. +- **JPEG 파일에 OCR을 실행**하고 깨끗한 텍스트를 가져오는 정확한 코드. +- 프로덕션 환경에서 OCR 파이프라인을 견고하게 유지하기 위한 팁과 함정. + +Aspose 사용 경험이 없어도 괜찮습니다; 기본적인 C# 배경과 Visual Studio(또는 선호하는 IDE)만 있으면 됩니다. 시작해 보겠습니다. + +![OCR용 이미지 전처리 예시](preprocess-ocr.png "OCR용 이미지 전처리") + +## 1단계: Aspose.OCR 엔진 설정 – OCR용 이미지 전처리 + +먼저 `OcrEngine` 인스턴스를 만들고 어떤 언어를 사용할지 알려줘야 합니다. 대부분의 경우 기본값은 영어이며, `OcrLanguage` 열거형을 변경하면 프랑스어, 독일어 등으로 바꿀 수 있습니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**왜 중요한가:** 엔진은 전체 작업의 핵심이며, 이 없이는 **OCR용 이미지 전처리**에 필요한 이미지 필터를 적용할 수 없습니다. 모든 재료가 섞이는 주방이라고 생각하면 됩니다. + +## 2단계: 맞춤형 이미지‑처리 파이프라인 구축 – OCR 정확도 향상 + +이제 핵심 부분입니다. Aspose는 여러 필터를 체인처럼 연결할 수 있게 해줍니다. 아래에서는 가장 효과적인 네 가지 필터를 활성화합니다: + +1. **Deskew** – 기울어진 문서를 바로 잡습니다(기본 최대 5°). +2. **Denoise** – 거친 배경을 부드럽게 합니다. +3. **Binarize** – 임계값을 사용해 이미지를 흑백으로 변환합니다. +4. **ContrastBoost** – 흐릿한 문자를 돋보이게 합니다. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**프로 팁:** 원본 이미지가 이미 선명하다면 `Strength` 값을 낮추거나 필터 자체를 끌 수 있습니다. 과도한 전처리는 흐릿한 문자를 지워버릴 수 있으니 실제 샘플로 실험해 보세요. + +## 3단계: JPEG(또는 기타 이미지) 로드 및 OCR 실행 – JPEG에 OCR 실행 + +Aspose는 .NET이 읽을 수 있는 모든 이미지 형식을 지원합니다—JPEG, PNG, BMP 등. 아래 코드는 JPEG 파일을 엔진에 전달하고 인식 프로세스를 시작하는 방법을 보여줍니다. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**왜 JPEG인가?** JPEG 압축은 OCR을 혼란스럽게 하는 아티팩트를 자주 만들습니다. 특히 denoise와 binarize 단계가 이러한 문제를 완화시켜 **JPEG에 OCR을 실행**할 때 자신감을 줍니다. + +## 4단계: 인식된 텍스트 출력 – Aspose로 텍스트 추출 + +마지막으로 텍스트를 콘솔, 파일 또는 다른 서비스에 기록합니다. 데모 목적이라면 콘솔에 출력하는 것으로 충분합니다. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +프로그램을 실행하면 다음과 같은 결과가 나타납니다: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +출력이 깨져 보인다면 **2단계**로 돌아가 필터 설정을 조정하세요. 작은 조정만으로도 **OCR 정확도 향상**에 큰 효과를 얻을 수 있습니다. + +## 흔히 마주치는 상황과 해결 방법 + +| 상황 | 권장 조정 | +|-----------|----------------------| +| **매우 어두운 이미지** | `ContrastBoost.Level`을 1.5 이상으로 높입니다. | +| **기울기 > 5°** | `DeskewOptions.MaxAngle`을 (예: 10.0) 높이거나 이미지를 미리 회전합니다. | +| **컬러 텍스트가 컬러 배경에 있는 경우** | 사용자 정의 임계값을 가진 `BinarizeOptions`를 사용하거나 `AdaptiveBinarizeOptions`로 전환합니다. | +| **대용량 파일 ( > 5 MB )** | 파일 잠금 문제를 피하기 위해 먼저 이미지를 `MemoryStream`에 로드합니다. | + +이러한 조정은 파이프라인을 유연하고 미래 지향적으로 만들어 주며, 특히 **Aspose를 사용해 텍스트를 추출**할 때 다양한 소스에 대응할 수 있게 해줍니다. + +## 전체 작업 예제 – 모든 단계 한 번에 + +아래는 복사‑붙여넣기 바로 가능한 전체 프로그램입니다. .NET 6+에서 컴파일되며 `Aspose.OCR` NuGet 패키지만 필요합니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +`Program.cs`로 저장하고 Aspose.OCR 패키지를 추가한 뒤(`dotnet add package Aspose.OCR`) `dotnet run`을 실행하면 정리된 텍스트가 콘솔에 출력됩니다. + +## 요약 – 이 접근법이 효과적인 이유 + +- **OCR용 이미지 전처리**: 파이프라인이 가장 흔한 오류 원인(기울기, 잡음, 저대비)을 제거합니다. +- **OCR 정확도 향상**: 각 필터가 엔진이 보는 신호‑대‑잡음 비율을 높이도록 조정됩니다. +- **JPEG에 OCR 실행**: 압축된 이미지도 deskew와 binarize 후에는 읽기 쉬워집니다. +- **Aspose로 텍스트 추출**: `Recognize` 메서드가 순수 문자열을 반환하므로 이후 로직에 바로 활용할 수 있습니다. + +이 단계들을 조합하면 몇 줄의 코드만으로도 신뢰할 수 있는 프로덕션‑급 OCR 솔루션을 만들 수 있습니다. + +## 다음 단계 및 관련 주제 + +- **배치 처리** – 폴더에 있는 이미지들을 순회하며 각각을 `.txt` 파일로 저장합니다. +- **언어 팩** – `OcrLanguage.English`를 `OcrLanguage.Spanish` 등으로 교체하거나 사용자 정의 사전을 추가합니다. +- **PDF 추출** – Aspose.OCR와 Aspose.PDF를 결합해 스캔된 PDF에서 직접 텍스트를 뽑아냅니다. +- **성능 튜닝** – 대량 작업 시 `Parallel.ForEach`를 사용해 엔진을 병렬로 실행합니다. + +필터 값을 자유롭게 실험하고, 다른 이미지 형식을 시도하거나 `SharpnessOptions`와 같은 추가 Aspose 필터를 체인에 연결해 보세요. 기본을 마스터하면 가능성은 무한합니다. + +--- + +*코딩 즐겁게! 문제가 생기면 아래 댓글로 알려 주세요. 함께 해결해 드리겠습니다.* + +## 관련 튜토리얼 + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/text-recognition/_index.md b/ocr/korean/net/text-recognition/_index.md index 1a906a77b..bce8b0f75 100644 --- a/ocr/korean/net/text-recognition/_index.md +++ b/ocr/korean/net/text-recognition/_index.md @@ -55,9 +55,23 @@ Aspose.OCR을 사용하여 .NET에서 OCR의 잠재력을 활용해 보세요. P Aspose.OCR을 사용하여 .NET에서 OCR의 잠재력을 활용해 보세요. PDF에서 텍스트를 쉽게 추출할 수 있습니다. 원활한 통합 경험을 위해 지금 다운로드하세요. ### [OCR 이미지 인식에서 테이블 인식](./recognize-table/) OCR 이미지 인식의 테이블 인식에 대한 포괄적인 가이드를 통해 .NET용 Aspose.OCR의 잠재력을 활용해 보세요. +### [Aspose OCR로 이미지에서 텍스트 인식 – 완전한 C# 가이드](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Aspose OCR를 사용하여 C#으로 이미지에서 텍스트를 추출하는 전체 가이드를 확인하세요. +### [C#에서 OCR 사용하기 – JPG에서 중국어 텍스트 인식](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Aspose.OCR를 활용해 C#으로 JPG 이미지에서 중국어 텍스트를 정확히 추출하는 단계별 가이드입니다. +### [C#에서 러시아어 텍스트 OCR – Aspose OCR을 사용한 완전 가이드](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Aspose OCR를 활용해 C#에서 러시아어 텍스트를 정확히 추출하는 단계별 전체 가이드를 확인하세요. +### [C#로 이미지에서 텍스트 추출 – 완전한 Aspose OCR 가이드](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Aspose OCR를 활용해 C#으로 이미지에서 텍스트를 추출하는 완전한 단계별 가이드를 확인하세요. +### [ASP.NET Core Minimal API에서 이미지 텍스트 추출 – 완전 가이드](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +ASP.NET Core Minimal API와 Aspose.OCR을 활용해 이미지에서 텍스트를 추출하는 전체 단계별 가이드를 확인하세요. +### [c# OCR 튜토리얼: Aspose로 PNG 영수증에서 텍스트 추출](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Aspose OCR을 사용하여 C#으로 PNG 형식 영수증 이미지에서 텍스트를 정확히 추출하는 단계별 가이드입니다. +### [C#에서 TIFF를 텍스트로 변환 – 완전 배치 OCR 가이드](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Aspose.OCR를 사용하여 C#에서 TIFF 이미지를 일괄적으로 텍스트로 변환하는 전체 가이드를 확인하세요. {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/korean/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..16b6e53be --- /dev/null +++ b/ocr/korean/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: 'c# OCR 튜토리얼: 이미지 파일을 c#으로 로드하고 Aspose OCR을 사용해 영수증의 png 텍스트를 인식하는 방법을 + 단계별로 안내합니다.' +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: ko +og_description: c# OCR 튜토리얼로 이미지 파일을 로드하고 Aspose OCR을 사용하여 영수증의 png 텍스트를 인식하는 방법을 + 안내합니다. +og_title: c# OCR 튜토리얼 – PNG 영수증에서 텍스트 추출 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR 튜토리얼: Aspose를 사용하여 PNG 영수증에서 텍스트 추출' +url: /ko/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR 튜토리얼 – Aspose로 PNG 영수증에서 텍스트 추출 + +끝없는 구글링 없이 실제로 작업을 수행하는 **c# OCR 튜토리얼**이 필요했나요? 바로 여기입니다. 이 가이드에서는 **load image file c#**, **recognize png text**, 그리고 **read receipt OCR** 결과를 다루면서 Aspose OCR로 **perform OCR image** 처리를 수행하는 방법을 보여드립니다. + +필요한 NuGet 패키지를 설치하고, 코드 한 줄씩을 살펴본 뒤, 다음 데이터 파이프라인에 바로 전달할 수 있는 깔끔한 JSON 덤프를 만들어 마무리합니다. 불필요한 내용 없이 실용적이고 바로 실행 가능한 솔루션입니다. + +## 배울 내용 + +- Aspose OCR을 .NET 6(또는 그 이후) 프로젝트에 설정하는 방법. +- 엔진에 전달하기 위한 **load an image file c#** 정확한 단계. +- 영수증 이미지에서 **recognize png text** 하고 결과를 캡처하는 방법. +- **read receipt OCR** 출력물을 깔끔하게 포맷된 JSON으로 변환하는 방법. +- 다양한 파일 유형에 대해 **perform OCR image** 작업을 수행하고 일반적인 함정을 처리하는 팁. + +**Prerequisites** +- Visual Studio 2022(또는 원하는 IDE). +- .NET 6 SDK 또는 그 이상. +- PNG 영수증 이미지가 필요합니다(예: `receipt.png`). + +준비가 되었다면, 시작해봅시다. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR 튜토리얼 – Aspose OCR 엔진 설정 + +우선 Aspose OCR 라이브러리가 필요합니다. 솔루션 폴더에서 터미널을 열고 다음을 실행하세요: + +```bash +dotnet add package Aspose.OCR +``` + +그 단일 명령은 이미지 디코딩을 위한 네이티브 바이너리를 포함한 모든 필요한 항목을 가져옵니다. 설치가 완료되면 새 콘솔 프로젝트를 만들거나 기존 프로젝트에 코드를 추가하세요. + +### 왜 Aspose인가? + +Aspose OCR은 30개 이상의 언어를 지원하고 오프라인에서도 작동하며 풍부한 `OcrResult` 객체를 반환합니다—단순 텍스트 이상이 필요한 **perform OCR image** 작업에 완벽합니다. + +## Load image file c#와 영수증 준비 + +이제 라이브러리가 준비되었으니 **load image file c#** 해봅시다. `System.Drawing.Image` 클래스가 무거운 작업을 담당하지만, 크로스‑플랫폼 대안을 원한다면 `SkiaSharp`을 사용할 수도 있습니다. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** `Image`를 `using` 문으로 감싸서(예시와 같이) 네이티브 리소스를 즉시 해제하세요—특히 루프에서 많은 파일에 대해 **perform OCR image** 할 때 중요합니다. + +## Aspose로 PNG 텍스트 인식 + +이미지가 메모리에 로드되면 엔진이 이제 **recognize png text** 할 수 있습니다. Aspose는 원시 문자열과 각 인식된 단어에 대한 상세 데이터를 모두 포함하는 `OcrResult`를 반환합니다. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +왜 더 간단한 `Recognize` 대신 `RecognizeWithResult`를 호출할까요? 전자는 신뢰도 점수, 경계 상자, 줄 바꿈 등에 접근할 수 있게 해 주어, 나중에 **read receipt OCR**을 통해 라인 아이템을 추출해야 할 때 유용합니다. + +## receipt OCR 결과를 JSON으로 읽기 + +대부분의 다운스트림 시스템은 JSON을 선호하므로 `OcrResult`를 직렬화해봅시다. `System.Text.Json` 직렬화기는 복잡한 객체를 우아하게 처리하며, 가독성을 위해 들여쓰기를 활성화합니다. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +결과 JSON은 다음과 같은 형태입니다(간략히 표시): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +이제 `jsonResult`를 데이터베이스, 메시지 큐에 파이프하거나 디버깅을 위해 간단히 로그에 남길 수 있습니다. + +## OCR 이미지 처리 수행 및 출력 표시 + +마지막으로 JSON을 콘솔에 출력합니다. 실제 애플리케이션에서는 파일에 쓰거나 HTTP로 전송할 가능성이 높지만, 콘솔은 모든 것이 정상 작동했는지 확인하기에 쉽습니다. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +프로그램을 실행(`dotnet run`)하면 깔끔하게 포맷된 JSON이 출력됩니다. 영수증 이미지가 선명하면 텍스트가 정확히 인식될 것이고, 그렇지 않다면 이미지 해상도를 높이거나 전처리 필터(예: 그레이스케일, 대비 강화)를 적용한 뒤 엔진에 전달하는 것을 고려하세요. + +### 일반적인 엣지 케이스 처리 + +| 상황 | 조치 | +|-----------|------------| +| **Image is blurry** | `System.Drawing`으로 전처리하여 선명하게 하거나 DPI를 높이세요. | +| **Receipt contains multiple languages** | `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Large batch processing** | 단일 `OcrEngine` 인스턴스를 재사용하고 각 반복에서 `Image`만 교체하세요. | +| **Memory pressure** | `Image` 객체를 즉시 Dispose하고 비동기 파이프라인을 위해 `await Task.Run`을 고려하세요. | + +이러한 조정으로 입력이 완벽하지 않더라도 **perform OCR image** 워크플로우를 견고하게 유지할 수 있습니다. + +## 마무리 + +축하합니다—이미지를 로드하고 **recognize png text** 를 수행하며 **read receipt OCR** 출력을 깔끔한 JSON으로 만든 **c# OCR 튜토리얼**을 완료했습니다. 엔진 설정, 이미지 로드, OCR 실행, 직렬화, 출력이라는 핵심 단계는 청구서, 여권 또는 기타 스캔 문서로 확장할 수 있는 탄탄한 기반을 제공합니다. + +### 다음 단계는? + +- 진정한 크로스‑플랫폼 지원을 위해 `SkiaSharp`을 사용한 **load image file c#** 를 실험해 보세요. +- `OcrResult.Words`를 깊이 파고들어 라인 아이템, 가격, 날짜 등을 추출하세요—경비 추적 앱에 최적입니다. +- 이 튜토리얼을 Azure Functions 또는 AWS Lambda와 결합해 서버리스 영수증 처리 API를 구축하세요. + +코드를 자유롭게 수정하고, 이미지를 추가하거나 다른 언어 팩으로 전환해 보세요. OCR 세계는 놀라움으로 가득하며, 이제 그 탐험을 위한 도구를 갖추었습니다. + +행복한 코딩 되세요, 그리고 영수증이 언제나 읽을 수 있기를 바랍니다! + +## 관련 튜토리얼 + +- [Aspose.OCR를 사용한 언어 선택 C# 이미지 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [이미지에서 텍스트 추출 – .NET용 Aspose.OCR OCR 최적화](/ocr/english/net/ocr-optimization/) +- [OCR 사용 방법 - 텍스트 영역 감지 없이 이미지 인식](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/korean/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..344bf13b8 --- /dev/null +++ b/ocr/korean/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,214 @@ +--- +category: general +date: 2026-05-25 +description: C#에서 Aspose.OCR을 사용하여 TIFF를 텍스트로 변환합니다. 배치 이미지‑텍스트 변환을 배우고 TIFF 파일에서 + 텍스트를 효율적으로 추출하세요. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: ko +og_description: Aspose.OCR를 사용하여 TIFF를 텍스트로 변환합니다. 이 가이드는 배치 이미지‑텍스트 변환 및 몇 줄의 C# + 코드로 TIFF 파일에서 텍스트를 추출하는 방법을 보여줍니다. +og_title: C#에서 TIFF를 텍스트로 변환 – 완전한 배치 OCR 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: C#에서 TIFF를 텍스트로 변환 – 완전한 배치 OCR 가이드 +url: /ko/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 TIFF를 텍스트로 변환 – 완전한 배치 OCR 가이드 + +Ever needed to **convert TIFF to text** but weren’t sure where to start? You’re not alone—many developers stumble over batch OCR when dealing with scanned documents. In this tutorial we’ll walk through a hands‑on solution that **extracts text from TIFF** files using Aspose.OCR, and we’ll do it in parallel so large folders finish in seconds. + +**TIFF를 텍스트로 변환**해야 할 때가 있었지만 어디서 시작해야 할지 몰랐나요? 당신만 그런 것이 아닙니다—많은 개발자들이 스캔된 문서를 다룰 때 배치 OCR에 어려움을 겪습니다. 이 튜토리얼에서는 Aspose.OCR을 사용하여 **TIFF 파일에서 텍스트를 추출**하는 실습 솔루션을 단계별로 안내하고, 병렬 처리로 큰 폴더도 몇 초 안에 완료하도록 하겠습니다. + +We’ll also touch on **batch image to text conversion** best practices, so by the end you’ll have a reusable snippet that turns a whole directory of scanned images into neat *.txt* files—perfect for indexing, searching, or feeding into downstream analytics. + +우리는 또한 **배치 이미지에서 텍스트 변환** 모범 사례에 대해서도 다룰 것이며, 최종적으로 스캔된 이미지 전체 디렉터리를 깔끔한 *.txt* 파일로 변환하는 재사용 가능한 스니펫을 얻게 됩니다—인덱싱, 검색, 또는 하위 분석에 활용하기에 완벽합니다. + +## 필요 사항 + +- **.NET 6.0** 이상 (코드는 .NET Framework에서도 컴파일됩니다) +- **Aspose.OCR for .NET** NuGet 패키지 (`Install-Package Aspose.OCR`) +- *.tif* 파일이 하나 이상 들어 있는 폴더 (전통적인 TIFF 스캔 형식) +- 선호하는 IDE (Visual Studio, VS Code, Rider—원하는 것을 사용하세요) + +그게 전부입니다. 외부 서비스나 API 키 없이 순수 C#와 Aspose만 사용합니다. + +![처리 중인 TIFF 파일과 결과 텍스트 파일의 스크린샷](/images/ocr-result.png "TIFF를 텍스트로 변환한 결과를 보여주는 OCR 결과") + +*(Alt text: 화면에 변환된 TIFF 텍스트 출력이 표시된 스크린샷)* + +## 1단계: OCR 엔진 설정 – TIFF를 텍스트로 변환 + +First things first, we need an `OcrEngine` instance that knows it should read English characters. The engine is the heart of the conversion; configuring it correctly ensures reliable results. + +먼저, 영어 문자를 읽어야 한다는 것을 알고 있는 `OcrEngine` 인스턴스가 필요합니다. 엔진은 변환의 핵심이며, 올바르게 구성하면 신뢰할 수 있는 결과를 보장합니다. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*왜 중요한가:* +Aspose.OCR은 수십 개의 언어를 지원합니다. 다국어 스캔을 처리하는 경우 `OcrLanguage.English`을 적절한 열거형 값으로 변경하면 됩니다. 언어를 정의하지 않으면 엔진이 자동 감지 모드로 전환되어 속도가 느리고 정확도가 떨어질 수 있습니다. + +## 2단계: 모든 TIFF 파일 수집 – 효율적으로 TIFF에서 텍스트 추출 + +Next we pull every *.tif* file from a folder you specify. Using `Directory.GetFiles` gives us a clean array that we can feed into the batch processor. + +다음으로 지정한 폴더에서 모든 *.tif* 파일을 가져옵니다. `Directory.GetFiles`를 사용하면 배치 프로세서에 전달할 수 있는 깔끔한 배열을 얻을 수 있습니다. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*팁:* 스캔 파일이 하위 폴더에 중첩되어 있는 경우 `SearchOption.AllDirectories` 플래그를 사용할 수 있습니다. 다만 재귀 깊이가 깊어지면 배치 단계에서 메모리 사용량이 증가할 수 있다는 점을 기억하세요. + +## 3단계: 병렬 OCR 수행 – 배치 이미지에서 텍스트 변환 + +Now the fun part. Aspose.OCR ships with a static helper `BatchOcr.RecognizeAll` that accepts an array of file paths, an engine, and a `parallelism` hint. We’ll spin up four threads, which on a modern quad‑core laptop gives near‑linear speed‑up. + +이제 재미있는 부분입니다. Aspose.OCR은 파일 경로 배열, 엔진, 그리고 `parallelism` 힌트를 받는 정적 헬퍼 `BatchOcr.RecognizeAll`을 제공합니다. 현대의 쿼드코어 노트북에서는 네 개의 스레드를 사용하면 거의 선형에 가까운 속도 향상을 얻을 수 있습니다. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*왜 병렬 처리인가?* +고해상도 TIFF 배치를 스캔하는 것은 CPU에 많은 부하를 줍니다. 작업을 여러 스레드에 분산하면 모든 코어를 활용해 전체 실행 시간을 크게 단축할 수 있습니다. 코어 수가 더 많은 서버에서 실행한다면 `parallelism` 값을 그에 맞게 늘리세요. + +## 4단계: 출력 쓰기 – 스캔 이미지 TXT 파일로 변환 + +Finally we loop through the dictionary and write each piece of text to a *.txt* file that shares the original base name. This is the moment where **convert scanned images txt** becomes a reality. + +마지막으로 사전을 순회하면서 각 텍스트를 원본 파일명과 동일한 기본 이름을 가진 *.txt* 파일에 씁니다. 바로 이 순간 **convert scanned images txt**가 현실이 됩니다. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### 코드가 수행하는 작업을 쉬운 영어로 설명 + +1. **Create** 영어용 OCR 엔진을 설정합니다. +2. **Collect** 대상 폴더에서 모든 TIFF 파일을 수집합니다. +3. **Run** 네 개의 스레드로 `BatchOcr.RecognizeAll`을 실행하여 각 이미지를 문자열로 변환합니다. +4. **Loop** 결과를 순회하면서 `.tif` 확장자를 `.txt`로 바꾸고 문자열을 디스크에 씁니다. + +이것이 전체 **convert TIFF to text** 워크플로우이며, 50줄 이하의 코드로 구현됩니다. + +## 예외 상황 처리 – 문제가 발생했을 때 + +- **Missing or corrupted TIFFs** – `BatchOcr`는 `OcrException`을 발생시킵니다. 정상적인 처리 감소가 필요하면 호출을 `try / catch`로 감싸세요. +- **Non‑English documents** – `OcrLanguage.English`을 `OcrLanguage.Spanish`, `OcrLanguage.French` 등으로 변경하거나 `OcrLanguage.AutoDetect`를 사용하세요. +- **Very large images** – OCR 전에 DPI를 낮추는 것을 고려하세요 (`ocrEngine.ImagePreprocessing.Dpi = 200`) 메모리를 절약할 수 있지만 정확도가 떨어질 수 있습니다. +- **Output encoding** – 특정 코드 페이지가 필요하면 (예: Windows‑1252) `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`에 전달하세요. + +## 견고한 배치 변환을 위한 전문가 팁 + +- **Log failures**: `List failedFiles`를 생성하고 예외가 발생한 파일을 추가하세요; 루프가 끝난 후 리스트를 로그에 기록합니다. +- **Reuse the engine**: 동일한 `OcrEngine` 인스턴스를 여러 파일에 재사용할 수 있습니다; 루프 내부에서 새로 생성하지 마세요. +- **Validate the result**: `if (string.IsNullOrWhiteSpace(extractedText))`와 같은 간단한 검사를 통해 빈 스캔이나 읽을 수 없는 스캔을 표시할 수 있습니다. +- **Combine with PDF**: 소스가 다중 페이지 PDF인 경우 먼저 각 페이지를 TIFF로 변환(Aspose.PDF가 지원)한 뒤 이 배치를 실행하세요. + +## 다음 단계 – 단순 변환을 넘어 + +Now that you can **extract text from TIFF** files in bulk, you might want to: + +- *.txt* 파일을 검색 인덱스(Elasticsearch, Azure Cognitive Search)에 공급합니다. +- 각 결과에 대해 언어 감지를 실행하여 문서를 지역별 파이프라인에 라우팅합니다. +- OCR 텍스트를 원본 이미지 위에 오버레이하여 검색 가능한 PDF를 생성합니다 (다시 Aspose.PDF 사용). + +이 모든 시나리오는 동일한 핵심 아이디어인 **batch image to text conversion**을 기반으로 하며, 이는 더 큰 문서 처리 시스템을 위한 빌딩 블록입니다. + +--- + +### 결론 + +이제 Aspose.OCR을 사용하여 **convert TIFF to text**하는 방법, 전체 폴더를 병렬로 처리하고 각 결과를 깔끔한 *.txt* 파일로 저장하는 방법을 배웠습니다. 이 솔루션은 가볍고 완전하게 구성 가능하며, 레거시 인보이스 디지털화, 스캔된 계약서 보관, 텍스트 검색 엔진 구동 등, 어떤 상황에서도 프로덕션에 바로 사용할 수 있습니다. + +한 번 실행해 보고, 병렬 처리 수치를 조정한 뒤, 필요에 따라 새로 만든 텍스트 파일들을 원하는 워크플로에 공급하세요. 즐거운 OCR 작업 되세요! + +--- + +## 관련 튜토리얼 + +- [폴더에서 OCR 작업을 사용하여 이미지에서 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [이미지에서 텍스트 추출 – 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/korean/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/korean/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..d4ff5463c --- /dev/null +++ b/ocr/korean/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: 최소한의 ASP.NET Core API로 이미지에서 텍스트를 추출하는 방법을 배웁니다. POST로 이미지를 업로드하고, 멀티파트 + 폼 데이터를 읽어 이미지에 OCR을 수행합니다. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: ko +og_description: 최소한의 ASP.NET Core API를 사용하여 이미지에서 텍스트를 추출합니다. 이 가이드는 POST로 이미지를 업로드하고, + 멀티파트 폼 데이터를 읽으며, 이미지에 OCR을 수행하는 방법을 보여줍니다. +og_title: ASP.NET Core에서 이미지 텍스트 추출 – 단계별 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: ASP.NET Core Minimal API에서 이미지 텍스트 추출 – 완전 가이드 +url: /ko/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ASP.NET Core Minimal API에서 이미지에서 텍스트 추출 – 완전 가이드 + +무거운 프레임워크 없이 **이미지에서 텍스트를 추출**하는 방법이 궁금하셨나요? 당신만 그런 것이 아닙니다. 영수증을 스캔하거나 손글씨 메모를 디지털화하거나 검색 인덱스를 구축할 때, 사용자가 사진을 올리고 원시 문자를 바로 받아볼 수 있는 간단한 방법이 필요합니다. + +이 튜토리얼에서는 **POST로 이미지 업로드**를 처리하고 *multipart/form‑data* 페이로드를 파싱한 뒤, 싱글톤 `OcrEngine`을 사용해 **이미지에 OCR 수행**하는 작은 ASP.NET Core Minimal API를 만들어 보겠습니다. 최종적으로 .NET 8 프로젝트에 바로 넣어 실행할 수 있는 완전한 앱을 얻을 수 있습니다. + +## 만들게 될 내용 + +- `/ocr` 경로에서 동작하는 최소 웹 앱 +- `multipart/form-data` POST 요청으로 전송된 이미지 파일을 받는 엔드포인트 +- 업로드된 파일을 읽어 OCR 엔진에 전달하고 평문 텍스트 결과를 반환하는 로직 +- 호환 가능한 GPU가 있을 경우 사용할 수 있는 (주석 처리된) GPU 가속 코드 스니펫 + +**전제 조건** +- .NET 8 SDK(이상) +- C#와 커맨드 라인에 대한 기본 지식 +- `OcrEngine` 클래스를 제공하는 OCR 라이브러리(예시에서는 가상의 NuGet 패키지를 가정) + +위 조건을 갖췄다면 바로 시작해 보세요. + +## 1단계: 프로젝트 설정 및 OCR 패키지 추가 + +먼저 새 웹 프로젝트를 만들고 OCR 라이브러리를 가져옵니다. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro tip:** 의존성을 최신 상태로 유지하세요. 최신 버전은 특히 GPU 가속 추론에서 성능 향상을 제공하는 경우가 많습니다. + +## 2단계: 싱글톤 OCR 엔진 등록 (주 서비스) + +앱 전체에서 하나의 `OcrEngine` 인스턴스만 사용하도록 합니다—요청마다 새 엔진을 만들 필요가 없습니다. 빌더의 서비스 컨테이너에 등록합니다. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**왜 싱글톤인가요?** +OCR 엔진을 초기화하는 데는 신경망 가중치를 메모리에 로드하는 등 비용이 많이 듭니다. 동일 인스턴스를 재사용하면 CPU 사이클과 RAM을 모두 절약할 수 있어 `/ocr` 호출마다 응답 속도가 빨라집니다. + +## 3단계: 애플리케이션 빌드 + +이제 `WebApplication` 객체를 구체화합니다. + +```csharp +var app = builder.Build(); +``` + +이 한 줄은 마법처럼 보이지만, 내부에서는 라우팅, 미들웨어, 그리고 방금 구성한 DI 컨테이너를 연결합니다. + +## 4단계: POST 엔드포인트 정의 – “POST로 이미지 업로드” + +튜토리얼의 핵심 부분입니다. **POST로 이미지 업로드**를 받고 multipart 페이로드를 파싱한 뒤 OCR 엔진에 전달합니다. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### 로직 상세 분석 + +| 단계 | 수행 내용 | 이유 | +|------|-----------|------| +| **ReadFormAsync** | 들어오는 *multipart/form-data* 요청을 파싱합니다. | 파일에 접근하려면 반드시 필요합니다. | +| **form.Files["image"]** | 폼 필드 이름이 `image`인 파일을 가져옵니다. | 호출자와의 계약을 명확히 합니다. | +| **Content‑type check** | 파일이 이미지인지 확인합니다(e.g., `image/png`). | OCR 엔진이 비이미지 데이터를 처리하는 것을 방지합니다. | +| **Image.FromStream** | 원시 스트림을 `System.Drawing.Image` 객체로 변환합니다. | OCR 라이브러리는 `Image` 객체를 요구합니다, 바이트 배열이 아니라. | +| **ocr.Recognize(img)** | OCR 엔진을 **이미지에서 텍스트 인식**하도록 호출합니다. | 바로 **이미지에 OCR 수행**하는 핵심 단계입니다. | +| **Results.Text** | 평문 텍스트 응답을 반환합니다. | 다운스트림 서비스가 쉽게 소비할 수 있는 형식입니다. | + +## 5단계: API 실행 + +마지막으로 웹 서버를 시작합니다. + +```csharp +app.Run(); +``` + +`dotnet run`을 실행하면 API가 `http://localhost:5000`(또는 지정한 포트)에서 대기합니다. `curl`로 테스트해 보세요: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**예상 출력:** 콘솔에 인식된 문자들이 출력됩니다. 예시: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +이미지가 흐리거나 지원되지 않는 언어인 경우 OCR 엔진은 빈 문자열이나 오류 메시지를 반환합니다—실제 서비스에서는 이러한 경우를 적절히 처리해야 합니다. + +## 엣지 케이스 및 모범 사례 + +### 1. 대용량 파일 + +기본 요청 본문 제한은 30 MB입니다. 더 큰 스캔 파일이 필요하면 다음과 같이 조정합니다: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. 비동기 OCR + +일부 OCR 라이브러리는 비동기 메서드(`RecognizeAsync`)를 제공합니다. 해당 메서드가 있다면 `ocr.Recognize(img)`를 `await ocr.RecognizeAsync(img)`로 교체하고 람다를 `async`로 표시하세요. + +### 3. 보안 고려 사항 + +- 메모리로 로드하기 전에 **파일 크기 검증**을 수행합니다. +- 파일을 디스크에 저장한다면 **파일명 정화**를 합니다. +- **Rate‑limit**을 적용해 서비스 거부 공격을 방지합니다. + +### 4. GPU 가속 + +`engine.GpuDevice = new GpuDevice(0);` 라인의 주석을 해제하고 하드웨어가 CUDA 또는 DirectML을 지원한다면, 특히 고해상도 이미지에서 눈에 띄는 속도 향상을 경험할 수 있습니다. + +## 전체 작동 예제 + +아래는 새 Minimal API 프로젝트에 그대로 복사해 넣을 수 있는 완전한 `Program.cs`입니다. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +저장하고 `dotnet run`을 실행하면 **이미지에서 텍스트 추출**을 즉시 사용할 수 있습니다. + +## 결론 + +ASP.NET Core Minimal API를 활용해 **이미지에서 텍스트를 추출**하는 **완전한 엔드‑투‑엔드 솔루션**을 살펴보았습니다. 프로젝트 스캐폴딩부터 **싱글톤 OCR 엔진 등록**, **POST로 이미지 업로드** 엔드포인트 구현, **multipart/form-data 읽기**, 그리고 **이미지에 OCR 수행**까지 전 과정을 다루었습니다. + +다음 단계로 할 수 있는 일: + +- richer한 응답을 위한 JSON 래퍼 추가 +- 추출된 텍스트를 저장할 데이터베이스 연동 +- 다국어 지원 확대 (`OcrLanguage.Spanish` 등) + +이 패턴은 마이크로서비스에 그대로 끼워 넣거나 API 게이트웨이 뒤에 배치해도 잘 확장됩니다. + +PDF 처리, 배치 작업, GPU 튜닝 등에 대한 질문이 있으면 댓글로 남겨 주세요. 즐거운 코딩 되세요! + +## 관련 튜토리얼 + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/korean/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..5a2990d12 --- /dev/null +++ b/ocr/korean/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: C#와 Aspose OCR을 사용하여 이미지에서 텍스트를 추출합니다. JPG를 텍스트로 변환하고, OCR을 위해 이미지를 로드하며, + 빠르고 신뢰할 수 있는 결과를 얻는 방법을 배워보세요. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: ko +og_description: C#를 사용하여 이미지에서 텍스트 추출하기. 이 가이드는 JPG를 텍스트로 변환하고, OCR을 위해 이미지를 로드하며, + 다국어 콘텐츠를 처리하는 방법을 보여줍니다. +og_title: C#에서 이미지에서 텍스트 추출 – Aspose OCR 튜토리얼 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: C#에서 이미지 텍스트 추출 – 완전한 Aspose OCR 가이드 +url: /ko/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 이미지에서 텍스트 추출 – 완전한 Aspose OCR 가이드 + +일반 C# 코드를 사용하여 **extract text from image**(이미지에서 텍스트 추출)하는 방법이 궁금했나요? 당신만 그런 것이 아닙니다. 영수증을 디지털화하거나, 간판을 스캔하거나, OCR에 호기심이 있든, 사진에서 문자를 추출하는 능력은 유용한 기술입니다. 이 튜토리얼에서는 Aspose.OCR을 사용하여 **extract text from image**를 정확히 수행하는 전체 실행 가능한 예제를 단계별로 살펴보고, **convert jpg to text**, **load image for OCR** 방법 및 고전적인 “**how to ocr image**” 질문에 대한 답을 한 번에 제공하겠습니다. + +이 가이드를 끝까지 따라오면 JPEG 파일을 읽고, 우크라이나어(또는 지원되는 다른 언어)를 인식하며, 결과를 콘솔에 출력하는 독립 실행형 콘솔 앱을 만들 수 있습니다. 모호한 참고 자료도, 누락된 부분도 없습니다—그냥 복사‑붙여넣기만 하면 바로 실행할 수 있는 완전한 솔루션입니다. + +--- + +## 배울 내용 + +* Aspose.OCR NuGet 패키지를 설치하는 방법. +* C#에서 **load image for OCR**에 필요한 정확한 코드. +* 언어를 설정하고 실제로 **extract text from image**하는 방법. +* **convert jpg to text**를 효율적으로 수행하는 요령. +* 흔히 발생하는 함정과 회피 방법. + +이미 .NET 개발 환경이 갖춰져 있다면 바로 시작할 수 있습니다. 그렇지 않다면 아래 전제 조건 섹션에서 준비 과정을 확인하세요. + +--- + +## 전제 조건 + +| 요구 사항 | 중요 이유 | +|-------------|----------------| +| .NET 6.0 SDK (or newer) | 콘솔 앱 실행 환경을 제공합니다. | +| Visual Studio 2022 or VS Code | 편집 및 디버깅을 쉽게 해줍니다. | +| Internet connection (first run) | NuGet이 Aspose.OCR을 다운로드해야 합니다. | +| A JPEG image you want to process (e.g., `ukrainian_sign.jpg`) | OCR 엔진의 소스 파일입니다. | + +> **Pro tip:** Linux나 macOS를 사용한다면 .NET CLI(`dotnet new console`)로 동일한 코드를 실행할 수 있으니 무거운 IDE를 건너뛰어도 됩니다. + +--- + +## Step 1 – Install Aspose.OCR via NuGet + +터미널(또는 Package Manager Console)을 열고 다음을 실행하세요: + +```bash +dotnet add package Aspose.OCR +``` + +이 한 줄로 최신 Aspose.OCR 바이너리와 모든 전이 종속성이 다운로드됩니다. 수동으로 DLL을 다룰 필요가 없습니다. + +--- + +## Step 2 – Create the OCR Engine (The Heart of Extraction) + +라이브러리가 준비되었으니 이제 `OcrEngine` 인스턴스를 생성합니다. 이 객체는 **extracting text from image** 데이터를 담당합니다. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Why this matters:** 엔진은 OCR 알고리즘, 언어 모델 및 구성 옵션을 캡슐화합니다. 한 번 인스턴스를 만들고 여러 이미지에 재사용하면 메모리 효율도 높고 속도도 빠릅니다. + +--- + +## Step 3 – Load Image for OCR (And Set the Language) + +다음 단계는 엔진에 어떤 사진을 읽을지 알려주는 것입니다. 여기서 **load image for OCR** 문구가 등장합니다. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Edge case:** 파일이 존재하지 않으면 `Image.FromFile`이 `FileNotFoundException`을 발생시킵니다. 실제 서비스 코드에서는 try‑catch 블록으로 감싸는 것이 좋습니다. + +--- + +## Step 4 – Perform OCR and Extract Text + +이미지가 로드되면 엔진이 이제 **extract text from image**를 수행할 수 있습니다. `Recognize` 메서드가 핵심 작업을 담당합니다. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +모든 것이 정상적으로 진행되면 `recognizedText`에 OCR 엔진이 읽어들인 모든 텍스트의 순수 문자열 표현이 들어갑니다. + +--- + +## Step 5 – Convert JPG to Text (Putting It All Together) + +지금까지 만든 코드는 이미 **convert jpg to text**를 수행하지만, 반복 호출할 수 있는 깔끔한 메서드로 감싸 보겠습니다. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +이제 간단히 다음과 같이 사용할 수 있습니다: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Expected output** (간략히 표시): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +이미지에 영어 텍스트가 포함되어 있다면 `OcrLanguage.English`으로 변경하면 해당 출력이 표시됩니다. + +--- + +## Step 6 – Handling Common “How to OCR Image” Questions + +### 6.1 Can I OCR a PNG or BMP? + +물론 가능합니다. `Image.FromFile` 메서드는 System.Drawing이 인식하는 모든 포맷을 지원하므로 경로를 `.png` 또는 `.bmp` 파일로 지정하면 나머지 코드는 그대로 사용할 수 있습니다. + +### 6.2 What if the image is low‑resolution? + +300 dpi 이하에서는 OCR 정확도가 크게 떨어집니다. 간단한 해결책은 엔진에 전달하기 전에 `Graphics`를 사용해 이미지를 확대하는 것입니다: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Do I need a license for Aspose.OCR? + +Aspose는 워터마크가 포함된 무료 체험판을 제공합니다. 실제 서비스에서는 라이선스를 구매하고 다음 코드를 추가하세요: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Full Working Example + +아래는 **how to OCR image**, **load image for OCR**, **convert jpg to text**를 한 번에 보여주는 완전한 실행 가능한 콘솔 애플리케이션 예제입니다. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**How to run it** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +콘솔에 추출된 텍스트가 출력되는 것을 확인할 수 있으며, 이를 통해 C#으로 **extract text from image**를 성공적으로 수행했음을 알 수 있습니다. + +--- + +## Common Pitfalls & Pro Tips + +| Issue | Why it happens | Fix | +|-------|----------------|-----| +| Blank output | Image too dark or low contrast. | `Bitmap`을 사용해 밝기를 높이는 전처리 수행. | +| Wrong language | `Language` property left at default English. | `ocrEngine.Language = OcrLanguage.Ukrainian;` 등 목표 언어를 명시적으로 설정. | +| Out‑of‑memory error | Very large images loaded without disposal. | `Image.FromFile`을 `using` 블록으로 감싸서 메모리 해제 (예시 참고). | +| License watermark | Running on a trial without a license. | `Main` 초기에 구매한 라이선스를 적용. | + +--- + +## Conclusion + +우리는 C#에서 **extract text from image**를 수행하는 데 필요한 모든 과정을 다루었습니다—Aspose.OCR 설치부터 **load image for OCR**, **convert jpg to text**까지, 그리고 다국어 시나리오 처리까지. 완전한 샘플 프로그램이 모든 요소를 연결해 주므로 OCR 관련 프로젝트의 신뢰할 수 있는 기반이 됩니다. + +다음 단계로 살펴볼 내용: + +* 파일 대신 **how to OCR image** 스트림을 사용하는 방법 (`MemoryStream` 활용). +* **c# image to text** 후처리로 맞춤법 검사 추가. +* OCR 단계를 더 큰 파이프라인에 통합 (예: 결과를 데이터베이스에 저장). + +다양한 언어, 이미지 포맷, 전처리 기법을 실험해 보세요. OCR은 과학이자 예술이며, 많이 시도할수록 결과가 개선됩니다. + +행복한 코딩 되시고, 여러분의 이미지가 언제나 읽히길 바랍니다! + +## Related Tutorials + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/korean/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..386662869 --- /dev/null +++ b/ocr/korean/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,300 @@ +--- +category: general +date: 2026-05-25 +description: C#에서 OCR을 사용하여 이미지 파일에서 텍스트를 추출하는 방법. 몇 단계만으로 Aspose.OCR을 이용해 JPG에서 중국어 + 문자를 인식하는 방법을 배워보세요. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: ko +og_description: C#에서 OCR을 사용하여 이미지 파일에서 텍스트를 추출하는 방법. 이 가이드는 Aspose.OCR을 사용해 JPG에서 + 중국어 문자를 인식하는 방법을 보여줍니다. +og_title: C#에서 OCR 사용 방법 – JPG에서 중국어 텍스트 인식 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: C#에서 OCR 사용 방법 – JPG에서 중국어 텍스트 인식 +url: /ko/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 OCR 사용 방법 – JPG에서 중국어 텍스트 인식 + +휴대폰으로 찍은 사진에서 **OCR을 어떻게 사용**해 단어를 추출할 수 있을지 궁금했던 적 있나요? 당신만 그런 것이 아닙니다. 영수증 스캐너, 번역 앱, 자동 데이터 입력과 같은 실제 프로젝트에서는 **이미지에서 텍스트 추출**을 빠르고 안정적으로 수행해야 합니다. + +이 튜토리얼에서는 **JPG 파일에서 텍스트를 인식**하고, **OCR Chinese Simplified** 언어 팩을 사용해 **중국어 문자 인식**이라는 까다로운 경우까지 처리하는 완전한 실행 예제를 단계별로 살펴봅니다. 최종적으로는 별도의 수동 다운로드 없이도 감지된 문자열을 콘솔에 출력하는 독립 실행형 콘솔 앱을 만들 수 있습니다. + +> **빠른 참고:** 코드는 Aspose.OCR ≥ 23.7에서 동작하며, 최초 사용 시 자동으로 언어 리소스를 가져옵니다. 이전 버전을 사용 중이라면 언어를 수동으로 추가해야 합니다. + +## 사전 요구 사항 + +시작하기 전에 다음이 설치되어 있는지 확인하세요: + +- .NET 6.0 SDK 이상 (예제는 .NET 6을 대상으로 하지만 .NET 5에서도 작동합니다) +- 최신 Visual Studio 2022 또는 C# 확장 기능이 설치된 VS Code +- 최초 언어 다운로드를 위한 인터넷 연결 +- Simplified Chinese 텍스트가 포함된 JPG 이미지 (`chinese_sign.jpg` 라고 가정) + +그 외에 별도의 무거운 OCR 엔진이나 네이티브 DLL이 필요하지 않습니다. NuGet 명령 몇 개와 몇 줄의 코드만 있으면 됩니다. + +## 1단계: NuGet을 통해 Aspose.OCR 설치 + +먼저 OCR 라이브러리를 가져와야 합니다. 프로젝트 폴더에서 터미널을 열고 다음을 실행하세요: + +```bash +dotnet add package Aspose.OCR +``` + +또는 Visual Studio UI를 선호한다면 **Dependencies → Manage NuGet Packages**를 마우스 오른쪽 버튼으로 클릭하고 “Aspose.OCR”을 검색한 뒤 **Install**을 클릭합니다. + +> **프로 팁:** 패키지를 최신 상태로 유지하세요. 새로운 언어 팩과 성능 개선이 매 마이너 릴리스마다 추가됩니다. + +## 2단계: 새 콘솔 프로젝트 생성 (아직 만들지 않았다면) + +처음부터 시작한다면 새 콘솔 앱을 만들어요: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +이제 OCR 코드를 넣을 `Program.cs` 파일이 준비되었습니다. + +## 3단계: OCR 코드 작성 – JPG에서 Simplified Chinese 인식 + +`Program.cs`를 열고 내용을 다음으로 교체합니다. 각 줄마다 *왜* 이 작업을 하는지, *무엇을* 하는지 주석으로 설명되어 있습니다. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 내부에서 무슨 일이 일어나나요? + +- **`OcrEngine.Language`** 는 Aspose에 어떤 사전을 사용할지 알려줍니다. `ChineseSimplified` 를 지정하면 엔진이 Simplified Chinese 언어 팩을 사용하도록 지시합니다. +- **첫 번째 다운로드**: `Recognize` 가 실행될 때 SDK가 Aspose CDN에 연결해 약 6 MB 크기의 언어 파일을 받아 로컬에 캐시한 뒤 OCR을 진행합니다. 이후 호출은 즉시 처리됩니다. +- **`Image.FromFile`** 은 .NET이 디코딩할 수 있는 모든 래스터 포맷(JPG, PNG, BMP 등)과 호환되므로 **이미지에서 텍스트 추출**을 JPG에 국한하지 않고 다양한 형식에 적용할 수 있습니다. + +## 4단계: 애플리케이션 실행 및 출력 확인 + +빌드하고 실행합니다: + +```bash +dotnet run +``` + +다음과 비슷한 결과가 표시될 것입니다: + +``` +=== Recognized Text === +欢迎光临 +``` + +콘솔에 의미 없는 문자나 빈 문자열이 출력된다면 다음을 확인하세요: + +1. 이미지에 선명하고 고대비인 중국어 문자가 포함되어 있는지. +2. 파일 경로에 공백이나 확장자 누락이 없는지. +3. 언어 팩을 다운로드하기 위해 `https://download.aspose.com` 에 접근할 수 있는지. + +## 5단계: 엣지 케이스 및 흔히 발생하는 문제 처리 + +### 5.1 저품질 이미지 다루기 + +이미지가 흐리거나 잡음이 많거나 조명이 부족하면 OCR 정확도가 떨어집니다. 간단한 해결책은 이미지를 전처리하는 것입니다: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 헤드리스 환경에서 실행하기 + +GUI가 없는 Linux 컨테이너에 배포한다면 `System.Drawing` 에 필요한 `libgdiplus` 라이브러리를 설치해야 합니다: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 언어 팩 수동 캐시 + +언어 파일을 한 번 다운로드한 뒤 `License` API를 통해 Aspose에 경로를 지정하면 네트워크 호출을 한 번만 수행하게 할 수 있습니다. 오프라인 시나리오에 유용합니다. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## 전체 작업 예제 (All‑In‑One) + +아래는 `Program.cs`에 그대로 복사‑붙여넣기 할 수 있는 **전체** 프로그램입니다. 숨겨진 부분이나 외부 스크립트가 없습니다. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### 예상 출력 + +JPG에 “欢迎光临” 문구가 포함되어 있다면 콘솔에 다음과 같이 출력됩니다: + +``` +=== Recognized Text === +欢迎光临 +``` + +이미지를 다른 Simplified Chinese 간판, 거리 이름, 제품 라벨 등으로 교체해도 엔진이 최선을 다해 인식합니다. + +## 결론 + +우리는 C#에서 **OCR을 사용해 이미지 파일에서 텍스트를 추출**하는 방법을 살펴보았으며, 특히 **JPG에서 중국어 문자 인식**이라는 과제를 해결했습니다. Aspose.OCR의 실시간 언어 다운로드 기능을 활용하면 배포 크기를 최소화하면서도 **OCR Chinese Simplified** 를 바로 지원할 수 있습니다. + +다음 단계는 어떨까요? + +- **배치 처리**: 이미지 폴더를 순회하면서 각 결과를 CSV 파일에 기록하기. +- **번역 API와 결합**: 인식된 문자열을 Azure Translator에 전달해 실시간 다국어 앱 만들기. +- **다른 언어 탐색**: `OcrLanguage.ChineseSimplified` 를 `Japanese` 혹은 `Arabic` 등으로 바꿔 동일 코드를 테스트해 보기. + +성능 튜닝, 라이선스, 웹 서비스와의 OCR 통합 등에 대한 질문이 있으면 아래 댓글로 남겨 주세요—행복한 코딩 되세요! + +--- + +![JPG 이미지에서 중국어 텍스트를 인식하기 위한 C# OCR 사용 방법을 보여주는 콘솔 출력 스크린샷](ocr-chinese-demo.png "OCR 콘솔 출력 예시") + +## 관련 튜토리얼 + +- [Aspose.OCR를 사용한 언어 선택으로 이미지 텍스트 추출 C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [다중 언어를 위한 Aspose OCR 이미지 텍스트 인식](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [OCR에서 사각형을 지정해 이미지 텍스트 추출하기](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/korean/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/korean/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..6eb75e238 --- /dev/null +++ b/ocr/korean/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: C#에서 러시아어 텍스트를 OCR하는 방법과 Aspose OCR을 사용해 이미지에서 텍스트를 추출하는 방법을 배워보세요. 이미지 + 를 텍스트로 빠르게 변환하는 단계별 C# 코드. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: ko +og_description: C#에서 러시아어 텍스트 OCR을 쉽게 할 수 있습니다. 이미지에서 텍스트를 추출하고, 이미지를 텍스트로 변환하며, Aspose + OCR을 사용해 OCR용 이미지를 로드하는 방법을 배워보세요. +og_title: C#에서 러시아어 텍스트 OCR – 완전한 Aspose OCR 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: C#에서 러시아어 텍스트 OCR – Aspose OCR을 이용한 완전 가이드 +url: /ko/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#에서 러시아어 텍스트 OCR – Aspose OCR을 이용한 완전 가이드 + +C#에서 러시아어 텍스트를 OCR 해야 하는데 어떤 라이브러리를 사용해야 할지 고민했던 적 있나요? 당신만 그런 것이 아닙니다. 키릴 문자 이미지에서 깨끗하고 읽기 쉬운 문자를 추출하는 일은 마치 비밀 메시지를 해독하는 것과 같으며, 특히 올바른 언어 모델을 설정하지 않았다면 더욱 그렇습니다. + +이 튜토리얼에서는 **extract text from image** 파일을 어떻게 처리하고, *image to text C#* 스타일로 변환하며, Aspose OCR을 사용해 러시아어 인식의 미묘한 차이를 다루는 실습 예제를 단계별로 안내합니다. 최종적으로 OCR을 위해 이미지를 로드하고 인식된 문자열을 출력하는 실행 가능한 콘솔 앱을 만들 수 있게 되며, 더 복잡한 시나리오를 위한 탄탄한 기반을 갖추게 됩니다. + +## What You’ll Learn + +- **Aspose OCR C#**를 러시아어 지원을 위해 설치하고 구성하는 방법. +- **load image for OCR** 및 엔진 호출에 필요한 정확한 단계. +- 언어 리소스 누락이나 흐릿한 스캔과 같은 일반적인 함정 처리 팁. +- 여러 파일을 배치 처리하거나 신뢰도 임계값을 조정하는 등 솔루션을 확장하는 방법. + +Aspose 사용 경험이 없어도 괜찮습니다; C# 및 .NET에 대한 기본적인 이해만 있으면 바로 시작할 수 있습니다. + +## Prerequisites + +시작하기 전에 다음 항목을 준비하세요: + +1. **.NET 6.0**(또는 그 이상) SDK – 코드는 .NET Core와 .NET Framework 모두에서 동작합니다. +2. **Visual Studio 2022**(또는 선호하는 IDE). +3. **Aspose.OCR for .NET** NuGet 패키지 – Aspose 웹사이트에서 무료 체험 키를 받을 수 있습니다. +4. **러시아어 언어 모델** 파일(`rus.traineddata`) – Aspose 리소스 페이지에서 다운로드하여 이후에 참조할 폴더에 넣으세요. +5. 명확한 키릴 문자 텍스트가 포함된 샘플 이미지(`russian_doc.png`). + +모두 준비되었나요? 좋습니다—시작해봅시다. + +## Step 1: Set Up the Project and Install Aspose OCR + +먼저 새 콘솔 프로젝트를 생성합니다: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +이제 Aspose OCR 패키지를 추가합니다: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** 체험 라이선스를 사용하는 경우 `Aspose.Total.lic` 파일을 손에 넣어두세요; 코드에서 이를 로드하면 워터마크를 방지할 수 있습니다. + +패키지가 설치되면 `Program.cs`를 엽니다. 기본 `Main` 메서드가 보일 텐데, 여기 내용을 아래 스켈레톤으로 교체합니다. + +## Step 2: Configure the OCR Engine for Russian Language + +작업의 핵심은 `OcrEngine` 객체입니다. 여기에는 두 가지 정보를 알려줘야 합니다: 인식할 언어와 언어 모델 파일이 위치한 경로. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Why this matters:** `Language = OcrLanguage.Russian` 설정을 건너뛰면 엔진이 기본값인 영어를 사용하게 되고, 모든 키릴 문자가 깨진 기호로 나타납니다. `ResourceFolder`는 `rus.traineddata` 파일이 들어 있는 디렉터리를 가리키며, 이 경로가 없으면 Aspose가 *resource not found* 예외를 발생시킵니다. + +## Step 3: Load the Image for OCR + +이제 **load image for OCR** 해야 합니다. Aspose OCR은 `System.Drawing.Image`와 함께 작동하므로 PNG, JPEG, BMP 등 지원되는 형식이면 어떤 것이든 전달할 수 있습니다. 파일 경로가 정확한지 확인하세요; 실행 파일 옆에 이미지를 두면 상대 경로도 문제없이 동작합니다. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** 이미지 파일이 5 MB를 초과한다면 먼저 축소하는 것이 좋습니다. DPI가 너무 낮으면 OCR 정확도가 떨어지고, 대용량 파일은 메모리 압박을 유발할 수 있습니다. 필요하다면 `Graphics`를 이용해 빠르게 리사이즈할 수 있습니다. + +## Step 4: Recognize the Text – From Image to Text C# Style + +엔진을 설정하고 이미지를 로드했으면 실제 인식은 한 줄 호출로 끝납니다: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +프로그램을 실행(`dotnet run`)하면 다음과 같은 출력이 나타납니다: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +출력이 의미 없는 문자열이라면 다음을 다시 확인하세요: + +- `ResourceFolder`에 `rus.traineddata` 파일이 존재하는지. +- 이미지가 너무 흐릿하지 않은지; OCR 전에 간단한 이진화 필터를 적용해 보세요. +- 언어 설정이 정확히 `OcrLanguage.Russian`인지. + +## Step 5: Fine‑Tuning and Common Pitfalls + +### Adjusting Confidence Threshold + +Aspose OCR은 내부적으로 문자별 신뢰도 값을 반환합니다. API가 직접 노출하지는 않지만 **detailed output**을 활성화하면 신뢰도가 낮은 단어를 확인할 수 있습니다: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +오인식이 빈번하다면 다음을 시도해 보세요: + +- **Pre‑processing**: 이미지를 그레이스케일로 변환하고, 대비를 높이거나, 중간값 필터를 적용합니다. +- **DPI settings**: 키릴 문자에 최소 300 DPI 이미지를 사용하도록 합니다. + +### Batch Processing Multiple Images + +대량으로 **extract text from image** 파일을 처리해야 한다면 인식 로직을 루프에 감싸면 됩니다: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +이제 각 PNG 파일마다 별도의 `.txt` 파일이 생성됩니다—문서 아카이빙에 유용합니다. + +### Handling Unicode Output + +키릴 문자는 Unicode이므로 콘솔 인코딩이 이를 표시할 수 있도록 설정해야 합니다: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +`Main` 메서드 시작 직후 이 코드를 삽입하세요. 설정하지 않으면 러시아어 문자가 물음표(`?`)로 표시될 수 있습니다. + +## Full Working Example + +아래는 완전한 실행 가능한 코드입니다. `Program.cs`에 복사·붙여넣기하고 경로만 조정하면 바로 사용할 수 있습니다. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Expected output** (샘플 이미지에 “Пример текста на русском языке.” 라고 적혀 있다고 가정): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +다른 결과가 나오면 Step 5의 트러블슈팅 팁을 다시 검토하세요. + +## Conclusion + +이제 Aspose OCR을 사용해 C#에서 **ocr russian text**를 처리하는 전체 흐름을 마스터했습니다. 라이브러리 설치, 러시아어 모델 구성, 이미지 로드 및 깨끗한 Unicode 텍스트 변환까지 모든 단계가 포함됩니다. + +신뢰할 수 있는 OCR을 위해서는 좋은 원본 자료가 필수입니다: 선명한 글꼴, 충분한 DPI, 올바른 언어 리소스. 기본을 익힌 뒤에는 배치 처리, 클라우드 스토리지 연동, 혹은 AI 기반 사후 처리(맞춤법 검사 등)까지 확장할 수 있습니다. + +### What’s Next? + +- **aspose ocr c#**의 레이아웃 분석이나 PDF 출력 같은 고급 옵션을 탐색해 보세요. +- Azure Functions와 결합해 **extract text from image** 워크플로를 서버리스 환경에서 구현해 보세요. +- 다른 언어도 시도해 보세요— `OcrLanguage.Russian`을 `OcrLanguage.English` 혹은 지원되는 다른 코드로 바꾸면 됩니다. + +궁금한 점이나 인식이 어려운 이미지가 있나요? 아래 댓글로 알려 주세요. 즐거운 코딩 되세요! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + +## Related Tutorials + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/korean/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..7fa0c6e1c --- /dev/null +++ b/ocr/korean/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,207 @@ +--- +category: general +date: 2026-05-25 +description: C#에서 Aspose OCR을 사용하여 이미지에서 텍스트를 인식합니다. OCR용 이미지를 로드하는 방법, OCR 언어를 설정하는 + 방법, OCR 엔진을 생성하는 방법 및 TIFF에서 텍스트를 추출하는 방법을 배웁니다. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: ko +og_description: Aspose OCR을 사용하여 C#에서 이미지의 텍스트를 인식합니다. 이 튜토리얼에서는 OCR 엔진을 생성하고, OCR을 + 위해 이미지를 로드하고, OCR 언어를 설정하며, TIFF에서 텍스트를 추출하는 방법을 보여줍니다. +og_title: Aspose OCR로 이미지에서 텍스트 인식 – 완전한 C# 가이드 +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Aspose OCR을 사용하여 이미지에서 텍스트 인식 – 완전한 C# 가이드 +url: /ko/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# 이미지에서 텍스트 인식 with Aspose OCR – Complete C# Guide + +이미지에서 **텍스트를 인식**해야 했지만 속도와 정확성을 모두 제공하는 라이브러리를 찾지 못해 고민한 적이 있나요? 당신만 그런 것이 아닙니다. 많은 청구서 처리나 보관 프로젝트에서 가장 큰 어려움은 TIFF 파일에서 사용자 정의 파서를 작성하지 않고도 깨끗하고 검색 가능한 텍스트를 추출하는 것입니다. + +사실은, Aspose OCR for .NET을 사용하면 전체 파이프라인이 아주 쉬워집니다. 이 가이드에서는 패키지 설치, **OCR 엔진 생성**, TIFF 로드, OCR 언어 설정, 그리고 최종적으로 **TIFF에서 텍스트 추출**까지 필요한 모든 과정을 단계별로 안내합니다. 끝까지 따라오면 이미지 파일에서 **텍스트를 인식**할 수 있는 실행 가능한 콘솔 앱을 손에 넣을 수 있습니다. + +## Prerequisites + +- .NET 6.0 이상 (코드는 .NET Core 및 .NET Framework에서도 동작합니다) +- Visual Studio 2022 (또는 선호하는 IDE) +- Aspose.OCR NuGet 패키지 (`Aspose.OCR.Gpu` 애드온은 GPU 지원에 필요) +- 추가 속도가 필요하다면 CUDA를 지원하는 GPU (선택 사항이지만 권장) + +> **Pro tip:** GPU가 없을 경우 `GpuDevice` 라인을 생략하면 엔진이 자동으로 CPU 모드로 전환됩니다. + +## Step 1: Install Aspose OCR and Create OCR Engine + +먼저 NuGet을 통해 필요한 패키지를 추가합니다: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +이제 **OCR 엔진을 생성**할 수 있습니다. 이 객체는 프로세스의 핵심으로, 실행 장치와 메모리 제한과 같은 구성을 보관합니다. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**왜 중요한가:** 엔진을 GPU에 바인딩하면 특히 고해상도 TIFF 대량 처리 시 **이미지에서 텍스트를 인식**하는 데 걸리는 시간을 크게 단축할 수 있습니다. + +## Step 2: Load Image for OCR + +다음으로 **OCR용 이미지를 로드**해야 합니다. Aspose.OCR은 `System.Drawing.Image`를 사용하므로 GDI+가 지원하는 모든 포맷(멀티 페이지 TIFF 포함)이 가능합니다. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +멀티 페이지 TIFF를 다루는 경우 `image.SelectActiveFrame`을 사용해 페이지를 순회할 수 있지만, 대부분의 상황에서는 한 번 호출만으로 충분합니다. + +## Step 3: Set OCR Language + +엔진은 자동으로 스캔 언어를 알지 못합니다. **OCR 언어를 설정**한 뒤에 인식기를 실행해야 하며, 그렇지 않으면 출력이 엉망이 됩니다. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Did you know?** 런타임 중에 언어를 전환하는 비용이 거의 없으므로 페이지마다 이 속성을 바꿔 혼합 언어 문서를 처리할 수도 있습니다. + +## Step 4: Perform the Recognition – Recognize Text from Image + +이제 재미있는 부분, 실제로 **이미지에서 텍스트를 인식**합니다. `Recognize` 메서드는 감지된 모든 문자를 포함한 일반 문자열을 반환합니다. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +신뢰도 점수나 바운딩 박스가 필요하면 `OcrResult` 객체를 반환하는 오버로드를 사용할 수 있지만, 대부분의 추출 작업에서는 일반 문자열이면 충분합니다. + +## Step 5: Extract Text from TIFF (and handle multi‑page files) + +소스가 여러 페이지를 가진 TIFF인 경우, 각 프레임에 대해 2‑4단계를 반복해야 합니다. 아래 예시는 **TIFF에서 텍스트를 페이지별로 추출**하는 간단한 루프입니다: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +위 코드는 각 페이지의 추출된 텍스트를 출력하므로 결과를 데이터베이스나 검색 인덱스로 바로 파이프라인에 연결하기가 매우 쉽습니다. + +## Step 6: Display or Persist the Extracted Text + +마지막으로 **추출된 텍스트를 화면에 표시**하고, 필요에 따라 파일에 저장해 나중에 처리할 수 있습니다. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +프로그램을 실행하면 인식된 문자들이 출력되고, 원본 TIFF 옆에 `extracted_text.txt` 파일이 생성됩니다. + +--- + +## Common Questions & Edge Cases + +- **GPU가 감지되지 않으면 어떻게 하나요?** + `GpuDevice` 라인을 삭제하면 엔진이 자동으로 CPU 모드로 전환됩니다. 성능은 다소 떨어지지만 결과 정확도는 유지됩니다. + +- **PNG나 JPEG 파일도 처리할 수 있나요?** + 물론 가능합니다—`Image.FromFile`은 System.Drawing이 지원하는 모든 포맷을 처리하므로 확장자와 관계없이 **OCR용 이미지를 로드**할 수 있습니다. + +- **저해상도 스캔을 어떻게 다루나요?** + `Recognize` 호출 전에 `ocrEngine.PreprocessOptions.Dpi` 값을 높여 주세요. DPI가 높을수록 엔진이 사용할 픽셀 수가 늘어나 정확도가 향상됩니다. + +- **TIFF 파일 크기에 제한이 있나요?** + `GpuMemoryLimit` 속성이 GPU 사용량을 제한합니다. 이 한도에 도달하면 엔진은 남은 페이지에 대해 자동으로 CPU로 전환합니다. + +## Conclusion + +이제 Aspose OCR을 사용해 C#에서 **이미지에서 텍스트를 인식**하는 완전한 프로덕션 수준 코드 스니펫을 보유하게 되었습니다. 튜토리얼에서는 **OCR 엔진 생성**, **OCR용 이미지 로드**, **OCR 언어 설정**, **TIFF에서 텍스트 추출** 방법을 다루었으며, 모두 GPU 가속을 활용해 속도를 높였습니다. + +다음 단계로는: + +- 다양한 언어(`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` 등) 실험 +- 출력 결과를 검색 가능한 ElasticSearch 인덱스로 통합 +- 데이터 품질 향상을 위한 후처리(맞춤법 검사, 정규식 정리) 추가 + +직접 청구서 배치에 적용해 보고, 메모리 제한을 조정하면서 OCR 성능이 급상승하는 것을 확인해 보세요. 즐거운 코딩 되세요! + +## Related Tutorials + +- [Aspose.OCR를 사용한 언어 선택이 가능한 C# 이미지 텍스트 추출](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [OCR에서 사각형을 준비하여 이미지 텍스트 추출하기](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Aspose.OCR로 이미지에서 텍스트 추출 – 라인 인식](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..35c95085e 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. +### [Utwórz silnik OCR w C# – Kompletny przewodnik](./create-ocr-engine-in-c-complete-guide/) +Pełny przewodnik tworzenia silnika OCR w C# przy użyciu Aspose.OCR, krok po kroku od konfiguracji po przetwarzanie obrazów. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/polish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..da8613bf7 --- /dev/null +++ b/ocr/polish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Utwórz silnik OCR w C# i dowiedz się, jak sprawdzić tryb ewaluacji oraz + status licencji w kilku linijkach kodu. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: pl +og_description: Utwórz silnik OCR w C# i natychmiast zobacz, jak wykrywać tryb oceny + oraz wyświetlać status licencji. +og_title: Stwórz silnik OCR w C# – Przewodnik krok po kroku +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Stwórz silnik OCR w C# – Kompletny przewodnik +url: /pl/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Utwórz silnik OCR w C# – Kompletny przewodnik + +Zastanawiałeś się kiedyś, jak **utworzyć obiekty silnika OCR** w C# bez przeszukiwania niekończącej się dokumentacji? Nie jesteś jedyny. Wielu programistów napotyka problem, gdy muszą uruchomić silnik OCR, sprawdzić, czy działa w trybie próbnym, i wyświetlić status licencji użytkownikom. + +W tym tutorialu przeprowadzimy Cię przez zwięzły, kompletny przykład, który **tworzy silnik OCR**, sprawdza jego **tryb oceny silnika OCR** i wypisuje przyjazny komunikat o stanie licencjonowania. Po zakończeniu będziesz mieć gotową do uruchomienia aplikację konsolową oraz jasny model mentalny obsługi licencjonowania OCR w własnych projektach. + +## Czego się nauczysz + +- Jak zainstancjonować `OcrEngine` (rdzeń każdego przepływu OCR). +- Dlaczego wykrywanie **trybu oceny** ma znaczenie dla zgodności i doświadczenia użytkownika. +- Najlepszy sposób **sprawdzenia statusu licencji OCR** i reagowania na nieoczekiwane stany. +- Typowe pułapki — odwołania do null, obsługa wyjątków i niezgodności wersji. + +Nie potrzebujesz żadnych zewnętrznych narzędzi poza SDK OCR, które już masz zainstalowane. Jeśli znasz podstawy składni C#, możesz śmiało zaczynać. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod kompiluje się zarówno w .NET Core, jak i .NET Framework). +- SDK OCR, które udostępnia klasę `OcrEngine` z właściwością `IsEvaluation` (np. hipotetyczny `MyOcrSdk`). +- Edytor tekstu lub IDE (Visual Studio, VS Code, Rider — wybierz swój ulubiony). + +To wszystko. Zanurzmy się. + +## Krok 1: Utwórz nowy projekt konsolowy + +Najpierw utwórz świeżą aplikację konsolową, aby móc uruchomić kod w izolacji. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Otwórz wygenerowany plik `Program.cs`. Zastąpimy jego zawartość kompletnym przykładem, który **tworzy instancje silnika OCR** i obsługuje licencjonowanie. + +## Krok 2: Zaimportuj przestrzeń nazw SDK OCR + +Zakładając, że SDK jest dodane przez NuGet (`MyOcrSdk` jest jedynie przykładem), dodaj dyrektywę using na początku pliku. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Jeśli jeszcze nie dodałeś pakietu, uruchom: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Trzymaj swoją wersję SDK aktualną; nowsze wydania często ulepszają wykrywanie trybu oceny. + +## Krok 3: Utwórz instancję silnika OCR + +Teraz w końcu **tworzymy obiekty silnika OCR**. To serce każdego przepływu OCR — można to porównać do mózgu, który później będzie odczytywał obrazy. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Dlaczego ten krok jest kluczowy? `OcrEngine` kapsułkuje całą konfigurację, pakiety językowe i dane licencyjne. Bez niego nie możesz przetwarzać obrazów ani odczytywać flagi oceny. + +> **Side note:** Niektóre SDK pozwalają przekazać obiekt konfiguracji do konstruktora (np. język, DPI). Jeśli potrzebujesz niestandardowych ustawień, zmodyfikuj odpowiednią linię. + +## Krok 4: Określ tryb oceny silnika OCR + +Większość dostawców OCR udostępnia wersję próbną, która działa w **trybie oceny**, dopóki nie zostanie podany prawidłowy klucz licencyjny. Wiedza o tym, czy jesteś w trybie próbnym, pozwala wyświetlać odpowiednie wskazówki UI lub ograniczać niektóre funkcje. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Właściwość `IsEvaluation` zwraca `true`, gdy silnik jest nielicencjonowany lub używa limitowanej czasowo wersji próbnej. To szybki, niezawodny sposób na ochronę funkcji premium. + +### Co zrobić, gdy właściwość nie istnieje? + +Starsze wersje SDK mogą udostępniać metodę taką jak `GetLicenseInfo()`. W takim wypadku należy sprawdzić zwrócony obiekt pod kątem flagi `IsTrial`. Zawsze konsultuj changelog SDK przy aktualizacjach. + +## Krok 5: Wyświetl bieżący status licencjonowania + +Na koniec pokażmy użytkownikowi, czy silnik jest licencjonowany, czy wciąż w wersji próbnej. Proste `Console.WriteLine` wystarczy, ale możesz dostosować to do aplikacji GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Operator warunkowy (`?:`) utrzymuje kod schludnym, a komunikaty są wystarczająco czytelne dla końcowych użytkowników lub deweloperów przeglądających logi. + +## Pełny działający przykład + +Łącząc wszystko razem, oto samodzielny program, który możesz skopiować do `Program.cs` i uruchomić poleceniem `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Oczekiwany wynik + +- **Wersja próbna:** + `Running in evaluation mode – limited functionality.` + +- **Wersja licencjonowana:** + `Licensed – full OCR capabilities enabled.` + +Jeśli SDK zgłosi wyjątek (np. brak natywnej biblioteki DLL), blok `catch` wypisze pomocny komunikat zamiast spowodować awarię całej aplikacji. + +## Obsługa przypadków brzegowych i typowych pułapek + +### 1. Nullowe instancje silnika + +Choć konstruktor zazwyczaj zwraca prawidłowy obiekt, niektóre SDK mogą zwrócić `null`, jeśli brak wymaganych zależności natywnych. Zabezpiecz się przed tym: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Wygaśnięcie licencji w trakcie działania + +Licencja próbna może wygasnąć w trakcie sesji. Okresowo ponownie odczytuj `IsEvaluation`, jeśli aplikacja działa przez dłuższy czas. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Różne nazwy właściwości w kolejnych wersjach + +Starsze wydania mogą udostępniać `engine.EvaluationMode` lub `engine.License.IsTrial`. Przy aktualizacji przeszukaj notatki wydawnicze SDK pod kątem zmian łamiących kompatybilność. + +### 4. Scenariusze wielowątkowe + +Jeśli uruchamiasz kilka pracowników OCR, utwórz **pojedynczy silnik OCR na wątek**, chyba że SDK wyraźnie obsługuje współdzielenie wątkowo‑bezpieczne. Współdzielenie jednego silnika może prowadzić do wyścigów i błędnych odczytów licencji. + +## Pro tipy dla środowiska produkcyjnego + +- **Cache'uj status licencji** po pierwszym sprawdzeniu, aby uniknąć niepotrzebnych wywołań właściwości. +- **Loguj klucz licencyjny** (z maskowaniem) przy starcie, aby mieć ślad audytowy — pomaga zespołom wsparcia diagnozować problemy z licencjonowaniem. +- **Udostępnij przełącznik UI**, który informuje użytkowników o trybie próbnym i oferuje przycisk „Kup licencję”. +- **Automatyzuj odnowienie licencji** przy użyciu API aktywacji SDK, jeśli jest dostępne, aby zapewnić płynne doświadczenie użytkownika. + +## Zakończenie + +Właśnie **utworzyliśmy obiekty silnika OCR** w kilku linijkach, sprawdziliśmy **tryb oceny silnika OCR** i wypisaliśmy klarowny komunikat o **statusie licencji OCR**. Pełny przykład działa od razu, obsługuje błędy w sposób elegancki i podkreśla „dlaczego” każdego kroku — dzięki czemu możesz go dostosować do aplikacji desktopowych, webowych lub serwisowych. + +Następnie możesz zbadać: + +- Przekazywanie obrazów do `engine.Recognize` i obsługę wielojęzyczności. +- Korzystanie z **check OCR license** API do programatycznej aktywacji zakupionego klucza. +- Integrację z frameworkami UI (WinForms, WPF, MAUI), aby wyświetlać odznaki licencyjne. + +Wypróbuj te pomysły, a będziesz mieć solidne podstawy OCR gotowe do każdej aplikacji. Szczęśliwego kodowania! + +## Powiązane tutoriale + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/ocr-optimization/_index.md b/ocr/polish/net/ocr-optimization/_index.md index 9273072bb..e689e7fe9 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. +### [Przetwarzanie obrazu przed OCR – Kompletny przewodnik Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Dowiedz się, jak zastosować pełne wstępne przetwarzanie obrazu w Aspose OCR przy użyciu C#. + ## 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/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/polish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..183d7f1a9 --- /dev/null +++ b/ocr/polish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Przygotuj obraz do OCR przy użyciu Aspose, aby zwiększyć dokładność OCR + i przeprowadzić OCR na plikach JPEG. Dowiedz się, jak wyodrębniać tekst przy użyciu + Aspose w przejrzystym, krok po kroku tutorialu. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: pl +og_description: Wstępnie przetwórz obraz do OCR przy użyciu Aspose, aby zwiększyć + dokładność OCR. Postępuj zgodnie z tym przewodnikiem, aby uruchomić OCR na pliku + JPEG i wyodrębnić tekst przy użyciu Aspose w C#. +og_title: Wstępne przetwarzanie obrazu do OCR – Poradnik Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Przygotowanie obrazu do OCR – Kompletny przewodnik Aspose C# +url: /pl/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wstępne przetwarzanie obrazu dla OCR – Kompletny przewodnik Aspose C# + +Zastanawiałeś się kiedyś, jak **preprocess image for OCR**, aby tekst zawsze wychodził czysty? Nie jesteś jedyny — programiści nieustannie walczą z zaszumionymi skanami, niskokontrastowymi JPEG‑ami i nieprzewidywalnym oświetleniem. Dobre wieści? Dzięki kilku sprytnym poprawkom możesz **improve OCR accuracy** dramatycznie, a Aspose sprawia, że jest to bezbolesne. + +W tym samouczku przeprowadzimy rzeczywisty przykład, który pokaże, jak **run OCR on JPEG** obrazy, zastosować własną ścieżkę przetwarzania obrazu i w końcu **extract text using Aspose**. Na końcu będziesz mieć gotowy do wklejenia fragment C# , który możesz wrzucić do dowolnego projektu .NET. + +## Co się nauczysz + +- Dlaczego przetwarzanie wstępne ma znaczenie i które filtry dają największy zysk. +- Jak skonfigurować `ImageProcessingOptions` Aspose.OCR do prostowania, odszumiania, binaryzacji i zwiększania kontrastu. +- Dokładny kod potrzebny do **run OCR on JPEG** plików i uzyskania czystego tekstu. +- Wskazówki i pułapki, które utrzymują Twoją linię OCR w produkcji. + +Nie wymagana jest wcześniejsza znajomość Aspose; wystarczy podstawowa znajomość C# oraz Visual Studio (lub ulubione IDE). Zaczynajmy. + +![Przykład wstępnego przetwarzania obrazu dla OCR](preprocess-ocr.png "Wstępne przetwarzanie obrazu dla OCR") + +## Krok 1: Skonfiguruj silnik Aspose.OCR – Preprocess Image for OCR + +Na początek potrzebujemy instancji `OcrEngine` i musimy określić, jakiego języka oczekujemy. W większości przypadków domyślnym jest angielski, ale możesz go zamienić na francuski, niemiecki itp., zmieniając enum `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Dlaczego to ważne:** Silnik jest sercem operacji; bez niego nie możesz zastosować żadnych filtrów obrazu, które faktycznie **preprocess image for OCR**. Pomyśl o nim jak o kuchni, w której mieszane są wszystkie składniki. + +## Krok 2: Zbuduj własną ścieżkę przetwarzania obrazu – Improve OCR Accuracy + +Teraz przychodzi najciekawsza część. Aspose pozwala łączyć kilka filtrów razem. Poniżej włączamy cztery z najbardziej efektywnych: + +1. **Deskew** – prostuje przechylone dokumenty (domyślnie maksymalnie 5°). +2. **Denoise** – wygładza ziarniste tła. +3. **Binarize** – konwertuje obraz do czarno‑białego przy użyciu progu. +4. **ContrastBoost** – sprawia, że słabe znaki stają się wyraźne. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** Jeśli Twoje obrazy źródłowe są już ostre, możesz zmniejszyć `Strength` lub wyłączyć filtr całkowicie. Nadmierne przetwarzanie może czasem wymazać słabe znaki, więc eksperymentuj na rzeczywistych próbkach. + +## Krok 3: Załaduj JPEG (lub dowolny obraz) i uruchom OCR – Run OCR on JPEG + +Aspose działa z każdym formatem obrazu, który .NET potrafi odczytać — JPEG, PNG, BMP, jakikolwiek. Oto jak wczytać plik JPEG do silnika i rozpocząć proces rozpoznawania. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Dlaczego JPEG?** Kompresja JPEG często wprowadza artefakty, które mylą OCR. Nasza ścieżka przetwarzania, szczególnie kroki odszumiania i binaryzacji, łagodzi te problemy, pozwalając **run OCR on JPEG** z pewnością. + +## Krok 4: Wyświetl rozpoznany tekst – Extract Text Using Aspose + +Na koniec po prostu zapisujemy tekst do konsoli, pliku lub dowolnej usługi downstream. Do celów demonstracyjnych konsola wystarczy. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Po uruchomieniu programu powinieneś zobaczyć coś takiego: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Jeśli wynik wygląda na zniekształcony, wróć do **Krok 2** i dostosuj ustawienia filtrów. Małe korekty często przynoszą duże zyski w **improve OCR accuracy**. + +## Typowe przypadki brzegowe i jak sobie z nimi radzić + +| Situation | Suggested Adjustment | +|-----------|----------------------| +| **Bardzo ciemne obrazy** | Increase `ContrastBoost.Level` to 1.5 or higher. | +| **Przechylenie > 5°** | Raise `DeskewOptions.MaxAngle` (e.g., 10.0) or pre‑rotate the image manually. | +| **Kolorowy tekst na kolorowym tle** | Use `BinarizeOptions` with a custom threshold or switch to `AdaptiveBinarizeOptions`. | +| **Duże pliki ( > 5 MB )** | Load the image into a `MemoryStream` first to avoid file‑lock issues. | + +Te poprawki utrzymują Twoją linię przetwarzania elastyczną i przyszłościową, szczególnie gdy musisz **extract text using Aspose** z różnych źródeł. + +## Pełny działający przykład – wszystkie kroki w jednym miejscu + +Poniżej znajduje się kompletny, gotowy do skopiowania i wklejenia program. Kompiluje się z .NET 6+ i wymaga jedynie pakietu NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Zapisz to jako `Program.cs`, dodaj pakiet Aspose.OCR (`dotnet add package Aspose.OCR`) i uruchom `dotnet run`. Zobaczysz wyczyszczony tekst wypisany w konsoli. + +## Podsumowanie – Dlaczego to podejście działa + +- **Preprocess image for OCR**: Ścieżka usuwa najczęstsze źródła błędów (przechylenie, szum, niski kontrast). +- **Improve OCR accuracy**: Każdy filtr jest dostrojony, aby zwiększyć stosunek sygnału do szumu widziany przez silnik. +- **Run OCR on JPEG**: Nawet skompresowane obrazy stają się czytelne po prostowaniu i binaryzacji. +- **Extract text using Aspose**: Metoda `Recognize` zwraca zwykły ciąg znaków, gotowy do dalszej logiki. + +Razem te kroki dają niezawodne, produkcyjne rozwiązanie OCR w zaledwie kilku linijkach. + +## Kolejne kroki i powiązane tematy + +- **Batch processing** – Przetwarzaj pętlą folder z obrazami i zapisz każdy wynik do pliku `.txt`. +- **Language packs** – Zamień `OcrLanguage.English` na `OcrLanguage.Spanish` lub dodaj własne słowniki. +- **PDF extraction** – Połącz Aspose.OCR z Aspose.PDF, aby wyciągnąć tekst bezpośrednio ze skanowanych PDF‑ów. +- **Performance tuning** – Uruchom silnik równolegle przy użyciu `Parallel.ForEach` przy dużych obciążeniach. + +Śmiało eksperymentuj z wartościami filtrów, wypróbuj różne formaty obrazów lub łańcuchuj dodatkowe filtry Aspose, takie jak `SharpnessOptions`. Nie ma granic, gdy opanujesz podstawy. + +--- + +*Sz​częśliwego kodowania! Jeśli napotkasz problemy, zostaw komentarz poniżej, a pomożemy rozwiązać je razem.* + +## Powiązane samouczki + +- [Wstępne przetwarzanie obrazu OCR przy użyciu filtrów Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Wyodrębnianie tekstu z obrazu – optymalizacja OCR przy użyciu Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [Wyodrębnianie tekstu 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/text-recognition/_index.md b/ocr/polish/net/text-recognition/_index.md index 40c85d634..6e1dcba04 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,24 @@ 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. +### [Rozpoznaj tekst z obrazu przy użyciu Aspose OCR – Kompletny przewodnik C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Kompletny przewodnik C# pokazujący, jak używać Aspose OCR do rozpoznawania tekstu z obrazów w aplikacjach .NET. +### [Jak używać OCR w C# – Rozpoznawanie chińskiego tekstu z JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Dowiedz się, jak przy użyciu Aspose.OCR w C# rozpoznać chiński tekst na obrazach JPG, krok po kroku. +### [OCR rosyjskiego tekstu w C# – Kompletny przewodnik z użyciem Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Poznaj, jak w C# przy użyciu Aspose OCR rozpoznać rosyjski tekst na obrazach, krok po kroku, z praktycznymi przykładami i wskazówkami. +### [Wyodrębnij tekst z obrazu w C# – Kompletny przewodnik Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Kompletny przewodnik w C#, pokazujący, jak używać Aspose OCR do wyodrębniania tekstu z obrazów w aplikacjach .NET. +### [Wyodrębnij tekst z obrazu w ASP.NET Core Minimal API – Kompletny przewodnik](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Kompletny przewodnik pokazujący, jak wyodrębnić tekst z obrazu w ASP.NET Core Minimal API przy użyciu Aspose OCR. +### [Samouczek C# OCR: wyodrębnianie tekstu z paragonów PNG przy użyciu Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Dowiedz się, jak w C# przy użyciu Aspose OCR wyodrębnić tekst z paragonów w formacie PNG, krok po kroku. +### [Konwertuj TIFF na tekst w C# – Kompletny przewodnik wsadowego OCR](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Dowiedz się, jak w C# przetworzyć wiele plików TIFF na tekst przy użyciu Aspose OCR w trybie wsadowym. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/polish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..8cb87f4bd --- /dev/null +++ b/ocr/polish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,218 @@ +--- +category: general +date: 2026-05-25 +description: Samouczek OCR w C#, który pokazuje, jak wczytać plik obrazu w C# i rozpoznać + tekst PNG z paragonu przy użyciu Aspose OCR – przewodnik krok po kroku. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: pl +og_description: Samouczek OCR w C#, który krok po kroku pokazuje, jak wczytać plik + obrazu w C# i rozpoznać tekst PNG z paragonu przy użyciu Aspose OCR. +og_title: c# OCR tutorial – Wyodrębnij tekst z paragonów PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'Samouczek OCR w C#: wyodrębnianie tekstu z paragonów PNG przy użyciu Aspose' +url: /pl/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Wyodrębnianie tekstu z paragonów PNG przy użyciu Aspose + +Kiedykolwiek potrzebowałeś **c# OCR tutorial**, który naprawdę wykonuje zadanie bez niekończącego się Googlowania? Jesteś we właściwym miejscu. W tym przewodniku **load image file c#**, **recognize png text** i **read receipt OCR** wyniki, jednocześnie pokazując, jak **perform OCR image** przetwarzanie przy użyciu Aspose OCR. + +Zaczniemy od zainstalowania wymaganego pakietu NuGet, przejdziemy przez każdą linię kodu i zakończymy schludnym zrzutem JSON, który możesz bezpośrednio przekierować do swojego kolejnego potoku danych. Bez zbędnych dodatków, tylko praktyczne, gotowe do uruchomienia rozwiązanie. + +## Co się nauczysz + +- Jak skonfigurować Aspose OCR w projekcie .NET 6 (lub nowszym). +- Dokładne kroki do **load an image file c#** i przekazania go silnikowi. +- Jak **recognize png text** z obrazu paragonu i przechwycić wynik. +- Sposoby na **read receipt OCR** wyjście jako ładnie sformatowany JSON. +- Wskazówki dotyczące operacji **perform OCR image** na różnych typach plików oraz radzenia sobie z typowymi pułapkami. + +**Wymagania wstępne** +- Visual Studio 2022 (lub dowolne IDE, które lubisz). +- .NET 6 SDK lub nowszy. +- Obraz PNG paragonu pod ręką (nazwijmy go `receipt.png`). + +Jeśli masz to wszystko, zanurzmy się. + +![zrzut ekranu c# OCR tutorial](ocr-demo.png "wynik c# OCR tutorial pokazujący wyjście JSON") + +## c# OCR Tutorial – Konfiguracja silnika Aspose OCR + +Na początek potrzebujemy biblioteki Aspose OCR. Otwórz terminal w folderze rozwiązania i uruchom: + +```bash +dotnet add package Aspose.OCR +``` + +To pojedyncze polecenie pobiera wszystko, co jest potrzebne, w tym natywne binaria do dekodowania obrazów. Po instalacji utwórz nowy projekt konsolowy lub dodaj kod do istniejącego. + +### Dlaczego Aspose? + +Aspose OCR obsługuje ponad 30 języków, działa offline i zwraca bogaty obiekt `OcrResult` — idealny do zadań **perform OCR image**, gdy potrzebujesz więcej niż zwykły tekst. + +## Load image file c# i przygotowanie paragonu + +Teraz, gdy biblioteka jest gotowa, **load image file c#**. Klasa `System.Drawing.Image` wykonuje ciężką pracę, ale możesz również użyć `SkiaSharp`, jeśli wolisz alternatywę wieloplatformową. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** Umieść `Image` w instrukcji `using` (jak pokazano), aby szybko zwolnić zasoby natywne — szczególnie ważne, gdy **perform OCR image** na wielu plikach w pętli. + +## Rozpoznawanie tekstu PNG przy użyciu Aspose + +Gdy obraz jest w pamięci, silnik może teraz **recognize png text**. Aspose zwraca `OcrResult`, który zawiera zarówno surowy ciąg znaków, jak i szczegółowe dane o każdym rozpoznanym słowie. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Dlaczego wywołać `RecognizeWithResult` zamiast prostszego `Recognize`? To pierwsze daje dostęp do wskaźników pewności, prostokątów ograniczających i podziałów wierszy — przydatne, jeśli później potrzebujesz **read receipt OCR** do wyodrębniania pozycji wierszy. + +## Odczyt wyniku OCR paragonu jako JSON + +Większość systemów downstream uwielbia JSON, więc zserializujmy `OcrResult`. Serializator `System.Text.Json` radzi sobie z złożonymi obiektami, a my włączymy wcięcia dla czytelności. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Wynikowy JSON wygląda mniej więcej tak (skrócony dla zwięzłości): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Teraz możesz przekierować `jsonResult` do bazy danych, kolejki wiadomości lub po prostu zalogować go w celach debugowania. + +## Wykonanie przetwarzania obrazu OCR i wyświetlenie wyniku + +Na koniec wypisz JSON w konsoli. W rzeczywistej aplikacji prawdopodobnie zapisałbyś go do pliku lub wysłał przez HTTP, ale konsola ułatwia weryfikację, że wszystko działa. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Uruchom program (`dotnet run`) i powinieneś zobaczyć ładnie sformatowany JSON. Jeśli obraz paragonu jest wyraźny, tekst będzie idealny; w przeciwnym razie rozważ zwiększenie rozdzielczości obrazu lub zastosowanie filtru wstępnego przetwarzania (np. odcienie szarości, zwiększenie kontrastu) przed przekazaniem go do silnika. + +### Obsługa typowych przypadków brzegowych + +| Sytuacja | Co zrobić | +|-----------|------------| +| **Obraz jest rozmyty** | Wstępnie przetwórz za pomocą `System.Drawing`, aby wyostrzyć lub zwiększyć DPI. | +| **Paragon zawiera wiele języków** | Set `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Przetwarzanie dużych partii** | Użyj jednej instancji `OcrEngine`; zmieniaj tylko `Image` w każdej iteracji. | +| **Obciążenie pamięci** | Niezwłocznie zwalniaj obiekty `Image` i rozważ `await Task.Run` dla asynchronicznych potoków. | + +## Podsumowanie + +Gratulacje — właśnie ukończyłeś **c# OCR tutorial**, który wczytuje obraz, **recognizes png text** i **reads receipt OCR** jako czysty JSON. Podstawowe kroki (konfiguracja silnika, wczytywanie obrazu, wykonanie OCR, serializacja i wyświetlanie) stanowią solidną bazę, którą możesz rozszerzyć na faktury, paszporty lub inne zeskanowane dokumenty. + +### Co dalej? + +- Eksperymentuj z **load image file c#** przy użyciu `SkiaSharp` dla prawdziwego wsparcia wieloplatformowego. +- Zagłęb się w `OcrResult.Words`, aby wyodrębnić pozycje, ceny i daty — idealne dla aplikacji śledzących wydatki. +- Połącz ten tutorial z Azure Functions lub AWS Lambda, aby zbudować bezserwerowe API do przetwarzania paragonów. + +Śmiało modyfikuj kod, dodawaj więcej obrazów lub nawet przełącz się na inny pakiet językowy. Świat OCR pełen jest niespodzianek, a teraz masz narzędzia, by je odkrywać. + +Szczęśliwego kodowania i niech Twoje paragony zawsze będą czytelne! + +## Powiązane tutoriale + +- [Wyodrębnianie tekstu z obrazu 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 – optymalizacja OCR przy użyciu Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [Jak używać OCR – rozpoznawanie obrazu bez wykrywania obszaru tekstowego](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/polish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..23b3b34ae --- /dev/null +++ b/ocr/polish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-05-25 +description: Konwertuj pliki TIFF na tekst przy użyciu Aspose.OCR w C#. Dowiedz się, + jak wykonywać wsadową konwersję obrazów na tekst i efektywnie wyodrębniać tekst + z plików TIFF. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: pl +og_description: Konwertuj pliki TIFF na tekst za pomocą Aspose.OCR. Ten przewodnik + pokazuje konwersję wsadową obrazów na tekst oraz jak wyodrębnić tekst z plików TIFF + w kilku linijkach C#. +og_title: Konwertuj TIFF na tekst w C# – Kompletny przewodnik po wsadowym OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Konwertuj TIFF na tekst w C# – Kompletny przewodnik po OCR wsadowym +url: /pl/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konwersja TIFF na tekst w C# – Kompletny przewodnik po batch OCR + +Kiedykolwiek potrzebowałeś **konwertować TIFF na tekst**, ale nie wiedziałeś od czego zacząć? Nie jesteś sam — wielu programistów napotyka problemy przy batch OCR w pracy ze zeskanowanymi dokumentami. W tym tutorialu przeprowadzimy praktyczne rozwiązanie, które **wyodrębnia tekst z plików TIFF** przy użyciu Aspose.OCR, a przy okazji zrobimy to równolegle, aby duże foldery zakończyły się w kilka sekund. + +Omówimy także najlepsze praktyki **batch image to text conversion**, więc na końcu będziesz mieć gotowy fragment kodu, który zamienia cały katalog zeskanowanych obrazów w schludne pliki *.txt* — idealne do indeksowania, wyszukiwania lub dalszej analizy. + +## Co będzie potrzebne + +- **.NET 6.0** lub nowszy (kod kompiluje się także na .NET Framework) +- Pakiet NuGet **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Folder zawierający jeden lub więcej plików *.tif* (klasyczny format skanów TIFF) +- Ulubione IDE (Visual Studio, VS Code, Rider — cokolwiek lubisz) + +To wszystko. Żadnych zewnętrznych usług, żadnych kluczy API, tylko czysty C# i Aspose. + +![Zrzut ekranu pliku TIFF przetwarzanego i wynikowego pliku tekstowego](/images/ocr-result.png "Wynik OCR pokazujący konwersję TIFF na tekst") + +*(Alt text: Zrzut ekranu pokazujący konwersję TIFF na tekst na ekranie)* + +## Krok 1: Konfiguracja silnika OCR – Konwersja TIFF na tekst + +Na początek potrzebujemy instancji `OcrEngine`, która wie, że ma czytać znaki angielskie. Silnik jest sercem konwersji; prawidłowa konfiguracja zapewnia niezawodne wyniki. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Dlaczego to ważne:* +Aspose.OCR obsługuje dziesiątki języków. Jeśli masz do czynienia z wielojęzycznymi skanami, po prostu zamień `OcrLanguage.English` na odpowiednią wartość wyliczeniową. Brak określenia języka zmusza silnik do trybu automatycznego wykrywania, co może być wolniejsze i mniej dokładne. + +## Krok 2: Zebranie wszystkich plików TIFF – Efektywne wyodrębnianie tekstu z TIFF + +Następnie pobieramy każdy plik *.tif* z podanego folderu. Użycie `Directory.GetFiles` daje nam czystą tablicę, którą możemy przekazać do przetwarzania wsadowego. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Wskazówka:* Flaga `SearchOption.AllDirectories` może być użyta, jeśli skany są zagnieżdżone w podfolderach. Pamiętaj jednak, że głębsza rekurencja może zwiększyć zużycie pamięci podczas etapu wsadowego. + +## Krok 3: Równoległe OCR – Batch image to text conversion + +Teraz najciekawsza część. Aspose.OCR udostępnia statyczny pomocnik `BatchOcr.RecognizeAll`, który przyjmuje tablicę ścieżek plików, silnik oraz wskazówkę `parallelism`. Uruchomimy cztery wątki, co na nowoczesnym czterordzeniowym laptopie daje prawie liniowy przyrost wydajności. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Dlaczego równoległość?* +Przetwarzanie partii wysokiej rozdzielczości TIFF może być intensywne pod względem CPU. Rozdzielając pracę na wiele wątków, wykorzystujemy wszystkie rdzenie, co dramatycznie skraca całkowity czas wykonania. Jeśli uruchamiasz to na serwerze z większą liczbą rdzeni, zwiększ wartość `parallelism` odpowiednio. + +## Krok 4: Zapis wyniku – Konwersja zeskanowanych obrazów na pliki TXT + +Na koniec przechodzimy przez słownik i zapisujemy każdy fragment tekstu do pliku *.txt*, który zachowuje pierwotną nazwę bazową. To właśnie moment, w którym **convert scanned images txt** staje się rzeczywistością. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Co robi kod, w prostych słowach + +1. **Utworzy** silnik OCR ustawiony na język angielski. +2. **Zbiera** wszystkie pliki TIFF z docelowego folderu. +3. **Uruchamia** `BatchOcr.RecognizeAll` z czterema wątkami, zamieniając każdy obraz na ciąg znaków. +4. **Iteruje** po wynikach, zamienia rozszerzenie `.tif` na `.txt` i zapisuje tekst na dysku. + +To cały **convert TIFF to text** workflow w mniej niż 50 linijkach kodu. + +## Obsługa przypadków brzegowych – Gdy coś idzie nie tak + +- **Brakujące lub uszkodzone pliki TIFF** – `BatchOcr` rzuci `OcrException`. Owiń wywołanie w `try / catch`, jeśli potrzebujesz łagodnego degradacji. +- **Dokumenty nieangielskie** – zmień `OcrLanguage.English` na `OcrLanguage.Spanish`, `OcrLanguage.French` itd., lub użyj `OcrLanguage.AutoDetect`. +- **Bardzo duże obrazy** – rozważ obniżenie DPI przed OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`), aby zaoszczędzić pamięć, choć możesz stracić nieco dokładności. +- **Kodowanie wyjścia** – jeśli potrzebujesz konkretnej strony kodowej (np. Windows‑1252), przekaż ją do `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Profesjonalne wskazówki dla solidnych batch konwersji + +- **Loguj niepowodzenia**: utwórz `List failedFiles` i dodawaj do niej każdy plik, który zgłosi wyjątek; po pętli zapisz listę do logu. +- **Wykorzystuj ponownie silnik**: ta sama instancja `OcrEngine` może być używana dla wielu plików; nie twórz jej w pętli. +- **Waliduj wynik**: szybkie `if (string.IsNullOrWhiteSpace(extractedText))` może wykryć skany, które były puste lub nieczytelne. +- **Połącz z PDF**: jeśli źródłem jest wielostronicowy PDF, najpierw skonwertuj każdą stronę na TIFF (Aspose.PDF to umożliwia), a potem uruchom tę batch konwersję. + +## Kolejne kroki – Wyjście poza prostą konwersję + +Teraz, gdy możesz **extract text from TIFF** w trybie wsadowym, możesz: + +- Przekazać pliki *.txt* do indeksu wyszukiwania (Elasticsearch, Azure Cognitive Search). +- Uruchomić wykrywanie języka na każdym wyniku, aby kierować dokumenty do odpowiednich potoków. +- Generować przeszukiwalne PDF‑y, nakładając tekst OCR z powrotem na oryginalne obrazy (znowu Aspose.PDF). + +Wszystkie te scenariusze opierają się na tej samej podstawie: **batch image to text conversion** jest budulcem większych systemów przetwarzania dokumentów. + +--- + +### Podsumowanie + +Właśnie nauczyłeś się **convert TIFF to text** przy użyciu Aspose.OCR, przetworzyć cały folder równolegle i zapisać każdy wynik jako czysty plik *.txt*. Rozwiązanie jest lekkie, w pełni konfigurowalne i gotowe do produkcji — niezależnie od tego, czy digitalizujesz stare faktury, archiwizujesz zeskanowane umowy, czy zasilasz silnik wyszukiwania tekstowego. + +Wypróbuj je, dostosuj poziom równoległości i zacznij wprowadzać nowo powstałe pliki tekstowe do dowolnego workflowu. Powodzenia w OCR‑owaniu! + +--- + + +## Powiązane tutoriale + +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/polish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/polish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..51a0ae348 --- /dev/null +++ b/ocr/polish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Dowiedz się, jak wyodrębnić tekst z obrazu przy użyciu minimalnego API + ASP.NET Core. Prześlij obraz metodą POST, odczytaj dane multipart/form-data i wykonaj + OCR na obrazie. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: pl +og_description: Wyodrębnij tekst z obrazu za pomocą minimalnego API ASP.NET Core. + Ten przewodnik pokazuje, jak przesłać obraz metodą POST, odczytać dane multipart/form-data + i wykonać OCR na obrazie. +og_title: Wyodrębnij tekst z obrazu w ASP.NET Core – krok po kroku +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Wyodrębnianie tekstu z obrazu w ASP.NET Core Minimal API – Kompletny przewodnik +url: /pl/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wyodrębnianie tekstu z obrazu w ASP.NET Core Minimal API – Kompletny przewodnik + +Zastanawiałeś się kiedyś, jak **wyodrębnić tekst z obrazu** bez zmagania się z ciężkimi frameworkami? Nie jesteś sam. Wielu programistów potrzebuje szybkiego sposobu, aby pozwolić użytkownikom wrzucić zdjęcie i otrzymać surowe znaki, niezależnie od tego, czy chodzi o skanowanie paragonów, digitalizację odręcznych notatek, czy zasilanie indeksu wyszukiwania. + +W tym poradniku uruchomimy małe ASP.NET Core Minimal API, które **przesyła obraz za pomocą POST**, analizuje ładunek *multipart/form‑data* i następnie **wykonuje OCR na obrazie** przy użyciu singletonu `OcrEngine`. Po zakończeniu będziesz mieć w pełni działającą aplikację, którą możesz wkleić do dowolnego projektu .NET 8 i od razu zacząć wyodrębniać tekst z obrazu. + +## Co zbudujesz + +- Minimalna aplikacja webowa nasłuchująca na `/ocr`. +- Endpoint, który akceptuje plik obrazu wysłany w żądaniu POST `multipart/form-data`. +- Logika, która odczytuje przesłany plik, przekazuje go do silnika OCR i zwraca wyniki w postaci czystego tekstu. +- Opcjonalny fragment przyspieszenia GPU (zakomentowany) dla posiadaczy kompatybilnej karty. + +**Wymagania wstępne** +- .NET 8 SDK (lub nowszy). +- Podstawowa znajomość C# i wiersza poleceń. +- Biblioteka OCR udostępniająca klasę `OcrEngine` (przykład zakłada hipotetyczny pakiet NuGet). + +Jeśli masz to wszystko, zanurzmy się. + +## Krok 1: Konfiguracja projektu i dodanie pakietu OCR + +Najpierw utwórz nowy projekt webowy i pobierz bibliotekę OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Porada:** Utrzymuj zależności aktualne. Nowsze wersje często przynoszą zyski wydajności, szczególnie przy wnioskowaniu przyspieszonym przez GPU. + +## Krok 2: Zarejestruj singletonowy silnik OCR (główna usługa) + +Chcemy jedną instancję `OcrEngine` dla całej aplikacji — nie ma potrzeby uruchamiania nowego silnika przy każdym żądaniu. Zarejestruj ją w kontenerze usług buildera. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Dlaczego singleton?** +Tworzenie silnika OCR może być kosztowne — wyobraź sobie ładowanie wag sieci neuronowej do pamięci. Ponowne użycie tej samej instancji pozwala zaoszczędzić zarówno cykle CPU, jak i RAM, co przekłada się na szybsze czasy odpowiedzi przy każdym wywołaniu `/ocr`. + +## Krok 3: Zbuduj aplikację + +Teraz materializujemy obiekt `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Ta linijka wygląda prawie magicznie, ale pod maską konfiguruje routing, middleware i kontener DI, który właśnie skonfigurowaliśmy. + +## Krok 4: Zdefiniuj endpoint POST – „Prześlij obraz za pomocą POST” + +Oto serce poradnika: endpoint, który **przesyła obraz za pomocą POST**, odczytuje ładunek multipart i przekazuje dane do silnika OCR. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Rozbicie logiki + +| Krok | Co się dzieje | Dlaczego to ważne | +|------|--------------|-------------------| +| **ReadFormAsync** | Parsuje przychodzące żądanie *multipart/form-data*. | Bez tego nie możesz uzyskać dostępu do przesłanych plików. | +| **form.Files["image"]** | Pobiera plik, którego nazwa pola formularza to `image`. | Gwarantuje przewidywalny kontrakt dla wywołujących. | +| **Content‑type check** | Sprawdza, czy plik jest obrazem (np. `image/png`). | Zapobiega zacinaniu się silnika OCR przy danych niebędących obrazem. | +| **Image.FromStream** | Konwertuje surowy strumień na `System.Drawing.Image`. | Biblioteka OCR oczekuje obiektu `Image`, a nie surowej tablicy bajtów. | +| **ocr.Recognize(img)** | Wywołuje silnik OCR, aby **rozpoznać tekst z obrazu**. | To jest kluczowy krok **wykonywania OCR na obrazie**. | +| **Results.Text** | Zwraca odpowiedź w postaci czystego tekstu. | Prosty, łatwy do przetworzenia format dla usług downstream. | + +## Krok 5: Uruchom API + +Na koniec uruchom serwer webowy. + +```csharp +app.Run(); +``` + +Gdy uruchomisz `dotnet run`, API będzie nasłuchiwać na `http://localhost:5000` (lub wybranym porcie). Możesz przetestować je przy pomocy `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Oczekiwany wynik:** Konsola wydrukuje rozpoznane znaki, np.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Jeśli obraz jest rozmyty lub język nie jest obsługiwany, silnik OCR zwróci pusty ciąg lub komunikat o błędzie — obsłuż te przypadki w kodzie produkcyjnym. + +## Przypadki brzegowe i najlepsze praktyki + +### 1. Duże pliki + +Domyślny limit rozmiaru ciała żądania to 30 MB. Dla większych skanów może być konieczna zmiana: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynchroniczny OCR + +Niektóre biblioteki OCR udostępniają asynchroniczne metody (`RecognizeAsync`). Jeśli Twoja tak, zamień `ocr.Recognize(img)` na `await ocr.RecognizeAsync(img)` i oznacz wyrażenie lambda jako `async`. + +### 3. Rozważania bezpieczeństwa + +- **Waliduj rozmiar pliku** przed załadowaniem go do pamięci. +- **Sanitizuj nazwę pliku** jeśli kiedykolwiek zapisujesz go na dysk. +- **Ogranicz liczbę żądań** (rate‑limit) endpointu, aby uniknąć ataków typu denial‑of‑service. + +### 4. Przyspieszenie GPU + +Jeśli odkomentujesz linię `engine.GpuDevice = new GpuDevice(0);` i Twój sprzęt obsługuje CUDA lub DirectML, zauważysz wyraźny przyrost wydajności, szczególnie przy obrazach wysokiej rozdzielczości. + +## Pełny działający przykład + +Poniżej znajduje się kompletny plik `Program.cs`, który możesz skopiować i wkleić do nowego projektu Minimal API. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Zapisz, uruchom `dotnet run` i będziesz gotowy do **wyodrębniania tekstu z obrazu** na żądanie. + +## Zakończenie + +Przeszliśmy przez **kompletną, end‑to‑end rozwiązanie** wyodrębniania tekstu z obrazu przy użyciu ASP.NET Core Minimal API. Zaczynając od szkieletu projektu, **zarejestrowaliśmy singletonowy silnik OCR**, zbudowaliśmy endpoint, który **przesyła obraz za pomocą POST**, **odczytuje dane multipart**, i w końcu **wykonuje OCR na obrazie**, aby zwrócić czysty tekst. + +Od tego momentu możesz: + +- Dodać opakowania JSON dla bogatszych odpowiedzi. +- Podłączyć bazę danych do przechowywania wyodrębnionego tekstu. +- Rozszerzyć wsparcie na wiele języków (`OcrLanguage.Spanish` itd.). + +Wzorzec skaluje się dobrze — wystarczy wkleić ten sam endpoint do większego mikroserwisu lub udostępnić go za pośrednictwem bramki API. + +Masz pytania dotyczące obsługi PDF‑ów, przetwarzania wsadowego lub strojenia GPU? zostaw komentarz i szczęśliwego kodowania! + +## Powiązane tutoriale + +- [Wyodrębnianie tekstu z obrazu przy użyciu Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Wyodrębnianie tekstu z obrazu – optymalizacja OCR z Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [Wyodrębnianie tekstu 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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/polish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..5ec8ac8ca --- /dev/null +++ b/ocr/polish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,292 @@ +--- +category: general +date: 2026-05-25 +description: Wyodrębnij tekst z obrazu przy użyciu C# i Aspose OCR. Dowiedz się, jak + konwertować jpg na tekst, wczytywać obraz do OCR i uzyskać szybkie, niezawodne wyniki. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: pl +og_description: Wyodrębnij tekst z obrazu przy użyciu C#. Ten przewodnik pokazuje, + jak konwertować jpg na tekst, wczytywać obraz do OCR i obsługiwać treści wielojęzyczne. +og_title: Wyodrębnianie tekstu z obrazu w C# – Poradnik Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Wyodrębnianie tekstu z obrazu w C# – Kompletny przewodnik po Aspose OCR +url: /pl/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Wyodrębnianie tekstu z obrazu w C# – Kompletny przewodnik Aspose OCR + +Zastanawiałeś się kiedyś, jak **extract text from image** przy użyciu czystego kodu C#? Nie jesteś jedyny. Czy cyfryzujesz paragony, skanujesz tablice, czy po prostu interesujesz się OCR, umiejętność wyciągania znaków z obrazu jest przydatna. W tym tutorialu przeprowadzimy pełny, uruchamialny przykład, który dokładnie pokazuje, jak **extract text from image** z Aspose.OCR, a także omówimy, jak **convert jpg to text**, **load image for OCR** oraz odpowiemy na klasyczne pytanie „**how to ocr image**” raz na zawsze. + +Po zakończeniu tego przewodnika będziesz mieć samodzielną aplikację konsolową, która odczytuje plik JPEG, rozpoznaje język ukraiński (lub dowolny inny obsługiwany język) i wypisuje wynik w konsoli. Bez niejasnych odniesień, bez brakujących elementów — po prostu kompletny rozwiązanie, które możesz skopiować i uruchomić. + +--- + +## Co się nauczysz + +* Jak zainstalować pakiet NuGet Aspose.OCR. +* Dokładny kod potrzebny do **load image for OCR** w C#. +* Jak ustawić język i faktycznie **extract text from image**. +* Sztuczki dla **convert jpg to text** w sposób efektywny. +* Typowe pułapki i jak ich unikać. + +Jeśli już masz skonfigurowane środowisko programistyczne .NET, możesz od razu zanurzyć się w kodzie. W przeciwnym razie sekcja wymagań poniżej przygotuje Cię do startu. + +## Wymagania + +| Wymaganie | Dlaczego jest ważne | +|-----------|---------------------| +| .NET 6.0 SDK (lub nowszy) | Zapewnia środowisko uruchomieniowe dla aplikacji konsolowej. | +| Visual Studio 2022 lub VS Code | Ułatwia edycję i debugowanie. | +| Połączenie internetowe (pierwsze uruchomienie) | NuGet musi pobrać Aspose.OCR. | +| Obraz JPEG, który chcesz przetworzyć (np. `ukrainian_sign.jpg`) | Plik źródłowy dla silnika OCR. | + +> **Pro tip:** Jeśli pracujesz na Linuxie lub macOS, ten sam kod działa z .NET CLI (`dotnet new console`), więc możesz pominąć ciężkie IDE. + +## Krok 1 – Instalacja Aspose.OCR przez NuGet + +Otwórz terminal (lub Package Manager Console) i uruchom: + +```bash +dotnet add package Aspose.OCR +``` + +To jedyne polecenie pobiera najnowsze binaria Aspose.OCR oraz wszystkie zależności tranzytywne. Nie musisz ręcznie zarządzać plikami DLL. + +## Krok 2 – Utworzenie silnika OCR (Serce ekstrakcji) + +Teraz, gdy biblioteka jest już dostępna, możemy stworzyć instancję `OcrEngine`. Ten obiekt jest odpowiedzialny za **extracting text from image**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Dlaczego to ważne:** Silnik kapsułkuje algorytmy OCR, modele językowe i opcje konfiguracji. Utworzenie go raz i ponowne użycie przy wielu obrazach jest zarówno oszczędne pod względem pamięci, jak i szybkie. + +## Krok 3 – Załadowanie obrazu do OCR (i ustawienie języka) + +Kolejnym krokiem jest poinformowanie silnika, który obraz ma odczytać. W tym miejscu wkracza fraza **load image for OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Edge case:** Jeśli plik nie istnieje, `Image.FromFile` rzuca `FileNotFoundException`. W kodzie produkcyjnym warto otoczyć wywołanie blokiem try‑catch. + +## Krok 4 – Wykonanie OCR i wyodrębnienie tekstu + +Po załadowaniu obrazu silnik może teraz **extract text from image**. Metoda `Recognize` wykonuje ciężką pracę. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Jeśli wszystko pójdzie dobrze, zmienna `recognizedText` będzie zawierała czysty tekst reprezentujący wszystko, co silnik OCR był w stanie odczytać. + +## Krok 5 – Konwersja JPG do tekstu (łączenie wszystkiego) + +Kod, który dotąd zbudowaliśmy, już **convert jpg to text**, ale opakujmy go w elegancką metodę, którą można wywoływać wielokrotnie. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Teraz możesz po prostu zrobić: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Oczekiwany wynik** (skrócony dla przejrzystości): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Jeśli obraz zawiera tekst po angielsku, zmień `OcrLanguage.English` i zobaczysz odpowiedni wynik. + +## Krok 6 – Obsługa typowych pytań „How to OCR Image” + +### 6.1 Czy mogę OCR‑ować PNG lub BMP? + +Oczywiście. Metoda `Image.FromFile` obsługuje wszystkie formaty rozpoznawane przez System.Drawing, więc wystarczy podać ścieżkę do pliku `.png` lub `.bmp`, a reszta kodu pozostaje niezmieniona. + +### 6.2 Co jeśli obraz ma niską rozdzielczość? + +Dokładność OCR drastycznie spada poniżej 300 dpi. Szybkim rozwiązaniem jest zwiększenie rozdzielczości obrazu przy użyciu `Graphics` przed przekazaniem go do silnika: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Czy potrzebna jest licencja na Aspose.OCR? + +Aspose oferuje darmową wersję próbną z watermarkiem. W zastosowaniach produkcyjnych zakup licencję i dodaj: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +## Pełny działający przykład + +Poniżej znajduje się kompletny, gotowy do uruchomienia program konsolowy, który demonstruje **how to OCR image**, **load image for OCR** oraz **convert jpg to text** w jednym schludnym pakiecie. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Jak to uruchomić** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Powinieneś zobaczyć wyodrębniony tekst wypisany w konsoli, co potwierdzi, że udało Ci się **extract text from image** przy użyciu C#. + +## Typowe problemy i wskazówki + +| Problem | Dlaczego się pojawia | Rozwiązanie | +|---------|----------------------|-------------| +| Pusty wynik | Obraz zbyt ciemny lub o niskim kontraście. | Przetwórz wstępnie za pomocą `Bitmap`, aby zwiększyć jasność. | +| Nieprawidłowy język | Właściwość `Language` pozostawiona domyślnie na angielski. | Jawnie ustaw `ocrEngine.Language = OcrLanguage.Ukrainian;` (lub inny docelowy). | +| Błąd pamięci | Bardzo duże obrazy ładowane bez zwalniania. | Otocz `Image.FromFile` blokiem `using` (jak pokazano). | +| Watermark licencyjny | Uruchamianie wersji próbnej bez licencji. | Dodaj zakupioną licencję wcześnie w metodzie `Main`. | + +## Zakończenie + +Właśnie omówiliśmy wszystko, co potrzebne, aby **extract text from image** w C# — od instalacji Aspose.OCR, **load image for OCR**, po **convert jpg to text** i obsługę scenariuszy wielojęzycznych. Pełny przykładowy program łączy wszystkie elementy, dając solidną bazę dla każdego projektu związanego z OCR. + +Następnie możesz zbadać: + +* **How to OCR image** strumienie zamiast plików (użyj `MemoryStream`). +* Dodawanie **c# image to text** post‑processingu, takiego jak sprawdzanie pisowni. +* Integrację kroku OCR w większym potoku (np. zapisywanie wyników w bazie danych). + +Śmiało eksperymentuj z różnymi językami, formatami obrazów i technikami wstępnej obróbki. OCR to zarówno sztuka, jak i nauka, a im więcej się bawisz, tym lepsze wyniki uzyskasz. + +Miłego kodowania i niech Twoje obrazy zawsze będą czytelne! + +## Powiązane tutoriale + +- [Wyodrębnianie tekstu z obrazu 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 – optymalizacja OCR z Aspose.OCR dla .NET](/ocr/english/net/ocr-optimization/) +- [Jak wyodrębnić tekst z obrazu przygotowując prostokąty w OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/polish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..033e02049 --- /dev/null +++ b/ocr/polish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: Jak używać OCR w C#, aby wyodrębnić tekst z plików graficznych. Dowiedz + się, jak rozpoznawać chińskie znaki z pliku JPG przy użyciu Aspose.OCR w kilku prostych + krokach. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: pl +og_description: Jak używać OCR w C#, aby wyodrębnić tekst z plików graficznych. Ten + przewodnik pokazuje, jak rozpoznawać chińskie znaki z pliku JPG przy użyciu Aspose.OCR. +og_title: Jak używać OCR w C# – Rozpoznawanie chińskiego tekstu z pliku JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Jak używać OCR w C# – Rozpoznawanie chińskiego tekstu z pliku JPG +url: /pl/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Jak używać OCR w C# – Rozpoznawanie chińskiego tekstu z JPG + +Zastanawiałeś się kiedyś **jak używać OCR**, aby wyciągnąć słowa z obrazka, który zrobiłeś telefonem? Nie jesteś sam. W wielu rzeczywistych projektach — pomyśl o skanerach paragonów, aplikacjach tłumaczeniowych lub automatycznym wprowadzaniu danych — będziesz musiał **wyodrębniać tekst z obrazu** szybko i niezawodnie. + +W tym samouczku przeprowadzimy Cię przez kompletny, gotowy do uruchomienia przykład, który **rozpoznaje tekst z plików JPG** i nawet radzi sobie z trudnym przypadkiem **rozpoznawania chińskich znaków** przy użyciu pakietu językowego **OCR Chinese Simplified**. Po zakończeniu będziesz mieć samodzielną aplikację konsolową, która wypisuje wykryty ciąg znaków w konsoli, bez dodatkowych ręcznych pobrań. + +> **Szybka uwaga:** Kod działa z Aspose.OCR ≥ 23.7, który automatycznie pobiera zasoby językowe przy pierwszym użyciu. Jeśli używasz starszej wersji, będziesz musiał dodać język ręcznie. + +## Wymagania wstępne + +Zanim zaczniemy, upewnij się, że masz: + +- .NET 6.0 SDK lub nowszy (przykład jest skierowany do .NET 6, ale .NET 5 również działa) +- Aktualną wersję Visual Studio 2022 lub VS Code z rozszerzeniem C# +- Połączenie internetowe do pierwszego pobrania języka +- Obraz JPG zawierający tekst w chińskim uproszczonym (nazwijmy go `chinese_sign.jpg`) + +To wszystko — bez ciężkich silników OCR, bez ręcznego zarządzania natywnymi DLL‑ami. Wystarczy kilka poleceń NuGet i kilka linii kodu. + +## Krok 1: Zainstaluj Aspose.OCR przez NuGet + +Najpierw potrzebujemy biblioteki OCR. Otwórz terminal w folderze projektu i uruchom: + +```bash +dotnet add package Aspose.OCR +``` + +Lub, jeśli wolisz interfejs Visual Studio, kliknij prawym przyciskiem **Dependencies → Manage NuGet Packages**, wyszukaj „Aspose.OCR” i kliknij **Install**. + +> **Pro tip:** Aktualizuj swoje pakiety na bieżąco. Nowe pakiety językowe i ulepszenia wydajności pojawiają się w każdym mniejszym wydaniu. + +## Krok 2: Utwórz nowy projekt konsolowy (jeśli jeszcze go nie masz) + +Jeśli zaczynasz od zera, utwórz nową aplikację konsolową: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Teraz masz plik `Program.cs` gotowy na kod OCR. + +## Krok 3: Napisz kod OCR – Rozpoznawanie chińskiego uproszczonego z JPG + +Otwórz `Program.cs` i zamień jego zawartość na poniższą. Każda linia jest opatrzona komentarzem, abyś widział *dlaczego* wykonujemy dany krok, a nie tylko *co* robimy. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Co się dzieje pod maską? + +- **`OcrEngine.Language`** informuje Aspose, którego słownika użyć. Wybierając `ChineseSimplified`, instruujemy silnik, aby szukał pakietu językowego chińskiego uproszczonego. +- **Pobranie przy pierwszym użyciu**: Gdy wywołasz `Recognize`, SDK łączy się z CDN‑em Aspose, pobiera plik językowy ≈6 MB, zapisuje go w pamięci podręcznej i dopiero wtedy przystępuje do OCR. Kolejne wywołania są natychmiastowe. +- **`Image.FromFile`** działa z każdym formatem rastrowym, który .NET potrafi zdekodować — JPG, PNG, BMP — więc możesz **wyodrębniać tekst z obrazu** z wielu typów plików, nie tylko JPG. + +## Krok 4: Uruchom aplikację i zweryfikuj wynik + +Zbuduj i uruchom: + +```bash +dotnet run +``` + +Powinieneś zobaczyć coś podobnego: + +``` +=== Recognized Text === +欢迎光临 +``` + +Jeśli konsola wyświetla nieczytelny ciąg znaków lub pusty wynik, sprawdź: + +1. Czy obraz faktycznie zawiera wyraźne, wysokokontrastowe chińskie znaki. +2. Czy ścieżka do pliku jest poprawna (brak zbędnych spacji lub brakujących rozszerzeń). +3. Czy Twój komputer może połączyć się z `https://download.aspose.com` w celu pobrania pakietu językowego. + +## Krok 5: Obsługa przypadków brzegowych i typowych pułapek + +### 5.1 Radzenie sobie z niskiej jakości obrazami + +Dokładność OCR spada, gdy źródłowy obraz jest rozmyty, zaszumiony lub ma słabe oświetlenie. Szybkim rozwiązaniem jest wstępne przetworzenie obrazu: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Uruchamianie w środowisku bez interfejsu graficznego + +Jeśli wdrażasz aplikację w kontenerze Linux bez GUI, upewnij się, że biblioteka `libgdiplus` (wymagana dla `System.Drawing`) jest zainstalowana: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Ręczne buforowanie pakietu językowego + +Możesz pobrać plik językowy raz i wskazać Aspose jego lokalizację za pomocą API `License`, co eliminuje jednorazowe wywołanie sieciowe. Jest to przydatne w scenariuszach offline. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Pełny działający przykład (Wszystko w jednym) + +Poniżej znajduje się *kompletny* program, który możesz skopiować i wkleić do `Program.cs`. Bez ukrytych fragmentów, bez zewnętrznych skryptów. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Oczekiwany wynik + +Jeśli JPG zawiera frazę „欢迎光临”, konsola wypisze: + +``` +=== Recognized Text === +欢迎光临 +``` + +Śmiało zamień obraz na dowolny inny znak chiński uproszczony, nazwę ulicy lub etykietę produktu — silnik zrobi, co w jego mocy. + +## Zakończenie + +Właśnie omówiliśmy **jak używać OCR** w C# do **wyodrębniania tekstu z obrazu**, szczególnie pod kątem **rozpoznawania chińskich znaków** w **JPG**. Korzystając z dynamicznego pobierania języka w Aspose.OCR, możesz utrzymać wdrożenie lekkie, a jednocześnie obsługiwać **OCR Chinese Simplified** od razu po instalacji. + +Co dalej? Wypróbuj następujące pomysły: + +- **Przetwarzanie wsadowe**: Przejdź po folderze z obrazami i zapisz każdy wynik do pliku CSV. +- **Połączenie z API tłumaczeń**: Przekaż rozpoznany ciąg znaków do Azure Translator, aby uzyskać aplikacje wielojęzyczne w czasie rzeczywistym. +- **Eksploracja innych języków**: Zamień `OcrLanguage.ChineseSimplified` na `Japanese` lub `Arabic` i zobacz, jak ten sam kod się zachowuje. + +Masz pytania dotyczące optymalizacji wydajności, licencjonowania lub integracji OCR w usłudze webowej? zostaw komentarz poniżej — powodzenia w kodowaniu! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + + +## Powiązane samouczki + +- [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/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/polish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/polish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..08a6ca3a9 --- /dev/null +++ b/ocr/polish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Dowiedz się, jak rozpoznawać rosyjski tekst w C# i wyodrębniać tekst + z obrazu za pomocą Aspose OCR. Krok po kroku kod, który szybko konwertuje obraz + na tekst w C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: pl +og_description: OCR rosyjskiego tekstu w C# stało się proste. Dowiedz się, jak wyodrębnić + tekst z obrazu, konwertować obraz na tekst w C# oraz wczytać obraz do OCR przy użyciu + Aspose OCR. +og_title: OCR rosyjskiego tekstu w C# – Kompletny przewodnik po Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR rosyjskiego tekstu w C# – Kompletny przewodnik z użyciem Aspose OCR +url: /pl/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR rosyjskiego tekstu w C# – Kompletny przewodnik z użyciem Aspose OCR + +Kiedykolwiek potrzebowałeś wykonać OCR rosyjskiego tekstu w C#, ale nie byłeś pewien, której biblioteki zaufać? Nie jesteś sam. Uzyskanie czystych, czytelnych znaków z obrazu cyrylicy może przypominać odszyfrowywanie tajnych wiadomości — szczególnie jeśli nie ustawiłeś odpowiedniego modelu językowego. + +W tym samouczku przeprowadzimy praktyczny przykład, który pokaże, jak **wyodrębnić tekst z obrazu** plików, konwertować *obraz na tekst w C#*, i radzić sobie z niuansami rozpoznawania języka rosyjskiego przy użyciu Aspose OCR. Po zakończeniu będziesz mieć gotową do uruchomienia aplikację konsolową, która wczytuje obraz do OCR, wypisuje rozpoznany ciąg znaków i zapewnia solidną podstawę do bardziej zaawansowanych scenariuszy. + +## Czego się nauczysz + +- Jak zainstalować i skonfigurować **Aspose OCR C#** dla wsparcia języka rosyjskiego. +- Dokładne kroki, aby **wczytać obraz do OCR** i wywołać silnik. +- Wskazówki dotyczące radzenia sobie z typowymi problemami, takimi jak brakujące zasoby językowe lub rozmyte skany. +- Sposoby rozszerzenia rozwiązania, takie jak przetwarzanie wsadowe wielu plików lub dostosowywanie progów pewności. + +Nie wymagana jest wcześniejsza znajomość Aspose; wystarczy podstawowa znajomość C# i .NET, aby rozpocząć. + +## Wymagania wstępne + +Zanim zaczniemy, upewnij się, że masz następujące elementy: + +1. **.NET 6.0** (lub nowszy) SDK zainstalowane – kod działa zarówno na .NET Core, jak i .NET Framework. +2. **Visual Studio 2022** (lub dowolne IDE, które preferujesz). +3. Pakiet NuGet **Aspose.OCR for .NET** – możesz pobrać darmowy klucz próbny ze strony Aspose. +4. Plik **modelu języka rosyjskiego** (`rus.traineddata`) – pobierz go ze strony zasobów Aspose i umieść w folderze, do którego będziesz się odwoływać później. +5. Przykładowy obraz (`russian_doc.png`) zawierający wyraźny tekst cyrylicą. + +Masz wszystko? Świetnie — zaczynajmy. + +## Krok 1: Utwórz projekt i zainstaluj Aspose OCR + +Najpierw utwórz nowy projekt konsolowy: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Teraz dodaj pakiet Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Wskazówka:** Jeśli używasz licencji próbnej, miej pod ręką plik `Aspose.Total.lic`; załadujesz go w kodzie, aby uniknąć znaków wodnych. + +Po zainstalowaniu pakietu otwórz `Program.cs`. Zobaczysz domyślną metodę `Main` — zastąp jej zawartość szkieletem, który zbudujemy. + +## Krok 2: Skonfiguruj silnik OCR dla języka rosyjskiego + +Serce operacji to obiekt `OcrEngine`. Musimy przekazać mu dwie rzeczy: jaki język rozpoznawać i gdzie znaleźć pliki modeli językowych. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Dlaczego to ważne:** Jeśli pominiesz ustawienie `Language = OcrLanguage.Russian`, silnik domyślnie użyje języka angielskiego, a wszystkie znaki cyrylicy pojawią się jako zniekształcone symbole. `ResourceFolder` wskazuje katalog zawierający plik `rus.traineddata`; bez niego Aspose zgłasza wyjątek *resource not found*. + +## Krok 3: Wczytaj obraz do OCR + +Teraz musimy **wczytać obraz do OCR**. Aspose OCR działa z `System.Drawing.Image`, więc możesz podać dowolny obsługiwany format (PNG, JPEG, BMP itp.). Upewnij się, że ścieżka do pliku jest prawidłowa; ścieżki względne są w porządku, jeśli trzymasz obraz obok pliku wykonywalnego. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Przypadek brzegowy:** Jeśli obraz jest duży (powyżej 5 MB), możesz najpierw go zmniejszyć. Dokładność OCR spada, gdy DPI jest zbyt niskie, ale ogromne pliki mogą powodować obciążenie pamięci. Szybka zmiana rozmiaru może być wykonana przy użyciu `Graphics`, jeśli to konieczne. + +## Krok 4: Rozpoznaj tekst – od obrazu do tekstu w stylu C# + +Po skonfigurowaniu silnika i wczytaniu obrazu, faktyczne rozpoznanie odbywa się jednym wywołaniem: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Gdy uruchomisz program (`dotnet run`), powinieneś zobaczyć coś podobnego do: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Jeśli wynik wygląda na bełkot, sprawdź ponownie, czy: + +- Plik `rus.traineddata` znajduje się w `ResourceFolder`. +- Obraz nie jest zbyt rozmyty; rozważ zastosowanie prostego filtru binaryzacji przed OCR. +- Ustawienie języka jest rzeczywiście `OcrLanguage.Russian`. + +## Krok 5: Dostosowywanie i typowe problemy + +### Dostosowywanie progu pewności + +Aspose OCR zwraca wewnętrznie wartość pewności dla każdego znaku. Chociaż API nie udostępnia jej bezpośrednio, możesz włączyć **szczegółowy output**, aby zobaczyć, które słowa mają niską pewność: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Jeśli zauważysz częste błędne rozpoznania, spróbuj: + +- **Wstępne przetwarzanie**: Konwertuj obraz na odcienie szarości, zwiększ kontrast lub zastosuj filtr medianowy. +- **Ustawienia DPI**: Upewnij się, że obraz ma co najmniej 300 DPI dla skryptów cyrylicy. + +### Przetwarzanie wsadowe wielu obrazów + +Jeśli potrzebujesz **wyodrębnić tekst z obrazu** w trybie wsadowym, otocz logikę rozpoznawania pętlą: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Teraz każdy plik PNG otrzymuje własny odpowiednik `.txt` — przydatne przy archiwizacji dokumentów. + +### Obsługa wyjścia Unicode + +Znaki cyrylicy są Unicode, więc upewnij się, że kodowanie konsoli może je wyświetlać: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Umieść tę linię zaraz po rozpoczęciu metody `Main`. Bez niej możesz zobaczyć znaki zapytania (`?`) zamiast rosyjskich liter. + +## Pełny działający przykład + +Poniżej znajduje się kompletny, gotowy do uruchomienia kod. Skopiuj i wklej go do `Program.cs`, dostosuj ścieżki i możesz zaczynać. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Oczekiwany wynik** (zakładając, że przykładowy obraz zawiera „Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Jeśli zobaczysz coś innego, wróć do wskazówek rozwiązywania problemów w Kroku 5. + +## Podsumowanie + +Masz teraz solidny, kompleksowy przykład, jak **ocr rosyjski tekst** w C# przy użyciu Aspose OCR. Od instalacji biblioteki, konfiguracji modelu języka rosyjskiego, po wczytanie obrazu i konwersję na czysty tekst Unicode, każdy element został omówiony. + +Pamiętaj, kluczem do niezawodnego OCR jest dobre źródło: wyraźne czcionki, odpowiednie DPI i właściwe zasoby językowe. Gdy opanujesz podstawy, możesz rozszerzyć rozwiązanie o przetwarzanie wsadowe, integrację z przechowywaniem w chmurze lub nawet połączenie z AI w celu korekty ortograficznej. + +### Co dalej? + +- Zbadaj zaawansowane opcje **aspose ocr c#**, takie jak analiza układu czy wyjście PDF. +- Połącz to z przepływami **extract text from image** w Azure Functions dla przetwarzania serverless. +- Wypróbuj różne języki — po prostu zamień `OcrLanguage.Russian` na `OcrLanguage.English` lub inny obsługiwany kod. + +Masz pytania lub trudny obraz, który nie współpracuje? Dodaj komentarz poniżej i powodzenia w kodowaniu! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + +## Powiązane samouczki + +- [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 przy użyciu Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/polish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..1f4d00b77 --- /dev/null +++ b/ocr/polish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-05-25 +description: Rozpoznawaj tekst z obrazu przy użyciu Aspose OCR w C#. Dowiedz się, + jak wczytać obraz do OCR, ustawić język OCR, utworzyć silnik OCR i wyodrębnić tekst + z pliku TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: pl +og_description: rozpoznawaj tekst z obrazu przy użyciu Aspose OCR w C#. Ten samouczek + pokazuje, jak utworzyć silnik OCR, załadować obraz do OCR, ustawić język OCR i wyodrębnić + tekst z pliku TIFF. +og_title: Rozpoznawanie tekstu z obrazu za pomocą Aspose OCR – Kompletny przewodnik + C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Rozpoznawanie tekstu z obrazu przy użyciu Aspose OCR – Kompletny przewodnik + C# +url: /pl/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# rozpoznawanie tekstu z obrazu przy użyciu Aspose OCR – Kompletny przewodnik C# + +Kiedykolwiek potrzebowałeś **rozpoznać tekst z obrazu**, ale nie wiedziałeś, która biblioteka zapewni zarówno szybkość, jak i dokładność? Nie jesteś sam. W wielu projektach przetwarzania faktur lub archiwizacji największym problemem jest uzyskanie czystego, przeszukiwalnego tekstu z plików TIFF bez pisania własnego parsera. + +Otóż Aspose OCR dla .NET sprawia, że cały ten proces jest dziecinnie prosty. W tym przewodniku przejdziemy przez wszystko, co jest potrzebne – instalację pakietu, **utworzenie silnika OCR**, wczytanie pliku TIFF, ustawienie języka OCR oraz w końcu **wyodrębnienie tekstu z TIFF**. Po zakończeniu będziesz mieć gotową aplikację konsolową, która **rozpoznaje tekst z obrazu** w mgnieniu oka. + +## Wymagania wstępne + +- .NET 6.0 lub nowszy (kod działa również z .NET Core i .NET Framework) +- Visual Studio 2022 (lub dowolne inne IDE) +- Pakiet NuGet Aspose.OCR (obsługa GPU wymaga dodatku `Aspose.OCR.Gpu`) +- GPU z obsługą CUDA, jeśli chcesz dodatkowej wydajności (opcjonalnie, ale zalecane) + +> **Pro tip:** Jeśli nie masz GPU, po prostu pomiń linię `GpuDevice`, a silnik automatycznie przełączy się na CPU. + +## Krok 1: Instalacja Aspose OCR i utworzenie silnika OCR + +Najpierw dodaj niezbędne pakiety przez NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Teraz możemy **utworzyć silnik OCR**. Ten obiekt jest sercem procesu; przechowuje konfigurację, taką jak urządzenie, na którym ma działać, oraz limity pamięci. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Dlaczego to ważne:** Powiązanie silnika z GPU drastycznie skraca czas potrzebny na **rozpoznawanie tekstu z obrazu**, szczególnie przy dużych partiach wysokiej rozdzielczości TIFF‑ów. + +## Krok 2: Wczytanie obrazu do OCR + +Następnie musimy **wczytać obraz do OCR**. Aspose.OCR współpracuje z `System.Drawing.Image`, więc każdy format obsługiwany przez GDI+ (w tym wielostronicowy TIFF) jest w porządku. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Jeśli pracujesz z wielostronicowym TIFF‑em, możesz przechodzić po stronach przy pomocy `image.SelectActiveFrame`, ale w większości przypadków wystarczy pojedyncze wywołanie. + +## Krok 3: Ustawienie języka OCR + +Silnik nie zgaduje, w jakim języku skanujesz. **Ustaw język OCR** przed uruchomieniem rozpoznawania; w przeciwnym razie otrzymasz mnóstwo nieczytelnych znaków. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Czy wiesz?** Zmiana języka w czasie działania jest tania – możesz nawet przetwarzać dokumenty wielojęzyczne, zmieniając tę właściwość pomiędzy stronami. + +## Krok 4: Wykonanie rozpoznawania – Rozpoznawanie tekstu z obrazu + +Teraz najciekawsza część: faktyczne **rozpoznawanie tekstu z obrazu**. Metoda `Recognize` zwraca zwykły ciąg znaków ze wszystkimi wykrytymi znakami. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Jeśli potrzebujesz wyników z oceną pewności lub ramkami ograniczającymi, możesz użyć przeciążenia zwracającego obiekt `OcrResult`, ale w większości zadań wyodrębniania wystarczy zwykły ciąg znaków. + +## Krok 5: Wyodrębnianie tekstu z TIFF (i obsługa plików wielostronicowych) + +Gdy źródłem jest TIFF zawierający kilka stron, będziesz chciał powtórzyć kroki 2‑4 dla każdej klatki. Oto szybka pętla, która **wyodrębnia tekst z TIFF** strona po stronie: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Powyższy kod wypisuje wyodrębniony tekst dla każdej strony, co ułatwia przekierowanie wyników do bazy danych lub indeksu wyszukiwania. + +## Krok 6: Wyświetlenie lub zapis wyodrębnionego tekstu + +Na koniec **wyświetlimy wyodrębniony tekst** i opcjonalnie zapiszemy go do pliku, aby móc go później przetworzyć. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Uruchomienie programu powinno wypisać rozpoznane znaki i utworzyć plik `extracted_text.txt` obok źródłowego TIFF‑a. + +--- + +## Często zadawane pytania i przypadki brzegowe + +- **Co zrobić, gdy GPU nie zostanie wykryte?** + Usuń linię `GpuDevice`; silnik automatycznie przełączy się w tryb CPU. Wydajność będzie niższa, ale wyniki pozostaną dokładne. + +- **Czy mogę przetwarzać pliki PNG lub JPEG?** + Oczywiście – `Image.FromFile` działa z każdym formatem obsługiwanym przez System.Drawing, więc możesz **wczytać obraz do OCR** niezależnie od rozszerzenia. + +- **Jak radzić sobie z niską rozdzielczością skanów?** + Zwiększ `ocrEngine.PreprocessOptions.Dpi` przed wywołaniem `Recognize`. Wyższe DPI daje silnikowi więcej pikseli do analizy, co poprawia dokładność. + +- **Czy istnieje limit rozmiaru TIFF‑a?** + Właściwość `GpuMemoryLimit` ogranicza zużycie pamięci GPU. Jeśli limit zostanie przekroczony, silnik przełączy się na CPU dla pozostałych stron. + +--- + +## Podsumowanie + +Masz teraz kompletny, gotowy do produkcji fragment kodu, który **rozpoznaje tekst z obrazu** przy użyciu Aspose OCR w C#. Tutorial pokazał, jak **utworzyć silnik OCR**, **wczytać obraz do OCR**, **ustawić język OCR** oraz **wyodrębnić tekst z TIFF** – wszystko z wykorzystaniem przyspieszenia GPU. + +Od tego momentu możesz: + +- Eksperymentować z różnymi językami (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` itp.). +- Zintegrować wyniki z przeszukiwalnym indeksem ElasticSearch. +- Dodać przetwarzanie po‑rozpoznawcze (sprawdzanie pisowni, czyszczenie regexem), aby podnieść jakość danych. + +Wypróbuj to na własnej partii faktur, dostosuj limity pamięci i zobacz, jak wydajność OCR rośnie. Powodzenia w kodowaniu! + +## Powiązane tutoriale + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..b502db727 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. +### [Criar Motor OCR em C# – Guia Completo](./create-ocr-engine-in-c-complete-guide/) +Aprenda a criar e configurar um motor OCR em C# passo a passo com Aspose.OCR. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/portuguese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..6e5c831eb --- /dev/null +++ b/ocr/portuguese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Crie um motor OCR em C# e aprenda como verificar seu modo de avaliação + e o status de licenciamento em poucas linhas de código. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: pt +og_description: Crie um motor OCR em C# e veja instantaneamente como detectar o modo + de avaliação e exibir o status da licença. +og_title: Crie um motor OCR em C# – Guia passo a passo +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Criar motor OCR em C# – Guia completo +url: /pt/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crie um OCR Engine em C# – Guia Completo + +Já se perguntou como **criar OCR engine** objetos em C# sem precisar vasculhar uma infinidade de documentos? Você não está sozinho. Muitos desenvolvedores se deparam com um obstáculo quando precisam iniciar um OCR engine, verificar se ele está em modo de avaliação e exibir o status da licença para os usuários. + +Neste tutorial vamos percorrer um exemplo conciso, de ponta a ponta, que **cria um OCR engine**, verifica seu **modo de avaliação do OCR engine** e imprime uma mensagem amigável sobre o estado da licença. Ao final, você terá um aplicativo console pronto‑para‑executar e um modelo mental claro para lidar com licenciamento de OCR em seus próprios projetos. + +## O que Você Vai Aprender + +- Como instanciar um `OcrEngine` (o núcleo de qualquer fluxo de trabalho OCR). +- Por que detectar **modo de avaliação** é importante para conformidade e experiência do usuário. +- A melhor forma de **verificar o status da licença OCR** e reagir a estados inesperados. +- Armadilhas comuns—referências nulas, tratamento de exceções e incompatibilidades de versão. + +Nenhuma ferramenta externa é necessária além do OCR SDK que você já tem instalado. Se você está confortável com a sintaxe básica de C#, está pronto para começar. + +## Pré‑requisitos + +- .NET 6.0 ou superior (o código compila com .NET Core e .NET Framework). +- Um OCR SDK que exponha uma classe `OcrEngine` com a propriedade `IsEvaluation` (por exemplo, o hipotético `MyOcrSdk`). +- Um editor de texto ou IDE (Visual Studio, VS Code, Rider—escolha o seu favorito). + +É só isso. Vamos mergulhar. + +## Etapa 1: Configurar um Novo Projeto de Console + +Primeiro, crie um novo aplicativo console para que você possa executar o código isoladamente. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Abra o `Program.cs` gerado. Substituiremos seu conteúdo por um exemplo completo que **cria instâncias de OCR engine** e trata o licenciamento. + +## Etapa 2: Importar o Namespace do OCR SDK + +Assumindo que o SDK foi referenciado via NuGet (`MyOcrSdk` é um placeholder), adicione a diretiva `using` no topo do arquivo. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Se ainda não adicionou o pacote, execute: + +```bash +dotnet add package MyOcrSdk +``` + +> **Dica profissional:** Mantenha sua versão do SDK sempre atualizada; lançamentos mais recentes costumam melhorar a detecção do modo de avaliação. + +## Etapa 3: Criar a Instância do OCR Engine + +Agora finalmente **crie objetos OCR engine**. Este é o coração de qualquer fluxo de trabalho OCR—pense nele como o cérebro que mais tarde lerá as imagens. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Por que essa etapa é crucial? O `OcrEngine` encapsula todas as configurações, pacotes de idioma e dados de licenciamento. Sem ele, você não pode processar imagens nem consultar a flag de avaliação. + +> **Observação:** Alguns SDKs permitem passar um objeto de configuração ao construtor (por exemplo, idioma, DPI). Se precisar de configurações personalizadas, modifique a linha conforme necessário. + +## Etapa 4: Determinar o Modo de Avaliação do OCR Engine + +A maioria dos fornecedores de OCR oferece uma versão de teste que funciona em **modo de avaliação** até que uma chave de licença válida seja fornecida. Saber se você está em modo de avaliação permite exibir indicadores de UI adequados ou restringir certos recursos. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +A propriedade `IsEvaluation` retorna `true` quando o engine está sem licença ou usando um teste com tempo limitado. É uma maneira rápida e confiável de proteger recursos premium. + +### E se a Propriedade Não Existir? + +Versões mais antigas do SDK podem expor um método como `GetLicenseInfo()` em vez disso. Nesse caso, você inspecionaria o objeto retornado em busca de uma flag `IsTrial`. Sempre consulte o changelog do SDK ao atualizar. + +## Etapa 5: Exibir o Status Atual da Licença + +Por fim, vamos mostrar ao usuário se o engine está licenciado ou ainda em modo de avaliação. Um simples `Console.WriteLine` resolve, mas você pode adaptar para aplicativos GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +O operador ternário mantém o código enxuto, e as mensagens são claras o suficiente para usuários finais ou desenvolvedores que leiam os logs. + +## Exemplo Completo Funcional + +Juntando tudo, aqui está um programa autocontido que você pode copiar‑colar no `Program.cs` e executar com `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Saída Esperada + +- **Build de avaliação:** + `Running in evaluation mode – limited functionality.` + +- **Build licenciado:** + `Licensed – full OCR capabilities enabled.` + +Se o SDK lançar uma exceção (por exemplo, DLL nativa ausente), o bloco `catch` imprimirá uma mensagem de erro útil em vez de travar todo o aplicativo. + +## Tratamento de Casos Limítrofes e Armadilhas Comuns + +### 1. Instâncias Nulas do Engine + +Embora o construtor geralmente retorne um objeto válido, alguns SDKs podem retornar `null` se dependências nativas necessárias estiverem ausentes. Proteja‑se contra isso: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Expiração da Licença Durante a Execução + +Uma licença de avaliação pode expirar no meio da sessão. Re‑consulta periodicamente `IsEvaluation` se seu app permanecer ativo por muito tempo. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Nomes de Propriedade Diferentes entre Versões + +Lançamentos antigos podem expor `engine.EvaluationMode` ou `engine.License.IsTrial`. Ao atualizar, procure nas notas de versão do SDK por mudanças que quebrem a compatibilidade. + +### 4. Cenários Multi‑Thread + +Se você iniciar vários workers de OCR, instancie **um OCR engine por thread** a menos que o SDK suporte explicitamente compartilhamento thread‑safe. Compartilhar um único engine pode gerar condições de corrida e leituras de licença incorretas. + +## Dicas Profissionais para Uso em Produção + +- **Cacheie o status da licença** após a primeira verificação para evitar chamadas desnecessárias à propriedade. +- **Registre a chave de licença** (mascarada) na inicialização para auditoria—ajuda as equipes de suporte a diagnosticar problemas de licenciamento. +- **Forneça um toggle UI** que informe aos usuários que estão em modo de avaliação e ofereça um botão “Comprar Licença”. +- **Automatize a renovação da licença** usando a API de ativação do SDK, se disponível, para manter a experiência do usuário fluida. + +## Conclusão + +Acabamos de **criar OCR engine** objetos em poucas linhas, inspecionar o **modo de avaliação do OCR engine** e imprimir uma mensagem clara de **status da licença OCR**. O exemplo completo funciona out‑of‑the‑box, trata erros de forma elegante e destaca o “porquê” de cada passo—para que você possa adaptá‑lo a cenários desktop, web ou de serviço. + +Próximos passos sugeridos: + +- Alimentar imagens em `engine.Recognize` e lidar com suporte a múltiplos idiomas. +- Usar APIs de **check OCR license** para ativar programaticamente uma chave comprada. +- Integrar com frameworks UI (WinForms, WPF, MAUI) para exibir selos de licenciamento. + +Experimente essas ideias e você terá uma base robusta de OCR pronta para qualquer aplicação. Feliz codificação! + +## Tutoriais Relacionados + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/ocr-optimization/_index.md b/ocr/portuguese/net/ocr-optimization/_index.md index 7a728f21a..ce45cc8af 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. +### [Pré‑processar Imagem para OCR – Guia Completo Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Aprenda a aplicar filtros avançados e melhorar a qualidade das imagens antes do OCR usando Aspose.OCR em C#. ## Perguntas Frequentes diff --git a/ocr/portuguese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/portuguese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..89e0d7f54 --- /dev/null +++ b/ocr/portuguese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Pré‑processar imagem para OCR com Aspose para melhorar a precisão do + OCR e executar OCR em arquivos JPEG. Aprenda como extrair texto usando Aspose em + um tutorial claro, passo a passo. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: pt +og_description: Pré-processar imagem para OCR com Aspose para melhorar a precisão + do OCR. Siga este guia para executar OCR em JPEG e extrair texto usando Aspose em + C#. +og_title: Pré-processar imagem para OCR – Tutorial Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Pré-processar imagem para OCR – Guia completo Aspose C# +url: /pt/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Pré-processar Imagem para OCR – Guia Completo Aspose C# + +Já se perguntou como **preprocess image for OCR** para que o texto saia limpo todas as vezes? Você não está sozinho—os desenvolvedores estão constantemente lutando contra digitalizações ruidosas, JPEGs de baixo contraste e iluminação imprevisível. A boa notícia? Com alguns ajustes inteligentes você pode **improve OCR accuracy** dramaticamente, e a Aspose torna isso fácil. + +Neste tutorial, percorreremos um exemplo do mundo real que mostra como **run OCR on JPEG** imagens, aplicar um pipeline de processamento de imagem personalizado e, finalmente, **extract text using Aspose**. Ao final, você terá um trecho de código C# pronto‑para‑colar que pode ser inserido em qualquer projeto .NET. + +## O que você aprenderá + +- Por que o pré-processamento importa e quais filtros oferecem o maior benefício. +- Como configurar `ImageProcessingOptions` da Aspose.OCR para correção de inclinação, remoção de ruído, binarização e aumento de contraste. +- O código exato necessário para **run OCR on JPEG** arquivos e recuperar texto limpo. +- Dicas e armadilhas que mantêm seu pipeline de OCR robusto em produção. + +Não é necessário ter experiência prévia com Aspose; basta um conhecimento básico de C# e Visual Studio (ou sua IDE favorita). Vamos começar. + +![Preprocess image for OCR example](preprocess-ocr.png "Preprocess image for OCR") + +## Etapa 1: Configurar o Motor Aspose.OCR – Preprocess Image for OCR + +Primeiro, precisamos de uma instância `OcrEngine` e devemos informar qual idioma esperamos. Na maioria dos casos, o inglês é o padrão, mas você pode trocá-lo por francês, alemão etc., alterando o enum `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Por que isso importa:** O motor é o coração da operação; sem ele você não pode aplicar nenhum dos filtros de imagem que realmente **preprocess image for OCR**. Pense nele como a cozinha onde todos os ingredientes são misturados. + +## Etapa 2: Construir um Pipeline de Processamento de Imagem Personalizado – Improve OCR Accuracy + +Agora vem a parte interessante. A Aspose permite encadear vários filtros. Abaixo habilitamos quatro dos mais eficazes: + +1. **Deskew** – endireita documentos inclinados (máx. 5° por padrão). +2. **Denoise** – suaviza fundos granulosos. +3. **Binarize** – converte a imagem para preto‑e‑branco usando um limiar. +4. **ContrastBoost** – realça caracteres fracos. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Dica profissional:** Se suas imagens de origem já estiverem nítidas, você pode reduzir o `Strength` ou desativar um filtro completamente. O processamento excessivo pode às vezes apagar caracteres fracos, então experimente com amostras reais. + +## Etapa 3: Carregar o JPEG (ou Qualquer Imagem) e Executar OCR – Run OCR on JPEG + +A Aspose funciona com qualquer formato de imagem que o .NET possa ler—JPEG, PNG, BMP, o que você quiser. Aqui está como você fornece um arquivo JPEG ao motor e inicia o processo de reconhecimento. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Por que JPEG?** A compressão JPEG frequentemente introduz artefatos que confundem o OCR. Nosso pipeline de pré-processamento, especialmente as etapas de denoise e binarize, mitiga esses problemas, permitindo que você **run OCR on JPEG** com confiança. + +## Etapa 4: Exportar o Texto Reconhecido – Extract Text Using Aspose + +Finalmente, simplesmente gravamos o texto no console, em um arquivo ou em qualquer serviço downstream. Para fins de demonstração, o console basta. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Ao executar o programa, você deverá ver algo como: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Se a saída parecer confusa, volte à **Step 2** e ajuste as configurações dos filtros. Pequenos ajustes costumam gerar grandes ganhos em **improve OCR accuracy**. + +## Casos de Borda Comuns e Como Lidar com Eles + +| Situação | Ajuste Sugerido | +|-----------|----------------------| +| **Very dark images** | Aumente `ContrastBoost.Level` para 1.5 ou mais. | +| **Skew > 5°** | Eleve `DeskewOptions.MaxAngle` (ex.: 10.0) ou pré‑gire a imagem manualmente. | +| **Colored text on colored background** | Use `BinarizeOptions` com um limiar personalizado ou troque para `AdaptiveBinarizeOptions`. | +| **Large files ( > 5 MB )** | Carregue a imagem em um `MemoryStream` primeiro para evitar problemas de bloqueio de arquivo. | + +Esses ajustes mantêm seu pipeline flexível e à prova de futuro, especialmente quando você precisa **extract text using Aspose** de fontes diversas. + +## Exemplo Completo Funcional – Todas as Etapas em Um Só Lugar + +Abaixo está o programa completo, pronto para copiar e colar. Ele compila com .NET 6+ e requer apenas o pacote NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Salve como `Program.cs`, adicione o pacote Aspose.OCR (`dotnet add package Aspose.OCR`) e execute `dotnet run`. Você verá o texto limpo impresso no console. + +## Recapitulação – Por Que Essa Abordagem Funciona + +- **Preprocess image for OCR**: O pipeline remove as fontes de erro mais comuns (inclinação, ruído, baixo contraste). +- **Improve OCR accuracy**: Cada filtro é ajustado para aumentar a relação sinal‑ruído que o motor vê. +- **Run OCR on JPEG**: Mesmo imagens comprimidas tornam‑se legíveis após a correção de inclinação e binarização. +- **Extract text using Aspose**: O método `Recognize` retorna uma string simples, pronta para qualquer lógica downstream. + +Juntas, essas etapas fornecem uma solução OCR confiável e de nível de produção em apenas algumas linhas. + +## Próximos Passos e Tópicos Relacionados + +- **Batch processing** – Percorra uma pasta de imagens e escreva cada resultado em um arquivo `.txt`. +- **Language packs** – Troque `OcrLanguage.English` por `OcrLanguage.Spanish` ou adicione dicionários personalizados. +- **PDF extraction** – Combine Aspose.OCR com Aspose.PDF para extrair texto diretamente de PDFs escaneados. +- **Performance tuning** – Execute o motor em paralelo usando `Parallel.ForEach` para grandes cargas de trabalho. + +Sinta-se à vontade para experimentar os valores dos filtros, testar diferentes formatos de imagem ou encadear filtros adicionais da Aspose como `SharpnessOptions`. O céu é o limite depois que você dominar o básico. + +--- + +*Feliz codificação! Se encontrar algum problema, deixe um comentário abaixo e nós vamos solucionar juntos.* + +## Tutoriais Relacionados + +- [Pré-processar Imagem OCR com Filtros Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Extrair Texto de Imagem – Otimização OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Extrair texto de imagem C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/_index.md b/ocr/portuguese/net/text-recognition/_index.md index 8efadbd23..2cd94b334 100644 --- a/ocr/portuguese/net/text-recognition/_index.md +++ b/ocr/portuguese/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Aprimore seus aplicativos .NET com Aspose.OCR para reconhecimento eficiente de t 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. ### [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. +### [Reconheça texto de imagem com Aspose OCR – Guia completo em C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Aprenda a reconhecer texto em imagens usando Aspose OCR com um guia completo em C#, passo a passo. +### [Extrair texto de imagem em C# – Guia completo Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Aprenda a extrair texto de imagens usando Aspose OCR em C# com um guia passo a passo completo. +### [Tutorial OCR em C#: Extrair Texto de Recibos PNG com Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Aprenda a extrair texto de recibos em PNG usando Aspose OCR em C#, passo a passo. +### [Como usar OCR em C# – Reconhecer texto chinês de JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Aprenda a usar Aspose.OCR em C# para reconhecer texto em chinês em arquivos JPG, passo a passo. +### [OCR de texto russo em C# – Guia completo usando Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Aprenda a reconhecer texto em russo usando Aspose OCR em C#, com um guia passo a passo para integrar OCR russo em suas aplicações. +### [Extrair texto de imagem em ASP.NET Core Minimal API – Guia completo](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Aprenda a extrair texto de imagens usando ASP.NET Core Minimal API com um guia passo a passo completo. +### [Converter TIFF para Texto em C# – Guia Completo de OCR em Lote](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Aprenda a converter arquivos TIFF em texto usando Aspose.OCR em C#, com um guia completo para processamento em lote. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/portuguese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..cfec1779b --- /dev/null +++ b/ocr/portuguese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: Tutorial de OCR em C# que mostra como carregar um arquivo de imagem em + C# e reconhecer texto PNG de um recibo usando Aspose OCR – guia passo a passo. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: pt +og_description: Tutorial de OCR em C# que orienta você a carregar um arquivo de imagem + em C# e reconhecer texto PNG de um recibo usando Aspose OCR. +og_title: Tutorial de OCR em C# – Extrair Texto de Recibos PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# tutorial de OCR: extrair texto de recibos PNG com Aspose' +url: /pt/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tutorial c# OCR – Extrair Texto de Recibos PNG com Aspose + +Já precisou de um **c# OCR tutorial** que realmente faça o trabalho sem ficar pesquisando infinitamente? Você está no lugar certo. Neste guia vamos **carregar arquivo de imagem c#**, **reconhecer texto png**, e **ler OCR de recibo** results, tudo enquanto mostramos como **executar OCR em imagem** com Aspose OCR. + +Vamos começar instalando o pacote NuGet necessário, percorrer cada linha de código e terminar com um dump de JSON organizado que você pode encaminhar diretamente para seu próximo pipeline de dados. Sem enrolação, apenas uma solução prática e pronta‑para‑executar. + +## O que você aprenderá + +- Como configurar o Aspose OCR em um projeto .NET 6 (ou posterior). +- Os passos exatos para **carregar um arquivo de imagem c#** e entregá‑lo ao motor. +- Como **reconhecer texto png** de uma imagem de recibo e capturar o resultado. +- Maneiras de **ler OCR de recibo** e obter a saída como JSON bem formatado. +- Dicas para **executar OCR em imagem** em diferentes tipos de arquivo e lidar com armadilhas comuns. + +**Prerequisites** +- Visual Studio 2022 (ou qualquer IDE de sua preferência). +- .NET 6 SDK ou mais recente. +- Uma imagem de recibo PNG à mão (vamos chamá‑la de `receipt.png`). + +Se você tem tudo isso, vamos mergulhar. + +![captura de tela do tutorial c# OCR](ocr-demo.png "resultado do tutorial c# OCR mostrando saída JSON") + +## Tutorial c# OCR – Configurando o Motor Aspose OCR + +First off, we need the Aspose OCR library. Open your terminal in the solution folder and run: + +```bash +dotnet add package Aspose.OCR +``` + +That single command pulls in everything required, including native binaries for image decoding. Once installed, create a new console project or add the code to an existing one. + +### Por que Aspose? + +Aspose OCR supports over 30 languages, works offline, and returns a rich `OcrResult` object—perfect for **executar OCR em imagem** tasks where you need more than just plain text. + +## Carregar arquivo de imagem c# e preparar o recibo + +Now that the library is ready, let’s **carregar arquivo de imagem c#**. The `System.Drawing.Image` class does the heavy lifting, but you could also use `SkiaSharp` if you prefer a cross‑platform alternative. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Dica profissional:** Envolva o `Image` em uma instrução `using` (como mostrado) para liberar recursos nativos rapidamente—especialmente importante quando você **executa OCR em imagem** em muitos arquivos dentro de um loop. + +## Reconhecer texto PNG com Aspose + +With the image in memory, the engine can now **reconhecer texto png**. Aspose returns an `OcrResult` that contains both the raw string and detailed data about each recognized word. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Why call `RecognizeWithResult` instead of the simpler `Recognize`? The former gives you access to confidence scores, bounding boxes, and line breaks—handy if you later need to **ler OCR de recibo** for line‑item extraction. + +## Ler resultado OCR de recibo como JSON + +Most downstream systems love JSON, so let’s serialize the `OcrResult`. The `System.Text.Json` serializer handles complex objects gracefully, and we’ll enable indentation for readability. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +The resulting JSON looks something like this (trimmed for brevity): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +You can now pipe `jsonResult` into a database, a message queue, or simply log it for debugging. + +## Executar processamento OCR de imagem e exibir saída + +Finally, output the JSON to the console. In a real‑world app you’d probably write it to a file or send it over HTTP, but the console makes it easy to verify everything worked. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Run the program (`dotnet run`) and you should see the nicely formatted JSON printed. If the receipt image is clear, the text will be spot‑on; if not, consider increasing the image resolution or applying a preprocessing filter (e.g., grayscale, contrast boost) before feeding it to the engine. + +### Lidando com casos de borda comuns + +| Situação | O que fazer | +|-----------|------------| +| **Imagem está borrada** | Pré‑processar com `System.Drawing` para aguçar ou aumentar DPI. | +| **Recibo contém múltiplos idiomas** | Set `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Processamento em lote grande** | Reutilize uma única instância de `OcrEngine`; altere apenas o `Image` a cada iteração. | +| **Pressão de memória** | Dispose os objetos `Image` rapidamente e considere `await Task.Run` para pipelines assíncronos. | + +These tweaks keep your **executar OCR em imagem** workflow robust even when the input isn’t perfect. + +## Conclusão + +Congratulations—you’ve just completed a **c# OCR tutorial** that loads an image, **recognizes png text**, and **reads receipt OCR** output as clean JSON. The core steps (engine setup, image loading, OCR execution, serialization, and display) form a solid foundation you can extend to invoices, passports, or any other scanned document. + +### O que vem a seguir? + +- Experimente **carregar arquivo de imagem c#** usando `SkiaSharp` para suporte verdadeiramente multiplataforma. +- Aprofunde-se em `OcrResult.Words` para extrair itens de linha, preços e datas—perfeito para aplicativos de controle de despesas. +- Combine este tutorial com Azure Functions ou AWS Lambda para criar uma API serverless de processamento de recibos. + +Feel free to tweak the code, throw in more images, or even switch to a different language pack. The world of OCR is full of surprises, and now you have the tools to explore them. + +Happy coding, and may your receipts always be readable! + +## Tutoriais Relacionados + +- [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 – Otimização OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Como usar OCR - Reconhecer Imagem sem Detecção de Área de Texto](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/portuguese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..619a9d545 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,204 @@ +--- +category: general +date: 2026-05-25 +description: Converta TIFF em texto usando Aspose.OCR em C#. Aprenda a conversão em + lote de imagens para texto e extraia texto de arquivos TIFF de forma eficiente. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: pt +og_description: Converta TIFF em texto com Aspose.OCR. Este guia mostra a conversão + em lote de imagem para texto e como extrair texto de arquivos TIFF em poucas linhas + de C#. +og_title: Converter TIFF para Texto em C# – Guia Completo de OCR em Lote +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Converter TIFF para Texto em C# – Guia Completo de OCR em Lote +url: /pt/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Converter TIFF para Texto em C# – Guia Completo de OCR em Lote + +Já precisou **converter TIFF para texto** mas não sabia por onde começar? Você não está sozinho — muitos desenvolvedores tropeçam no OCR em lote ao lidar com documentos escaneados. Neste tutorial vamos percorrer uma solução prática que **extrai texto de arquivos TIFF** usando Aspose.OCR, e faremos isso em paralelo para que pastas grandes terminem em segundos. + +Também abordaremos as melhores práticas de **conversão em lote de imagem para texto**, então ao final você terá um trecho reutilizável que transforma um diretório inteiro de imagens escaneadas em arquivos *.txt* organizados — perfeito para indexação, busca ou alimentação de análises posteriores. + +## O que você vai precisar + +- **.NET 6.0** ou superior (o código também compila no .NET Framework) +- Pacote NuGet **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Uma pasta contendo um ou mais arquivos *.tif* (o clássico formato de escaneamento TIFF) +- Seu IDE favorito (Visual Studio, VS Code, Rider — o que preferir) + +É só isso. Sem serviços externos, sem chaves de API, apenas C# puro e Aspose. + +![Screenshot of a TIFF file being processed and the resulting text file](/images/ocr-result.png "OCR result showing converted TIFF to text output") + +*(Alt text: Screenshot showing converted TIFF to text output on screen)* + +## Etapa 1: Configurar o Motor OCR – Converter TIFF para Texto + +Primeiro de tudo, precisamos de uma instância `OcrEngine` que saiba que deve ler caracteres em inglês. O motor é o coração da conversão; configurá‑lo corretamente garante resultados confiáveis. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Por que isso importa:* +Aspose.OCR suporta dezenas de idiomas. Se você estiver lidando com escaneamentos multilíngues, basta mudar `OcrLanguage.English` para o valor enum apropriado. Deixar o idioma indefinido força o motor ao modo de auto‑detecção, que pode ser mais lento e menos preciso. + +## Etapa 2: Coletar Todos os Arquivos TIFF – Extrair Texto de TIFF de Forma Eficiente + +Em seguida, buscamos cada arquivo *.tif* de uma pasta que você especificar. Usar `Directory.GetFiles` nos fornece um array limpo que podemos passar ao processador em lote. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Dica de especialista:* O sinalizador `SearchOption.AllDirectories` pode ser usado se seus escaneamentos estiverem aninhados em subpastas. Apenas lembre‑se de que recursão mais profunda pode aumentar o uso de memória durante a etapa em lote. + +## Etapa 3: Executar OCR em Paralelo – Conversão em Lote de Imagem para Texto + +Agora vem a parte divertida. Aspose.OCR fornece o helper estático `BatchOcr.RecognizeAll` que aceita um array de caminhos de arquivo, um motor e uma sugestão de `parallelism`. Vamos iniciar quatro threads, o que em um laptop quad‑core moderno oferece quase aceleração linear. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Por que paralelismo?* +Processar um lote de TIFFs de alta resolução pode ser intensivo para a CPU. Ao distribuir o trabalho entre várias threads mantemos todos os núcleos ocupados, reduzindo drasticamente o tempo total. Se você executar isso em um servidor com mais núcleos, aumente o valor de `parallelism` conforme necessário. + +## Etapa 4: Gravar a Saída – Converter Imagens Escaneadas em Arquivos TXT + +Por fim, percorremos o dicionário e gravamos cada trecho de texto em um arquivo *.txt* que compartilha o nome base original. Este é o momento em que **convert scanned images txt** se torna realidade. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### O que o código faz, em português simples + +1. **Cria** um motor OCR configurado para inglês. +2. **Coleta** todos os arquivos TIFF da pasta de destino. +3. **Executa** `BatchOcr.RecognizeAll` com quatro threads, transformando cada imagem em uma string. +4. **Percorre** os resultados, substituindo a extensão `.tif` por `.txt` e gravando a string no disco. + +Esse é todo o fluxo de **converter TIFF para texto** em menos de 50 linhas de código. + +## Lidando com Casos de Borda – Quando as Coisas Não Saem Como Esperado + +- **TIFFs ausentes ou corrompidos** – `BatchOcr` lançará uma `OcrException`. Envolva a chamada em um `try / catch` se precisar de degradação graciosa. +- **Documentos não‑inglês** – altere `OcrLanguage.English` para `OcrLanguage.Spanish`, `OcrLanguage.French`, etc., ou use `OcrLanguage.AutoDetect`. +- **Imagens muito grandes** – considere reduzir o DPI antes do OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) para economizar memória, embora possa perder alguma precisão. +- **Codificação da saída** – se precisar de uma página de códigos específica (ex.: Windows‑1252), passe-a para `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Dicas Profissionais para Conversões em Lote Robustas + +- **Registre falhas**: crie uma `List failedFiles` e adicione qualquer arquivo que lançar exceção; escreva a lista em um log após o loop. +- **Reutilize o motor**: a mesma instância `OcrEngine` pode ser reutilizada em vários arquivos; não a instancie dentro do loop. +- **Valide o resultado**: um rápido `if (string.IsNullOrWhiteSpace(extractedText))` pode sinalizar escaneamentos em branco ou ilegíveis. +- **Combine com PDF**: se sua fonte for um PDF multipágina, converta cada página para TIFF primeiro (Aspose.PDF faz isso) e então execute este lote. + +## Próximos Passos – Indo Além da Conversão Simples + +Agora que você pode **extrair texto de arquivos TIFF** em massa, talvez queira: + +- Alimentar os arquivos *.txt* em um índice de busca (Elasticsearch, Azure Cognitive Search). +- Executar detecção de idioma em cada resultado para encaminhar documentos a pipelines específicos por localidade. +- Gerar PDFs pesquisáveis sobrepondo o texto OCR nas imagens originais (Aspose.PDF novamente). + +Todos esses cenários se baseiam na mesma ideia central: **conversão em lote de imagem para texto** é um bloco de construção para sistemas maiores de processamento de documentos. + +--- + +### Conclusão + +Você acabou de aprender como **converter TIFF para texto** usando Aspose.OCR, processar uma pasta inteira em paralelo e salvar cada resultado como um arquivo *.txt* limpo. A solução é leve, totalmente configurável e pronta para produção — seja digitalizando faturas legadas, arquivando contratos escaneados ou alimentando um motor de busca textual. + +Teste, ajuste o paralelismo e comece a alimentar esses novos arquivos de texto ao fluxo de trabalho que precisar. Boa OCR! + +--- + + +## Tutoriais Relacionados + +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/portuguese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..252e3588f --- /dev/null +++ b/ocr/portuguese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Aprenda como extrair texto de uma imagem com uma API mínima ASP.NET Core. + Envie a imagem via POST, leia os dados de formulário multipart e execute OCR na + imagem. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: pt +og_description: Extrair texto de imagem usando uma API minimal do ASP.NET Core. Este + guia mostra como fazer upload de imagem via POST, ler dados de formulário multipart + e realizar OCR na imagem. +og_title: Extrair Texto de Imagem no ASP.NET Core – Passo a Passo +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Extrair Texto de Imagem em ASP.NET Core Minimal API – Guia Completo +url: /pt/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrair Texto de Imagem em ASP.NET Core Minimal API – Guia Completo + +Já se perguntou como **extrair texto de imagem** sem lidar com frameworks pesados? Você não está sozinho. Muitos desenvolvedores precisam de uma maneira rápida de permitir que os usuários enviem uma foto e recebam de volta os caracteres brutos, seja escaneando recibos, digitalizando notas manuscritas ou alimentando um índice de busca. + +Neste tutorial vamos criar uma pequena ASP.NET Core Minimal API que **faz upload de imagem via POST**, analisa o payload *multipart/form‑data* e então **executa OCR na imagem** usando um singleton `OcrEngine`. Ao final, você terá um aplicativo totalmente executável que pode ser inserido em qualquer projeto .NET 8 e começar a extrair texto de imagem imediatamente. + +## O que você vai construir + +- Um aplicativo web minimal que escuta em `/ocr`. +- Um endpoint que aceita um arquivo de imagem enviado com uma requisição POST `multipart/form-data`. +- Lógica que lê o arquivo enviado, o encaminha para o motor OCR e retorna resultados em texto simples. +- Trecho opcional de aceleração por GPU (comentado) para quem tem uma placa compatível. + +**Pré-requisitos** +- .NET 8 SDK (ou superior). +- Familiaridade básica com C# e a linha de comando. +- Uma biblioteca OCR que exponha a classe `OcrEngine` (o exemplo assume um pacote NuGet hipotético). + +Se você tem isso, vamos mergulhar. + +## Etapa 1: Configurar o Projeto e Adicionar o Pacote OCR + +Primeiro, crie um novo projeto web e inclua a biblioteca OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Dica profissional:** Mantenha suas dependências atualizadas. Versões mais recentes costumam trazer ganhos de desempenho, especialmente para inferência acelerada por GPU. + +## Etapa 2: Registrar um Engine OCR Singleton (Serviço Principal) + +Queremos uma única instância de `OcrEngine` para todo o aplicativo — não há necessidade de criar um novo engine por requisição. Registre-a no contêiner de serviços do builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Por que um singleton?** +Criar um engine OCR pode ser caro — pense em carregar pesos de redes neurais na memória. Reutilizando a mesma instância, economizamos ciclos de CPU e RAM, o que se traduz em tempos de resposta mais rápidos para cada chamada `/ocr`. + +## Etapa 3: Construir a Aplicação + +Agora materializamos o objeto `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Essa linha parece quase mágica, mas nos bastidores ela configura o roteamento, middleware e o contêiner DI que acabamos de configurar. + +## Etapa 4: Definir o Endpoint POST – “Upload Image via POST” + +Aqui está o coração do tutorial: um endpoint que **faz upload de imagem via POST**, lê o payload multipart e entrega os dados ao engine OCR. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Detalhando a Lógica + +| Etapa | O que acontece | Por que importa | +|------|----------------|-----------------| +| **ReadFormAsync** | Analisa a requisição *multipart/form-data* entrante. | Sem isso, você não pode acessar os arquivos enviados. | +| **form.Files["image"]** | Recupera o arquivo cujo nome de campo no formulário é `image`. | Garante um contrato previsível para os chamadores. | +| **Content‑type check** | Verifica se o arquivo é uma imagem (ex., `image/png`). | Impede que o engine OCR falhe ao receber dados que não são imagens. | +| **Image.FromStream** | Converte o fluxo bruto em um `System.Drawing.Image`. | A biblioteca OCR espera um objeto `Image`, não um array de bytes bruto. | +| **ocr.Recognize(img)** | Chama o engine OCR para **como reconhecer texto a partir da imagem**. | Este é o passo central de **executar OCR na imagem**. | +| **Results.Text** | Retorna a resposta em texto simples. | Um formato simples e consumível para serviços downstream. | + +## Etapa 5: Executar a API + +Finalmente, inicie o servidor web. + +```csharp +app.Run(); +``` + +Ao executar `dotnet run`, a API ouvirá em `http://localhost:5000` (ou em uma porta de sua escolha). Você pode testá-la com `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Saída esperada:** O console imprimirá os caracteres reconhecidos, por exemplo: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Se a imagem estiver borrada ou o idioma não for suportado, o engine OCR retornará uma string vazia ou uma mensagem de erro — trate esses casos no código de produção. + +## Casos de Borda & Boas Práticas + +### 1. Arquivos Grandes + +O limite padrão do corpo da requisição é 30 MB. Para digitalizações maiores, talvez seja necessário ajustar: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR Assíncrono + +Algumas bibliotecas OCR expõem métodos assíncronos (`RecognizeAsync`). Se a sua fizer isso, substitua `ocr.Recognize(img)` por `await ocr.RecognizeAsync(img)` e marque a lambda como `async`. + +### 3. Considerações de Segurança + +- **Validar o tamanho do arquivo** antes de carregá-lo na memória. +- **Sanitizar o nome do arquivo** se você alguma vez o gravar em disco. +- **Aplicar rate‑limit** ao endpoint para evitar ataques de negação de serviço. + +### 4. Aceleração por GPU + +Se você descomentar a linha `engine.GpuDevice = new GpuDevice(0);` e seu hardware suportar CUDA ou DirectML, verá um aumento de velocidade perceptível, especialmente em imagens de alta resolução. + +## Exemplo Completo Funcional + +Abaixo está o `Program.cs` completo que você pode copiar‑colar em um novo projeto Minimal API. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Salve, execute `dotnet run`, e você estará pronto para **extrair texto de imagem** sob demanda. + +## Conclusão + +Percorremos uma **solução completa, de ponta a ponta** para extrair texto de imagem usando ASP.NET Core Minimal API. Começando da estruturação do projeto, **registramos um engine OCR singleton**, construímos um endpoint que **faz upload de imagem via POST**, **lê dados multipart de formulário**, e finalmente **executa OCR na imagem** para retornar texto simples limpo. + +A partir daqui você pode: + +- Adicionar wrappers JSON para respostas mais ricas. +- Conectar um banco de dados para armazenar o texto extraído. +- Expandir o suporte para múltiplos idiomas (`OcrLanguage.Spanish`, etc.). + +O padrão escala bem — basta inserir o mesmo endpoint em um microserviço maior ou expô-lo por trás de um gateway de API. + +Tem perguntas sobre manipulação de PDFs, processamento em lote ou ajuste de GPU? Deixe um comentário, e feliz codificação! + +## Tutoriais Relacionados + +- [Extrair Texto de Imagem Usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extrair Texto de Imagem – Otimização OCR com Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Extrair texto de imagem C# com seleção de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/portuguese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..90f6f879e --- /dev/null +++ b/ocr/portuguese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: Extraia texto de imagens usando C# e Aspose OCR. Aprenda como converter + JPG em texto, carregar a imagem para OCR e obter resultados confiáveis rapidamente. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: pt +og_description: Extraia texto de imagem com C#. Este guia mostra como converter jpg + em texto, carregar a imagem para OCR e lidar com conteúdo multilíngue. +og_title: Extrair Texto de Imagem em C# – Tutorial de OCR da Aspose +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Extrair Texto de Imagem em C# – Guia Completo de OCR da Aspose +url: /pt/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrair Texto de Imagem em C# – Guia Completo de Aspose OCR + +Já se perguntou como **extrair texto de imagem** usando código C# puro? Você não está sozinho. Seja digitalizando recibos, escaneando placas ou apenas curioso sobre OCR, a capacidade de retirar caracteres de uma foto é uma habilidade útil. Neste tutorial vamos percorrer um exemplo completo, executável, que mostra exatamente como **extrair texto de imagem** com Aspose.OCR, e também abordaremos como **converter jpg para texto**, **carregar imagem para OCR**, e responderemos à clássica pergunta “**como fazer OCR em imagem**” de uma vez por todas. + +Ao final deste guia você terá um aplicativo console autônomo que lê um arquivo JPEG, reconhece ucraniano (ou qualquer outro idioma suportado) e imprime o resultado no console. Sem referências vagas, sem peças faltando — apenas uma solução completa que você pode copiar‑colar e executar. + +--- + +## O que Você Vai Aprender + +* Como instalar o pacote NuGet Aspose.OCR. +* O código exato necessário para **carregar imagem para OCR** em C#. +* Como definir o idioma e realmente **extrair texto de imagem**. +* Truques para **converter jpg para texto** de forma eficiente. +* Armadilhas comuns e como evitá‑las. + +Se você já tem um ambiente de desenvolvimento .NET configurado, está pronto para mergulhar. Caso contrário, a seção de pré‑requisitos abaixo vai deixá‑lo pronto. + +--- + +## Pré‑requisitos + +| Requisito | Por que é importante | +|-----------|----------------------| +| .NET 6.0 SDK (ou mais recente) | Fornece o runtime para o aplicativo console. | +| Visual Studio 2022 ou VS Code | Facilita a edição e depuração. | +| Conexão à internet (na primeira execução) | O NuGet precisa baixar o Aspose.OCR. | +| Uma imagem JPEG que você deseja processar (ex.: `ukrainian_sign.jpg`) | O arquivo fonte para o motor OCR. | + +> **Dica profissional:** Se você estiver no Linux ou macOS, o mesmo código funciona com a CLI do .NET (`dotnet new console`), então sinta‑se à vontade para pular o IDE pesado. + +--- + +## Etapa 1 – Instalar Aspose.OCR via NuGet + +Abra seu terminal (ou o Package Manager Console) e execute: + +```bash +dotnet add package Aspose.OCR +``` + +Essa única linha baixa os binários mais recentes do Aspose.OCR e todas as dependências transitivas. Não é necessário lidar manualmente com DLLs. + +--- + +## Etapa 2 – Criar o Motor OCR (O Coração da Extração) + +Agora que a biblioteca está instalada, podemos criar uma instância de `OcrEngine`. Esse objeto é responsável por **extrair texto de imagem**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Por que isso importa:** O motor encapsula os algoritmos de OCR, modelos de idioma e opções de configuração. Instanciá‑lo uma vez e reutilizá‑lo em várias imagens é eficiente em memória e rápido. + +--- + +## Etapa 3 – Carregar Imagem para OCR (E Definir o Idioma) + +O próximo passo é informar ao motor qual foto ler. É aqui que a frase **carregar imagem para OCR** entra em ação. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Caso de borda:** Se o arquivo não existir, `Image.FromFile` lança uma `FileNotFoundException`. Envolva a chamada em um bloco try‑catch para código de produção. + +--- + +## Etapa 4 – Executar OCR e Extrair Texto + +Com a imagem carregada, o motor pode agora **extrair texto de imagem**. O método `Recognize` faz o trabalho pesado. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Se tudo correr bem, `recognizedText` conterá a representação em texto simples de tudo que o motor OCR conseguiu ler. + +--- + +## Etapa 5 – Converter JPG para Texto (Juntando Tudo) + +O código que construímos até agora já **converte jpg para texto**, mas vamos encapsulá‑lo em um método elegante que você pode chamar repetidamente. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Agora você pode simplesmente fazer: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Saída esperada** (truncada para brevidade): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Se a imagem contiver texto em inglês, altere `OcrLanguage.English` e você verá a saída correspondente. + +--- + +## Etapa 6 – Lidando com Perguntas Comuns “Como Fazer OCR em Imagem” + +### 6.1 Posso fazer OCR em PNG ou BMP? + +Absolutamente. O método `Image.FromFile` suporta todos os formatos que o System.Drawing reconhece, então basta apontar o caminho para um arquivo `.png` ou `.bmp` e o restante do código permanece idêntico. + +### 6.2 E se a imagem for de baixa resolução? + +A precisão do OCR cai drasticamente abaixo de 300 dpi. Uma solução rápida é aumentar a resolução da imagem com `Graphics` antes de enviá‑la ao motor: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Preciso de licença para Aspose.OCR? + +Aspose oferece um teste gratuito com marca d'água. Para uso em produção, adquira uma licença e adicione: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Exemplo Completo Funcionando + +Abaixo está um aplicativo console completo, pronto‑para‑executar, que demonstra **como fazer OCR em imagem**, **carregar imagem para OCR**, e **converter jpg para texto** em um único pacote organizado. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Como executá‑lo** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Você deverá ver o texto extraído impresso no console, confirmando que você conseguiu **extrair texto de imagem** usando C#. + +--- + +## Armadilhas Comuns & Dicas Profissionais + +| Problema | Por que acontece | Solução | +|----------|------------------|---------| +| Saída em branco | Imagem muito escura ou com baixo contraste. | Pré‑processar com `Bitmap` para aumentar o brilho. | +| Idioma errado | Propriedade `Language` deixada no padrão inglês. | Defina explicitamente `ocrEngine.Language = OcrLanguage.Ukrainian;` (ou o seu idioma alvo). | +| Erro de falta de memória | Imagens muito grandes carregadas sem descarte. | Envolva `Image.FromFile` em um bloco `using` (como mostrado). | +| Marca d'água de licença | Executando a versão trial sem licença. | Aplique a licença comprada logo no início do `Main`. | + +--- + +## Conclusão + +Acabamos de cobrir tudo o que você precisa para **extrair texto de imagem** em C# — desde a instalação do Aspose.OCR, **carregar imagem para OCR**, até **converter jpg para texto** e lidar com cenários multilíngues. O programa de exemplo completo une todas as peças, oferecendo uma base confiável para qualquer projeto relacionado a OCR. + +A seguir, você pode explorar: + +* **Como fazer OCR em imagem** a partir de streams em vez de arquivos (use `MemoryStream`). +* Adicionar pós‑processamento **c# image to text** como correção ortográfica. +* Integrar a etapa de OCR em um pipeline maior (ex.: armazenar resultados em um banco de dados). + +Sinta‑se à vontade para experimentar diferentes idiomas, formatos de imagem e truques de pré‑processamento. OCR é tanto arte quanto ciência, e quanto mais você brincar, melhores serão os resultados. + +Feliz codificação, e que suas imagens estejam sempre legíveis! + +## Tutoriais Relacionados + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/portuguese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..2e0197984 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-05-25 +description: Como usar OCR em C# para extrair texto de arquivos de imagem. Aprenda + a reconhecer caracteres chineses de um JPG usando Aspose.OCR em alguns passos simples. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: pt +og_description: Como usar OCR em C# para extrair texto de arquivos de imagem. Este + guia mostra como reconhecer caracteres chineses de um JPG usando Aspose.OCR. +og_title: Como usar OCR em C# – Reconhecer texto chinês de JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Como usar OCR em C# – Reconhecer texto chinês de JPG +url: /pt/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Como usar OCR em C# – Reconhecer texto chinês de JPG + +Já se perguntou **como usar OCR** para extrair palavras de uma foto que você tirou com o celular? Você não está sozinho. Em muitos projetos do mundo real — pense em scanners de recibos, aplicativos de tradução ou entrada de dados automatizada — você precisará **extrair texto de imagem** rapidamente e de forma confiável. + +Neste tutorial, percorreremos um exemplo completo e executável que **reconhece texto de arquivos JPG** e ainda lida com o caso complicado de **reconhecer caracteres chineses** usando o pacote de idioma **OCR Chinese Simplified**. Ao final, você terá um aplicativo de console autônomo que imprime a string detectada no console, sem necessidade de downloads manuais adicionais. + +> **Nota rápida:** O código funciona com Aspose.OCR ≥ 23.7, que busca automaticamente os recursos de idioma na primeira utilização. Se você estiver usando uma versão mais antiga, precisará adicionar o idioma manualmente. + +## Pré-requisitos + +- .NET 6.0 SDK ou posterior (o exemplo tem como alvo .NET 6, mas .NET 5 também funciona) +- A versão recente do Visual Studio 2022 ou VS Code com a extensão C# +- Uma conexão à internet para o primeiro download de idioma +- Uma imagem JPG que contém texto em Chinês Simplificado (chamaremos de `chinese_sign.jpg`) + +É isso — sem motores OCR pesados, sem lidar com DLLs nativas. Apenas alguns comandos NuGet e algumas linhas de código. + +## Etapa 1: Instalar Aspose.OCR via NuGet + +Primeiro de tudo: precisamos da biblioteca OCR. Abra um terminal na pasta do seu projeto e execute: + +```bash +dotnet add package Aspose.OCR +``` + +Ou, se preferir a interface do Visual Studio, clique com o botão direito em **Dependencies → Manage NuGet Packages**, procure por “Aspose.OCR” e clique em **Install**. + +> **Dica profissional:** Mantenha seus pacotes atualizados. Novos pacotes de idioma e ajustes de desempenho são lançados em cada versão menor. + +## Etapa 2: Criar um Novo Projeto de Console (Se Ainda Não o Fez) + +Se você está começando do zero, crie um novo aplicativo de console: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Agora você tem um arquivo `Program.cs` pronto para o código OCR. + +## Etapa 3: Escrever o Código OCR – Reconhecer Chinês Simplificado a partir de um JPG + +Abra `Program.cs` e substitua seu conteúdo pelo seguinte. Cada linha está anotada para que você veja *por que* estamos fazendo cada passo, não apenas *o que* estamos fazendo. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### O que está acontecendo nos bastidores? + +- **`OcrEngine.Language`** informa ao Aspose qual dicionário usar. Ao escolher `ChineseSimplified`, instruímos o engine a procurar o pacote de idioma Chinês Simplificado. +- **Download na primeira vez**: Quando `Recognize` é executado, o SDK acessa o CDN da Aspose, baixa o arquivo de idioma de ≈6 MB, o armazena em cache localmente e então prossegue com o OCR. Chamadas subsequentes são instantâneas. +- **`Image.FromFile`** funciona com qualquer formato raster que o .NET possa decodificar — JPG, PNG, BMP —, permitindo que você **extraia texto de imagem** de vários tipos de arquivos, não apenas JPG. + +## Etapa 4: Executar o Aplicativo e Verificar a Saída + +Compile e execute: + +```bash +dotnet run +``` + +Você deverá ver algo como: + +``` +=== Recognized Text === +欢迎光临 +``` + +Se o console imprimir caracteres incompreensíveis ou uma string vazia, verifique novamente que: + +1. A imagem realmente contém caracteres chineses claros e de alto contraste. +2. O caminho do arquivo está correto (sem espaços extras ou extensões ausentes). +3. Sua máquina pode acessar `https://download.aspose.com` para o pacote de idioma. + +## Etapa 5: Lidando com Casos Limítrofes e Armadilhas Comuns + +### 5.1 Lidando com Imagens de Baixa Qualidade + +A precisão do OCR diminui quando a imagem de origem está borrada, ruidosa ou com iluminação ruim. Uma solução rápida é pré‑processar a imagem: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Executando em um Ambiente sem Interface Gráfica + +Se você estiver implantando em um contêiner Linux sem interface gráfica, certifique-se de que a biblioteca `libgdiplus` (necessária para `System.Drawing`) esteja instalada: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Cacheando o Pacote de Idioma Manualmente + +Você pode baixar o arquivo de idioma uma vez e apontar o Aspose para ele via a API `License`, o que elimina a chamada de rede única. Isso é útil para cenários offline. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Exemplo Completo (Tudo‑em‑Um) + +Abaixo está o programa *completo* que você pode copiar‑colar em `Program.cs`. Sem partes ocultas, sem scripts externos. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Saída Esperada + +Se o JPG contiver a frase “欢迎光临”, o console imprimirá: + +``` +=== Recognized Text === +欢迎光临 +``` + +Sinta-se à vontade para substituir a imagem por qualquer outro sinal em Chinês Simplificado, nome de rua ou rótulo de produto — o engine fará o melhor possível. + +## Conclusão + +Acabamos de abordar **como usar OCR** em C# para **extrair texto de imagem** de arquivos, especificamente enfrentando o desafio de **reconhecer caracteres chineses** em um **JPG**. Ao aproveitar o download de idioma sob demanda do Aspose.OCR, você pode manter sua implantação leve enquanto ainda suporta **OCR Chinese Simplified** pronto para uso. + +O que vem a seguir? Experimente estas ideias: + +- **Processamento em lote**: Percorra uma pasta de imagens e grave cada resultado em um CSV. +- **Combinar com APIs de tradução**: Envie a string reconhecida para o Azure Translator para aplicativos multilíngues em tempo real. +- **Explorar outros idiomas**: Troque `OcrLanguage.ChineseSimplified` por `Japanese` ou `Arabic` e veja como o mesmo código se adapta. + +Têm dúvidas sobre otimização de desempenho, licenciamento ou integração do OCR em um serviço web? Deixe um comentário abaixo — feliz codificação! + +--- + +![Captura de tela da saída do console mostrando como usar OCR em C# para reconhecer texto chinês de uma imagem JPG](ocr-chinese-demo.png "como usar a saída do console OCR") + + +## Tutoriais Relacionados + +- [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/) +- [Como Extrair Texto de Imagem Preparando Retângulos no OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/portuguese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/portuguese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..48e8649c7 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: Aprenda a fazer OCR de texto russo em C# e extrair texto de imagem com + Aspose OCR. Código passo a passo para converter imagem em texto C# rapidamente. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: pt +og_description: OCR de texto russo em C# facilitado. Aprenda a extrair texto de imagens, + converter imagem em texto C# e carregar imagem para OCR com Aspose OCR. +og_title: OCR de Texto Russo em C# – Guia Completo de Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR de Texto Russo em C# – Guia Completo Usando Aspose OCR +url: /pt/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR de Texto Russo em C# – Guia Completo Usando Aspose OCR + +Já precisou fazer OCR de texto russo em C# mas não sabia qual biblioteca confiar? Você não está sozinho. Obter caracteres limpos e legíveis a partir de uma imagem em cirílico pode parecer decifrar mensagens secretas — especialmente se o modelo de idioma correto não estiver configurado. + +Neste tutorial vamos percorrer um exemplo prático que mostra como **extrair texto de arquivos de imagem**, converter *imagem para texto C#* e lidar com as nuances do reconhecimento da língua russa usando Aspose OCR. Ao final, você terá um aplicativo console pronto‑para‑executar que carrega uma imagem para OCR, imprime a string reconhecida e fornece uma base sólida para cenários mais avançados. + +## O que você vai aprender + +- Como instalar e configurar **Aspose OCR C#** para suporte ao idioma russo. +- Os passos exatos para **carregar imagem para OCR** e chamar o motor. +- Dicas para lidar com armadilhas comuns, como recursos de idioma ausentes ou digitalizações borradas. +- Formas de estender a solução, como processamento em lote de vários arquivos ou ajuste de limites de confiança. + +Não é necessário ter experiência prévia com Aspose; apenas um conhecimento básico de C# e .NET já é suficiente. + +## Pré‑requisitos + +Antes de mergulharmos, certifique‑se de que você tem o seguinte: + +1. **.NET 6.0** (ou superior) SDK instalado – o código funciona tanto no .NET Core quanto no .NET Framework. +2. **Visual Studio 2022** (ou qualquer IDE de sua preferência). +3. Um pacote NuGet **Aspose.OCR for .NET** – você pode obter uma chave de avaliação gratuita no site da Aspose. +4. Um arquivo de modelo de idioma **russo** (`rus.traineddata`) – faça o download na página de recursos da Aspose e coloque‑o em uma pasta que será referenciada mais adiante. +5. Uma imagem de exemplo (`russian_doc.png`) contendo texto cirílico nítido. + +Tem tudo isso? Ótimo — vamos começar. + +## Etapa 1: Configurar o Projeto e Instalar o Aspose OCR + +Primeiro, crie um novo projeto console: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Agora adicione o pacote Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Dica profissional:** Se você estiver usando uma licença de avaliação, mantenha o arquivo `Aspose.Total.lic` à mão; você o carregará no código para evitar marcas d’água. + +Com o pacote instalado, abra `Program.cs`. Você verá o método `Main` padrão — substitua seu conteúdo pelo esqueleto que vamos construir. + +## Etapa 2: Configurar o Motor OCR para o Idioma Russo + +O coração da operação é o objeto `OcrEngine`. Precisamos informar duas coisas: qual idioma reconhecer e onde encontrar os arquivos de modelo de idioma. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Por que isso importa:** Se você omitir `Language = OcrLanguage.Russian`, o motor usará o inglês por padrão, e quaisquer caracteres cirílicos aparecerão como símbolos incompreensíveis. O `ResourceFolder` aponta para o diretório que contém o arquivo `rus.traineddata`; sem ele, o Aspose lança uma exceção *resource not found*. + +## Etapa 3: Carregar a Imagem para OCR + +Agora precisamos **carregar imagem para OCR**. O Aspose OCR trabalha com `System.Drawing.Image`, portanto você pode passar qualquer formato suportado (PNG, JPEG, BMP, etc.). Certifique‑se de que o caminho do arquivo esteja correto; caminhos relativos funcionam bem se a imagem ficar ao lado do executável. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Caso extremo:** Se a imagem for grande (mais de 5 MB) pode ser interessante reduzi‑la primeiro. A precisão do OCR cai quando o DPI está muito baixo, mas arquivos enormes podem gerar pressão de memória. Um redimensionamento rápido pode ser feito com `Graphics` se necessário. + +## Etapa 4: Reconhecer o Texto – De Imagem para Texto no estilo C# + +Com o motor configurado e a imagem carregada, o reconhecimento propriamente dito é uma única chamada: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Ao executar o programa (`dotnet run`), você deverá ver algo como: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Se a saída parecer lixo, verifique novamente: + +- O arquivo `rus.traineddata` está presente em `ResourceFolder`. +- A imagem não está muito borrada; considere aplicar um filtro de binarização simples antes do OCR. +- A configuração de idioma está realmente `OcrLanguage.Russian`. + +## Etapa 5: Ajustes Finos e Armadilhas Comuns + +### Ajustando o Limite de Confiança + +O Aspose OCR devolve um valor de confiança por caractere internamente. Embora a API não exponha isso diretamente, você pode habilitar **saída detalhada** para ver quais palavras têm baixa confiança: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Se notar reconhecimentos errôneos frequentes, experimente: + +- **Pré‑processamento**: Converta a imagem para escala de cinza, aumente o contraste ou aplique um filtro mediano. +- **Configurações de DPI**: Garanta que a imagem tenha pelo menos 300 DPI para scripts cirílicos. + +### Processamento em Lote de Múltiplas Imagens + +Se precisar **extrair texto de arquivos de imagem** em massa, envolva a lógica de reconhecimento em um loop: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Agora cada PNG gera seu próprio arquivo `.txt` — útil para arquivamento de documentos. + +### Manipulando Saída Unicode + +Caracteres cirílicos são Unicode, portanto certifique‑se de que a codificação do console possa exibí‑los: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Coloque esta linha logo após o início do método `Main`. Sem ela, você pode ver pontos de interrogação (`?`) em vez de letras russas. + +## Exemplo Completo Funcional + +A seguir está o código completo, pronto‑para‑executar. Copie‑e cole em `Program.cs`, ajuste os caminhos e está tudo pronto. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Saída esperada** (supondo que a imagem de exemplo contenha “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Se aparecer algo diferente, revise as dicas de solução de problemas na Etapa 5. + +## Conclusão + +Agora você tem um exemplo sólido, de ponta a ponta, de como **fazer OCR de texto russo** em C# usando Aspose OCR. Desde a instalação da biblioteca, configuração do modelo de idioma russo, carregamento da imagem e conversão para texto Unicode limpo, tudo está coberto. + +Lembre‑se, a chave para um OCR confiável é material de origem de qualidade: fontes nítidas, DPI adequado e os recursos de idioma corretos. Depois de dominar o básico, você pode expandir para processamento em lote, integrar com armazenamento em nuvem ou até combinar com pós‑processamento de IA para correção ortográfica. + +### O que vem a seguir? + +- Explore opções avançadas do **aspose ocr c#** como análise de layout ou saída em PDF. +- Combine isso com fluxos de **extrair texto de imagem** em Azure Functions para processamento serverless. +- Experimente outros idiomas — basta trocar `OcrLanguage.Russian` por `OcrLanguage.English` ou outro código suportado. + +Tem dúvidas ou uma imagem complicada que não colabora? Deixe um comentário abaixo e feliz codificação! + +![ocr russian text example](ocr-russian-example.png){alt="exemplo de texto OCR em russo"} + +## Tutoriais Relacionados + +- [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 em imagem com Aspose OCR para múltiplos idiomas](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Extrair Texto de Imagem Usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/portuguese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..b07efde86 --- /dev/null +++ b/ocr/portuguese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: reconhecer texto de imagem usando Aspose OCR em C#. Aprenda como carregar + a imagem para OCR, definir o idioma do OCR, criar o mecanismo OCR e extrair texto + de um TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: pt +og_description: Reconheça texto de imagem usando Aspose OCR em C#. Este tutorial mostra + como criar o mecanismo OCR, carregar a imagem para OCR, definir o idioma do OCR + e extrair texto de um TIFF. +og_title: reconheça texto de imagem com Aspose OCR – Guia Completo de C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Reconheça texto de imagem com Aspose OCR – Guia Completo em C# +url: /pt/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconhecer texto de imagem com Aspose OCR – Guia Completo em C# + +Já precisou **reconhecer texto de imagem** mas não sabia qual biblioteca ofereceria velocidade e precisão? Você não está sozinho. Em muitos projetos de processamento de faturas ou arquivamento, o maior ponto crítico é obter texto limpo e pesquisável a partir de arquivos TIFF sem escrever um analisador personalizado. + +A verdade é que o Aspose OCR para .NET torna todo esse fluxo muito simples. Neste guia vamos percorrer tudo o que você precisa — instalar o pacote, **criar o motor OCR**, carregar um TIFF, definir o idioma do OCR e, finalmente, **extrair texto de TIFF**. Ao final, você terá um aplicativo console pronto‑para‑executar que pode **reconhecer texto de imagem** em um piscar de olhos. + +## Pré‑requisitos + +- .NET 6.0 ou superior (o código funciona também com .NET Core e .NET Framework) +- Visual Studio 2022 (ou qualquer IDE de sua preferência) +- Pacote NuGet Aspose.OCR (suporte a GPU requer o add‑on `Aspose.OCR.Gpu`) +- Uma GPU com suporte a CUDA se você quiser velocidade extra (opcional, mas recomendado) + +> **Dica de especialista:** Se você não tem uma GPU, basta omitir a linha `GpuDevice` que o motor retornará automaticamente ao uso da CPU. + +## Etapa 1: Instalar Aspose OCR e Criar o Motor OCR + +Primeiro, adicione os pacotes necessários via NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Agora podemos **criar o motor OCR**. Este objeto é o coração do processo; ele contém configurações como o dispositivo de execução e limites de memória. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Por que isso importa:** Ao vincular o motor a uma GPU você reduz drasticamente o tempo necessário para **reconhecer texto de imagem**, especialmente em lotes grandes de TIFFs de alta resolução. + +## Etapa 2: Carregar Imagem para OCR + +Em seguida, precisamos **carregar a imagem para OCR**. O Aspose.OCR trabalha com `System.Drawing.Image`, portanto qualquer formato suportado pelo GDI+ (incluindo TIFF multipágina) funciona. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Se você estiver lidando com um TIFF multipágina, pode percorrer as páginas usando `image.SelectActiveFrame`, mas na maioria dos cenários uma única chamada já basta. + +## Etapa 3: Definir o Idioma do OCR + +O motor não sabe magicamente qual idioma está sendo escaneado. **Defina o idioma do OCR** antes de executar o reconhecedor; caso contrário, você receberá muita saída corrompida. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Sabia que?** Trocar de idioma em tempo de execução é barato — você pode até processar um documento com múltiplos idiomas alterando essa propriedade entre as páginas. + +## Etapa 4: Executar o Reconhecimento – Reconhecer Texto de Imagem + +Agora a parte divertida: realmente **reconhecer texto de imagem**. O método `Recognize` devolve uma string simples com todos os caracteres detectados. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Se precisar de pontuações de confiança ou caixas delimitadoras, pode usar a sobrecarga que retorna um objeto `OcrResult`, mas para a maioria das tarefas de extração a string simples é suficiente. + +## Etapa 5: Extrair Texto de TIFF (e lidar com arquivos multipágina) + +Quando a fonte é um TIFF contendo várias páginas, você desejará repetir as etapas 2‑4 para cada quadro. Aqui está um loop rápido que **extrai texto de TIFF** página por página: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +O código acima imprime o texto extraído para cada página, facilitando o encaminhamento dos resultados para um banco de dados ou um índice de busca. + +## Etapa 6: Exibir ou Persistir o Texto Extraído + +Por fim, vamos **exibir o texto extraído** e, opcionalmente, gravá‑lo em um arquivo para processamento posterior. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Executar o programa deve exibir os caracteres reconhecidos e criar `extracted_text.txt` ao lado do seu TIFF de origem. + +--- + +## Perguntas Frequentes & Casos de Borda + +- **E se minha GPU não for detectada?** + Remova a linha `GpuDevice`; o motor mudará automaticamente para o modo CPU. O desempenho será mais lento, mas os resultados permanecem precisos. + +- **Posso processar arquivos PNG ou JPEG?** + Claro — `Image.FromFile` funciona com qualquer formato suportado pelo System.Drawing, então você pode **carregar a imagem para OCR** independentemente da extensão. + +- **Como lidar com digitalizações de baixa resolução?** + Aumente `ocrEngine.PreprocessOptions.Dpi` antes de chamar `Recognize`. DPI maior fornece mais pixels ao motor, melhorando a precisão. + +- **Existe um limite para o tamanho do TIFF?** + A propriedade `GpuMemoryLimit` limita o uso da GPU. Se o limite for atingido, o motor recairá para a CPU nas páginas restantes. + +--- + +## Conclusão + +Agora você tem um trecho completo, pronto para produção, que **reconhece texto de imagem** usando Aspose OCR em C#. O tutorial abordou como **criar o motor OCR**, **carregar a imagem para OCR**, **definir o idioma do OCR** e **extrair texto de TIFF** — tudo aproveitando a aceleração por GPU para velocidade. + +A partir daqui, você pode: + +- Experimentar diferentes idiomas (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, etc.). +- Integrar a saída em um índice ElasticSearch pesquisável. +- Adicionar pós‑processamento (correção ortográfica, limpeza com regex) para melhorar a qualidade dos dados. + +Teste em seu próprio lote de faturas, ajuste os limites de memória e veja o desempenho do OCR decolar. Boa codificação! + +## Tutoriais Relacionados + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..02d41d5a5 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 со списками. Повышайте продуктивность и извлечение данных в ваших приложениях. +### [Создание OCR‑движка в C# – Полное руководство](./create-ocr-engine-in-c-complete-guide/) +Полное руководство по созданию OCR‑движка в C# с использованием Aspose.OCR, включая настройку, обучение и интеграцию. ### Распространенные случаи использования - **Извлечение текстовых изображений** из отсканированных счетов для автоматического бухгалтерского учета. @@ -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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/russian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..c048b5768 --- /dev/null +++ b/ocr/russian/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Создайте OCR‑движок на C# и узнайте, как проверить режим оценки и статус + лицензии в нескольких строках кода. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: ru +og_description: Создайте OCR‑движок на C# и мгновенно посмотрите, как определить режим + оценки и отобразить статус лицензии. +og_title: Создание OCR‑движка на C# – пошаговое руководство +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Создание OCR‑движка на C# — Полное руководство +url: /ru/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Создание OCR Engine в C# – Полное руководство + +Когда‑нибудь задумывались, как **создавать OCR engine** объекты в C# без бесконечного поиска в документации? Вы не одиноки. Многие разработчики сталкиваются с проблемой, когда нужно запустить OCR engine, проверить, работает ли он в режиме пробной версии, и отобразить статус лицензии пользователям. + +В этом руководстве мы пройдём через лаконичный, сквозной пример, который **создаёт OCR engine**, проверяет его **режим оценки OCR engine**, и выводит дружелюбное сообщение о состоянии лицензии. К концу вы получите готовое к запуску консольное приложение и чёткую концепцию работы с лицензированием OCR в своих проектах. + +## Что вы узнаете + +- Как создать экземпляр `OcrEngine` (ядро любого OCR‑процесса). +- Почему важно определять **режим оценки** для соответствия требованиям и удобства пользователя. +- Лучший способ **проверить статус лицензии OCR** и реагировать на неожиданные состояния. +- Распространённые подводные камни — null‑ссылки, обработка исключений и несоответствия версий. + +Никаких внешних инструментов, кроме уже установленного OCR SDK, не требуется. Если вы знакомы с базовым синтаксисом C#, вы готовы к работе. + +## Предварительные требования + +- .NET 6.0 или новее (код компилируется как в .NET Core, так и в .NET Framework). +- OCR SDK, который предоставляет класс `OcrEngine` с свойством `IsEvaluation` (например, гипотетический `MyOcrSdk`). +- Текстовый редактор или IDE (Visual Studio, VS Code, Rider — выбирайте своё). + +Это всё. Погружаемся. + +## Шаг 1: Создайте новый консольный проект + +Сначала создайте свежий консольный проект, чтобы запускать код в изоляции. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Откройте сгенерированный `Program.cs`. Мы заменим его содержимое полным примером, который **создаёт OCR engine** экземпляры и обрабатывает лицензирование. + +## Шаг 2: Подключите пространство имён OCR SDK + +Предполагая, что SDK подключён через NuGet (`MyOcrSdk` — заполнитель), добавьте директиву `using` в начало файла. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Если пакет ещё не добавлен, выполните: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Держите версию SDK актуальной; новые релизы часто улучшают определение режима оценки. + +## Шаг 3: Создайте экземпляр OCR Engine + +Теперь мы наконец **создаём OCR engine** объекты. Это сердце любого OCR‑процесса — по сути, мозг, который позже будет читать изображения. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Почему этот шаг критичен? `OcrEngine` инкапсулирует всю конфигурацию, языковые пакеты и данные лицензии. Без него нельзя обрабатывать изображения или запрашивать флаг оценки. + +> **Side note:** Некоторые SDK позволяют передать объект конфигурации в конструктор (например, язык, DPI). Если нужны пользовательские настройки, измените строку соответствующим образом. + +## Шаг 4: Определите режим оценки OCR Engine + +Большинство поставщиков OCR поставляют пробную версию, работающую в **режиме оценки**, пока не будет предоставлен действительный лицензионный ключ. Знание того, что вы находитесь в режиме пробной версии, позволяет отображать соответствующие подсказки UI или ограничивать определённые функции. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Свойство `IsEvaluation` возвращает `true`, когда движок не лицензирован или использует ограниченную по времени пробную версию. Это быстрый и надёжный способ защищать премиум‑функции. + +### Что делать, если свойства нет? + +В более старых версиях SDK может быть метод `GetLicenseInfo()`. В этом случае нужно проверить возвращаемый объект на наличие флага `IsTrial`. Всегда обращайтесь к журналу изменений SDK при обновлении. + +## Шаг 5: Выведите текущий статус лицензии + +Наконец, покажем пользователю, лицензирован ли движок или всё ещё находится в пробном режиме. Достаточно простой `Console.WriteLine`, но вы можете адаптировать его для GUI‑приложений. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Тернарный оператор делает код лаконичным, а сообщения достаточно понятны как конечным пользователям, так и разработчикам, читающим логи. + +## Полный рабочий пример + +Объединив всё вместе, получаем автономную программу, которую можно скопировать в `Program.cs` и запустить командой `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Ожидаемый вывод + +- **Пробная сборка:** + `Running in evaluation mode – limited functionality.` + +- **Лицензированная сборка:** + `Licensed – full OCR capabilities enabled.` + +Если SDK бросит исключение (например, отсутствует нативная DLL), блок `catch` выведет полезное сообщение об ошибке вместо падения всего приложения. + +## Обработка граничных случаев и распространённых подводных камней + +### 1. Null‑экземпляры движка + +Хотя конструктор обычно возвращает валидный объект, некоторые SDK могут вернуть `null`, если отсутствуют необходимые нативные зависимости. Защититесь от этого: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Истечение срока действия лицензии во время работы + +Пробная лицензия может истечь в середине сессии. Периодически пере‑проверяйте `IsEvaluation`, если ваше приложение работает длительное время. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Разные имена свойств в разных версиях + +В старых релизах может быть `engine.EvaluationMode` или `engine.License.IsTrial`. При обновлении ищите в примечаниях к выпуску изменения, нарушающие совместимость. + +### 4. Многопоточные сценарии + +Если вы создаёте несколько OCR‑рабочих, инстанцируйте **по одному OCR engine на поток**, если только SDK явно не поддерживает потокобезопасное совместное использование. Совместное использование одного движка может привести к состояниям гонки и неверным чтениям лицензии. + +## Pro‑советы для продакшн‑использования + +- **Кешируйте статус лицензии** после первой проверки, чтобы избежать лишних вызовов свойства. +- **Логируйте лицензионный ключ** (замаскированный) при старте для аудита — это помогает службе поддержки диагностировать проблемы с лицензией. +- **Предоставьте переключатель UI**, который информирует пользователей о пробном режиме и предлагает кнопку «Купить лицензию». +- **Автоматизируйте продление лицензии** с помощью API активации SDK, если оно доступно, чтобы обеспечить бесшовный пользовательский опыт. + +## Заключение + +Мы только что **создали OCR engine** объекты в несколько строк, проверили **режим оценки OCR engine** и вывели чёткое сообщение о **статусе лицензии OCR**. Полный пример работает «из коробки», корректно обрабатывает ошибки и подчёркивает «почему» каждого шага — чтобы вы могли адаптировать его под настольные, веб‑ или серверные сценарии. + +Дальше вы можете изучить: + +- Передачу изображений в `engine.Recognize` и поддержку нескольких языков. +- Использование **check OCR license** API для программной активации приобретённого ключа. +- Интеграцию с UI‑фреймворками (WinForms, WPF, MAUI) для отображения значков лицензии. + +Попробуйте, и у вас будет надёжный фундамент OCR, готовый к любой задаче. Приятного кодинга! + +## Related Tutorials + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/ocr-optimization/_index.md b/ocr/russian/net/ocr-optimization/_index.md index 64f6e406b..c18ddd3c0 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 в виде документов с помощью этого всестороннего пошагового руководства. +### [Предобработка изображения для OCR – Полное руководство по Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Полное руководство по предобработке изображений для OCR с использованием Aspose в C#. Улучшите точность распознавания. + ## Часто задаваемые вопросы **Q: Могу ли я извлекать текст из файлов изображений, содержащих несколько языков?** diff --git a/ocr/russian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/russian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..96f88800f --- /dev/null +++ b/ocr/russian/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Предобработайте изображение для OCR с помощью Aspose, чтобы повысить + точность распознавания, и выполните OCR для JPEG‑файлов. Узнайте, как извлекать + текст с помощью Aspose в понятном пошаговом руководстве. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: ru +og_description: Предобработайте изображение для OCR с помощью Aspose, чтобы повысить + точность распознавания. Следуйте этому руководству, чтобы выполнить OCR на JPEG + и извлечь текст с использованием Aspose в C#. +og_title: Предобработка изображения для OCR – учебник Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Предобработка изображения для OCR – Полное руководство Aspose C# +url: /ru/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Предобработка изображения для OCR – Полное руководство по Aspose C# Guide + +Задумывались ли вы когда‑нибудь, как **preprocess image for OCR**, чтобы текст получался чистым каждый раз? Вы не одиноки — разработчики постоянно борются с шумными сканами, JPEG с низким контрастом и непредсказуемым освещением. Хорошая новость? С несколькими умными настройками вы можете **improve OCR accuracy** значительно, и Aspose делает это без усилий. + +В этом руководстве мы пройдем реальный пример, показывающий, как **run OCR on JPEG** изображения, применить пользовательский конвейер обработки изображений и, наконец, **extract text using Aspose**. К концу вы получите готовый к вставке фрагмент C#, который можно добавить в любой проект .NET. + +## Что вы узнаете + +- Почему предобработка важна и какие фильтры дают наибольший эффект. +- Как настроить `ImageProcessingOptions` из Aspose.OCR для исправления наклона, удаления шума, бинаризации и повышения контраста. +- Точный код, необходимый для **run OCR on JPEG** файлов и получения чистого текста. +- Советы и подводные камни, позволяющие вашему конвейеру OCR оставаться надёжным в продакшене. + +Предыдущий опыт работы с Aspose не требуется; достаточно базовых знаний C# и Visual Studio (или вашей любимой IDE). Приступим. + +![Preprocess image for OCR example](preprocess-ocr.png "Preprocess image for OCR") + +## Шаг 1: Настройка движка Aspose.OCR – Preprocess Image for OCR + +Во-первых. Нам нужен экземпляр `OcrEngine`, и мы должны указать, какой язык ожидаем. В большинстве случаев по умолчанию — English, но вы можете заменить его на French, German и т.д., изменив перечисление `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Why this matters:** Движок — сердце операции; без него вы не сможете применить ни один из фильтров изображения, которые действительно **preprocess image for OCR**. Считайте его кухней, где смешиваются все ингредиенты. + +## Шаг 2: Создание пользовательского конвейера обработки изображений – Improve OCR Accuracy + +Теперь начинается самая интересная часть. Aspose позволяет соединять несколько фильтров последовательно. Ниже мы включаем четыре самых эффективных: + +1. **Deskew** – выравнивает наклонённые документы (по умолчанию максимум 5°). +2. **Denoise** – сглаживает зернистый фон. +3. **Binarize** – преобразует изображение в черно‑белое с использованием порога. +4. **ContrastBoost** – делает бледные символы более заметными. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** Если ваши исходные изображения уже чёткие, вы можете уменьшить `Strength` или полностью отключить фильтр. Чрезмерная обработка иногда стирает слабые символы, поэтому экспериментируйте с реальными образцами. + +## Шаг 3: Загрузка JPEG (или любого изображения) и запуск OCR – Run OCR on JPEG + +Aspose работает с любым форматом изображения, который может читать .NET — JPEG, PNG, BMP и т.д. Ниже показано, как передать файл JPEG в движок и запустить процесс распознавания. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Why JPEG?** Сжатие JPEG часто вводит артефакты, сбивающие OCR. Наш конвейер предобработки, особенно шаги denoise и binarize, смягчают эти проблемы, позволяя вам **run OCR on JPEG** с уверенностью. + +## Шаг 4: Вывод распознанного текста – Extract Text Using Aspose + +Наконец, мы просто выводим текст в консоль, файл или любой downstream сервис. Для демонстрации достаточно консоли. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +При запуске программы вы должны увидеть что‑то вроде: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Если вывод выглядит искажённым, вернитесь к **Step 2** и отрегулируйте настройки фильтров. Небольшие корректировки часто дают большой прирост в **improve OCR accuracy**. + +## Распространённые граничные случаи и как с ними справиться + +| Ситуация | Рекомендуемая настройка | +|-----------|----------------------| +| **Очень тёмные изображения** | Увеличьте `ContrastBoost.Level` до 1.5 или выше. | +| **Наклон > 5°** | Увеличьте `DeskewOptions.MaxAngle` (например, 10.0) или предварительно поверните изображение вручную. | +| **Цветной текст на цветном фоне** | Используйте `BinarizeOptions` с пользовательским порогом или переключитесь на `AdaptiveBinarizeOptions`. | +| **Большие файлы ( > 5 MB )** | Сначала загрузите изображение в `MemoryStream`, чтобы избежать проблем с блокировкой файла. | + +Эти настройки делают ваш конвейер гибким и готовым к будущему, особенно когда вам нужно **extract text using Aspose** из разных источников. + +## Полный рабочий пример – все шаги в одном месте + +Ниже представлен полный готовый к копированию и вставке код программы. Он компилируется с .NET 6+ и требует только пакет `Aspose.OCR` из NuGet. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Сохраните как `Program.cs`, добавьте пакет Aspose.OCR (`dotnet add package Aspose.OCR`) и выполните `dotnet run`. Вы увидите очищенный текст, выведенный в консоль. + +## Итоги – почему этот подход работает + +- **Preprocess image for OCR**: Конвейер удаляет наиболее распространённые источники ошибок (наклон, шум, низкий контраст). +- **Improve OCR accuracy**: Каждый фильтр настроен для повышения отношения сигнал‑к‑шуму, которое видит движок. +- **Run OCR on JPEG**: Даже сжатые изображения становятся разборчивыми после исправления наклона и бинаризации. +- **Extract text using Aspose**: Метод `Recognize` возвращает обычную строку, готовую для любой downstream логики. + +В совокупности эти шаги дают надёжное OCR‑решение уровня production, используя всего несколько строк кода. + +## Следующие шаги и связанные темы + +- **Batch processing** – Перебрать папку с изображениями и записать каждый результат в файл `.txt`. +- **Language packs** – Заменить `OcrLanguage.English` на `OcrLanguage.Spanish` или добавить пользовательские словари. +- **PDF extraction** – Скомбинировать Aspose.OCR с Aspose.PDF для извлечения текста напрямую из отсканированных PDF. +- **Performance tuning** – Запустить движок параллельно с помощью `Parallel.ForEach` для больших нагрузок. + +Не стесняйтесь экспериментировать со значениями фильтров, пробовать разные форматы изображений или соединять дополнительные фильтры Aspose, такие как `SharpnessOptions`. Возможности безграничны, как только вы освоите основы. + +--- + +*Счастливого кодинга! Если возникнут проблемы, оставьте комментарий ниже, и мы разберём их вместе.* + +## Связанные руководства + +- [Предобработка изображения OCR с фильтрами Aspose.OCR для .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Извлечение текста из изображения – оптимизация 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/text-recognition/_index.md b/ocr/russian/net/text-recognition/_index.md index cbc7a99c9..f59fafc88 100644 --- a/ocr/russian/net/text-recognition/_index.md +++ b/ocr/russian/net/text-recognition/_index.md @@ -55,9 +55,24 @@ url: /ru/net/text-recognition/ Раскройте потенциал оптического распознавания символов в .NET с помощью Aspose.OCR. Извлекайте текст из PDF-файлов без особых усилий. Загрузите сейчас и получите беспрепятственную интеграцию. ### [Распознать таблицу в распознавании изображений OCR](./recognize-table/) Раскройте потенциал Aspose.OCR для .NET с помощью нашего подробного руководства по распознаванию таблиц в распознавании изображений OCR. +### [Распознать текст с изображения с помощью Aspose OCR – Полное руководство на C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Полное руководство по распознаванию текста с изображений в C# с использованием Aspose OCR. +### [Как использовать OCR в C# – Распознавание китайского текста из JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Узнайте, как с помощью Aspose.OCR в C# распознавать китайский текст на изображениях JPG. +### [OCR русский текст в C# – Полное руководство по использованию Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Полное руководство по распознаванию русского текста в C# с помощью Aspose OCR, охватывающее настройку и примеры кода. +### [Извлечь текст из изображения в C# – Полное руководство Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Полное руководство по извлечению текста из изображений в C# с использованием Aspose OCR. +### [Извлечение текста из изображения в ASP.NET Core Minimal API – Полное руководство](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Полное руководство по извлечению текста из изображений с помощью ASP.NET Core Minimal API и Aspose OCR. +### [c# OCR руководство: извлечение текста из PNG‑чеков с Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Полное руководство по извлечению текста из PNG‑чеков в C# с использованием Aspose OCR. +### [Преобразование TIFF в текст в C# – Полное руководство по пакетному OCR](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Полное руководство по пакетному конвертированию TIFF‑изображений в текст с использованием 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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/russian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..cb8e3d7ab --- /dev/null +++ b/ocr/russian/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: Учебник по OCR на C#, показывающий, как загрузить файл изображения в + C# и распознать текст PNG с чека с помощью Aspose OCR – пошаговое руководство. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: ru +og_description: Учебник по OCR на C#, который пошагово покажет, как загрузить файл + изображения в C# и распознать текст PNG с чека с помощью Aspose OCR. +og_title: c# OCR tutorial – Извлечение текста из PNG‑чеков +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR tutorial: Извлечение текста из PNG‑чеков с помощью Aspose' +url: /ru/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – Извлечение текста из PNG‑чеков с помощью Aspose + +Когда‑нибудь вам нужен был **c# OCR tutorial**, который действительно справляется с задачей без бесконечного гугления? Вы попали по адресу. В этом руководстве мы **load image file c#**, **recognize png text**, и **read receipt OCR** результаты, показывая при этом, как **perform OCR image** обработка с Aspose OCR. + +Мы начнём с установки необходимого пакета NuGet, пройдёмся по каждой строке кода и завершим аккуратным дампом JSON, который можно сразу передать в ваш следующий конвейер данных. Без лишних слов, только практическое готовое решение. + +## Что вы узнаете + +- Как настроить Aspose OCR в проекте .NET 6 (или более новой версии). +- Точные шаги для **load an image file c#** и передачи его движку. +- Как **recognize png text** из изображения чека и захватить результат. +- Способы **read receipt OCR** вывода в красиво отформатированном JSON. +- Советы по **perform OCR image** операциям с различными типами файлов и обработке распространённых проблем. + +**Требования** +- Visual Studio 2022 (или любая IDE по вашему выбору). +- .NET 6 SDK или новее. +- Изображение чека в формате PNG под рукой (мы будем называть его `receipt.png`). + +Если у вас есть всё это, давайте погрузимся. + +![c# OCR tutorial screenshot](ocr-demo.png "c# OCR tutorial result showing JSON output") + +## c# OCR Tutorial – Настройка движка Aspose OCR + +Для начала нам нужна библиотека Aspose OCR. Откройте терминал в папке решения и выполните: + +```bash +dotnet add package Aspose.OCR +``` + +Эта единственная команда загрузит всё необходимое, включая нативные бинарные файлы для декодирования изображений. После установки создайте новый консольный проект или добавьте код в существующий. + +### Почему Aspose? + +Aspose OCR поддерживает более 30 языков, работает офлайн и возвращает богатый объект `OcrResult` — идеально подходит для задач **perform OCR image**, где требуется больше, чем простой текст. + +## Load image file c# и подготовка чека + +Теперь, когда библиотека готова, давайте **load image file c#**. Класс `System.Drawing.Image` выполняет основную работу, но вы также можете использовать `SkiaSharp`, если предпочитаете кросс‑платформенную альтернативу. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro tip:** Оберните `Image` в оператор `using` (как показано), чтобы быстро освобождать нативные ресурсы — особенно важно, когда вы **perform OCR image** на многих файлах в цикле. + +## Recognize PNG text с Aspose + +С изображением в памяти движок теперь может **recognize png text**. Aspose возвращает `OcrResult`, содержащий как необработанную строку, так и подробные данные о каждом распознанном слове. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Зачем вызывать `RecognizeWithResult` вместо более простого `Recognize`? Первый предоставляет доступ к оценкам уверенности, ограничивающим рамкам и разрывам строк — удобно, если позже понадобится **read receipt OCR** для извлечения позиций строки. + +## Read receipt OCR Result в формате JSON + +Большинство downstream‑систем любят JSON, поэтому давайте сериализуем `OcrResult`. Сериализатор `System.Text.Json` корректно обрабатывает сложные объекты, и мы включим отступы для удобочитаемости. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Получившийся JSON выглядит примерно так (сокращён для краткости): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Теперь вы можете передать `jsonResult` в базу данных, очередь сообщений или просто записать его в журнал для отладки. + +## Perform OCR Image Processing и вывод результата + +Наконец, выведите JSON в консоль. В реальном приложении вы, вероятно, запишете его в файл или отправите по HTTP, но консоль упрощает проверку корректности работы. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Запустите программу (`dotnet run`), и вы увидите красиво отформатированный JSON в выводе. Если изображение чека чёткое, текст будет точным; если нет, рассмотрите возможность увеличения разрешения изображения или применения предобработки (например, преобразование в градации серого, повышение контраста) перед передачей в движок. + +### Обработка распространённых граничных случаев + +| Ситуация | Что делать | +|-----------|------------| +| **Изображение размыто** | Предобработайте с помощью `System.Drawing`, чтобы резкостить или увеличить DPI. | +| **Чек содержит несколько языков** | Set `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Обработка больших пакетов** | Повторно используйте один экземпляр `OcrEngine`; меняйте только `Image` на каждой итерации. | +| **Нагрузка на память** | Своевременно освобождайте объекты `Image` и рассмотрите `await Task.Run` для асинхронных конвейеров. | + +Эти настройки сохраняют ваш рабочий процесс **perform OCR image** надёжным, даже если ввод не идеален. + +## Итоги + +Поздравляем — вы только что завершили **c# OCR tutorial**, который загружает изображение, **recognizes png text**, и **reads receipt OCR** вывод в чистом JSON. Основные шаги (настройка движка, загрузка изображения, выполнение OCR, сериализация и вывод) образуют прочную основу, которую можно расширить на счета, паспорта или любые другие сканированные документы. + +### Что дальше? + +- Экспериментируйте с **load image file c#** с использованием `SkiaSharp` для настоящей кросс‑платформенной поддержки. +- Углубитесь в `OcrResult.Words`, чтобы извлекать позиции строк, цены и даты — идеально для приложений учёта расходов. +- Скомбинируйте этот урок с Azure Functions или AWS Lambda, чтобы создать безсерверный API обработки чеков. + +Не стесняйтесь менять код, добавлять больше изображений или даже переключаться на другой языковой пакет. Мир OCR полон сюрпризов, и теперь у вас есть инструменты для их исследования. + +Счастливого кодинга, и пусть ваши чеки всегда читаемы! + +## Связанные уроки + +- [Извлечение текста из изображения C# с выбором языка с помощью Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Извлечение текста из изображения — оптимизация OCR с Aspose.OCR для .NET](/ocr/english/net/ocr-optimization/) +- [Как использовать OCR — распознавание изображения без обнаружения текстовой области](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/russian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..6a7c4d673 --- /dev/null +++ b/ocr/russian/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Конвертировать TIFF в текст с помощью Aspose.OCR на C#. Узнайте о пакетном + преобразовании изображений в текст и эффективно извлекайте текст из файлов TIFF. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: ru +og_description: Конвертировать TIFF в текст с помощью Aspose.OCR. Это руководство + демонстрирует пакетное преобразование изображений в текст и показывает, как извлечь + текст из файлов TIFF за несколько строк кода на C#. +og_title: Преобразование TIFF в текст на C# – Полное руководство по пакетному OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Конвертация TIFF в текст на C# – Полное руководство по пакетному OCR. +url: /ru/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Конвертация TIFF в текст на C# – Полное руководство по пакетному OCR + +Когда‑нибудь вам нужно было **конвертировать TIFF в текст**, но вы не знали, с чего начать? Вы не одиноки — многие разработчики сталкиваются с пакетным OCR при работе со сканированными документами. В этом руководстве мы пройдем практическое решение, которое **извлекает текст из TIFF** файлов с помощью Aspose.OCR, и сделаем это параллельно, чтобы большие папки обрабатывались за секунды. + +Мы также коснёмся лучших практик **batch image to text conversion**, так что к концу у вас будет переиспользуемый фрагмент кода, который преобразует целый каталог сканированных изображений в аккуратные файлы *.txt* — идеально подходит для индексации, поиска или передачи в последующий анализ. + +## Что понадобится + +- **.NET 6.0** или новее (код также компилируется на .NET Framework) +- NuGet‑пакет **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Папка, содержащая один или несколько файлов *.tif* (классический формат сканирования TIFF) +- Ваш любимый IDE (Visual Studio, VS Code, Rider — что угодно) + +Вот и всё. Никаких внешних сервисов, никаких API‑ключей, только чистый C# и Aspose. + +![Скриншот обработки TIFF‑файла и полученного текстового файла](/images/ocr-result.png "Результат OCR, показывающий вывод конвертированного TIFF в текст") + +*(Alt text: Скриншот, показывающий конвертированный TIFF в текстовый вывод на экране)* + +## Шаг 1: Настройка OCR‑движка — Конвертация TIFF в текст + +Прежде всего, нам нужен экземпляр `OcrEngine`, который знает, что должен читать английские символы. Движок — сердце конвертации; правильная настройка обеспечивает надёжные результаты. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Почему это важно:* +Aspose.OCR поддерживает десятки языков. Если вы работаете с многоязычными сканами, просто измените `OcrLanguage.English` на соответствующее значение enum. Оставление языка неопределённым заставляет движок переходить в режим автоопределения, что может быть медленнее и менее точно. + +## Шаг 2: Сбор всех TIFF‑файлов — Эффективное извлечение текста из TIFF + +Далее мы получаем каждый файл *.tif* из указанной вами папки. Использование `Directory.GetFiles` даёт нам чистый массив, который мы можем передать пакетному процессору. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Полезный совет:* Флаг `SearchOption.AllDirectories` можно использовать, если ваши сканы находятся в подпапках. Просто помните, что более глубокая рекурсия может увеличить использование памяти во время пакетного шага. + +## Шаг 3: Выполнение параллельного OCR — Пакетное преобразование изображения в текст + +Теперь самая интересная часть. Aspose.OCR поставляется со статическим помощником `BatchOcr.RecognizeAll`, который принимает массив путей к файлам, движок и подсказку `parallelism`. Мы запустим четыре потока, что на современном четырёхъядерном ноутбуке даёт почти линейное ускорение. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Почему параллелизм?* +Сканирование пакета высокоразрешённых TIFF может сильно нагружать CPU. Распределяя работу по нескольким потокам, мы загружаем все ядра, значительно сокращая общее время выполнения. Если запускать это на сервере с большим количеством ядер, увеличьте значение `parallelism` соответственно. + +## Шаг 4: Запись вывода — Конвертация сканированных изображений в TXT‑файлы + +Наконец мы проходим по словарю и записываем каждый фрагмент текста в файл *.txt*, который имеет то же базовое имя, что и оригинал. Это тот момент, когда **convert scanned images txt** становится реальностью. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Что делает код, простыми словами + +1. **Create** OCR‑движок, настроенный на английский. +2. **Collect** каждый TIFF‑файл из целевой папки. +3. **Run** `BatchOcr.RecognizeAll` с четырьмя потоками, преобразуя каждое изображение в строку. +4. **Loop** по результатам, заменяя расширение `.tif` на `.txt` и записывая строку на диск. + +Это весь процесс **convert TIFF to text** в менее чем 50 строк кода. + +## Обработка граничных случаев — Когда всё идёт не гладко + +- **Missing or corrupted TIFFs** – `BatchOcr` бросит `OcrException`. Оберните вызов в `try / catch`, если нужна плавная деградация. +- **Non‑English documents** – измените `OcrLanguage.English` на `OcrLanguage.Spanish`, `OcrLanguage.French` и т.д., или используйте `OcrLanguage.AutoDetect`. +- **Very large images** – рассмотрите возможность снижения DPI перед OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`), чтобы сэкономить память, хотя может пострадать точность. +- **Output encoding** – если вам нужна определённая кодовая страница (например, Windows‑1252), передайте её в `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Профессиональные советы для надёжных пакетных конвертаций + +- **Log failures**: создайте `List failedFiles` и добавляйте в него любой файл, который бросает исключение; после цикла запишите список в лог. +- **Reuse the engine**: тот же экземпляр `OcrEngine` можно переиспользовать для множества файлов; не создавайте его внутри цикла. +- **Validate the result**: быстрая проверка `if (string.IsNullOrWhiteSpace(extractedText))` может пометить сканы, которые пусты или нечитаемы. +- **Combine with PDF**: если ваш источник — многостраничный PDF, сначала конвертируйте каждую страницу в TIFF (это делает Aspose.PDF), а затем запустите этот пакет. + +## Следующие шаги — Выход за пределы простой конвертации + +Теперь, когда вы можете **extract text from TIFF** файлы пакетно, вы можете захотеть: + +- Передать файлы *.txt* в поисковый индекс (Elasticsearch, Azure Cognitive Search). +- Запустить определение языка для каждого результата, чтобы направлять документы в локально‑специфичные конвейеры. +- Создать поисковые PDF, наложив OCR‑текст обратно на оригинальные изображения (снова Aspose.PDF). + +Все эти сценарии основаны на одной основной идее: **batch image to text conversion** — строительный блок для более крупных систем обработки документов. + +--- + +### Заключение + +Вы только что узнали, как **convert TIFF to text** с помощью Aspose.OCR, обрабатывать всю папку параллельно и сохранять каждый результат в чистый файл *.txt*. Решение лёгкое, полностью настраиваемое и готово к продакшн‑использованию — будь то оцифровка старых счетов, архивирование сканированных контрактов или обеспечение работы поискового движка. + +Попробуйте, настройте степень параллелизма и начните подавать эти только что созданные текстовые файлы в любой необходимый вам рабочий процесс. Приятного OCR! + +--- + +## Связанные руководства + +- [Извлечение текста из изображений с помощью OCR‑операции в папках](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Извлечение текста из изображения — оптимизация 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/russian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..f6ae58963 --- /dev/null +++ b/ocr/russian/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: Узнайте, как извлекать текст из изображения с помощью минимального API + ASP.NET Core. Загружайте изображение через POST, считывайте multipart‑данные формы + и выполняйте OCR изображения. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: ru +og_description: Извлеките текст из изображения с помощью минимального API ASP.NET + Core. В этом руководстве показано, как загрузить изображение через POST, прочитать + данные multipart/form-data и выполнить OCR изображения. +og_title: Извлечение текста из изображения в ASP.NET Core – пошагово +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Извлечение текста из изображения в ASP.NET Core Minimal API — Полное руководство +url: /ru/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Извлечение текста из изображения в ASP.NET Core Minimal API – Полное руководство + +Задумывались когда‑нибудь, как **извлечь текст из изображения** без борьбы с тяжёлыми фреймворками? Вы не одиноки. Многие разработчики нуждаются в быстром способе позволить пользователям загрузить картинку и получить обратно символы, будь то сканирование чеков, оцифровка рукописных заметок или наполнение поискового индекса. + +В этом руководстве мы создадим крошечный ASP.NET Core Minimal API, который **загружает изображение через POST**, разбирает полезную нагрузку *multipart/form‑data* и затем **выполняет OCR на изображении** с помощью singleton‑объекта `OcrEngine`. К концу вы получите полностью рабочее приложение, которое можно добавить в любой проект .NET 8 и сразу начинать извлекать текст из изображения. + +## Что вы построите + +- Минимальное веб‑приложение, прослушивающее `/ocr`. +- Точка доступа, принимающая файл изображения, отправленный POST‑запросом `multipart/form-data`. +- Логика, читающая загруженный файл, передающая его OCR‑движку и возвращающая результат в виде простого текста. +- Необязательный фрагмент ускорения на GPU (закомментирован) для тех, у кого есть совместимая видеокарта. + +**Требования** +- .NET 8 SDK (или новее). +- Базовое знакомство с C# и командной строкой. +- Библиотека OCR, предоставляющая класс `OcrEngine` (в примере используется гипотетический пакет NuGet). + +Если всё это у вас есть, давайте начнём. + +## Шаг 1: Настройка проекта и добавление OCR‑пакета + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Подсказка:** Держите зависимости в актуальном состоянии. Более новые версии часто дают прирост производительности, особенно для ускорения на GPU. + +## Шаг 2: Регистрация singleton‑OCR‑движка (основной сервис) + +Нам нужен один экземпляр `OcrEngine` для всего приложения — нет необходимости создавать новый движок для каждого запроса. Зарегистрируйте его в контейнере сервисов билдера. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Почему singleton?** +Создание OCR‑движка может быть дорогим — представьте загрузку весов нейронной сети в память. Переиспользуя один и тот же экземпляр, мы экономим как CPU‑циклы, так и ОЗУ, что приводит к более быстрым откликам для каждого вызова `/ocr`. + +## Шаг 3: Сборка приложения + +Теперь мы материализуем объект `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Эта строка выглядит почти волшебно, но под капотом она настраивает маршрутизацию, middleware и DI‑контейнер, который мы только что сконфигурировали. + +## Шаг 4: Определение POST‑эндпоинта – «Загрузка изображения через POST» + +Это сердце руководства: эндпоинт, который **загружает изображение через POST**, читает multipart‑payload и передаёт данные OCR‑движку. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Разбор логики + +| Шаг | Что происходит | Почему это важно | +|------|----------------|-------------------| +| **ReadFormAsync** | Разбирает входящий запрос *multipart/form-data*. | Без этого нельзя получить доступ к загруженным файлам. | +| **form.Files["image"]** | Получает файл, у которого имя поля формы `image`. | Обеспечивает предсказуемый контракт для вызывающих. | +| **Content‑type check** | Проверяет, что файл является изображением (например, `image/png`). | Предотвращает сбой OCR‑движка при обработке не‑изображений. | +| **Image.FromStream** | Преобразует поток байтов в объект `System.Drawing.Image`. | OCR‑библиотека ожидает объект `Image`, а не сырые байты. | +| **ocr.Recognize(img)** | Вызывает OCR‑движок для **распознавания текста из изображения**. | Это основной шаг **выполнения OCR на изображении**. | +| **Results.Text** | Возвращает ответ в виде простого текста. | Простой, удобный формат для downstream‑сервисов. | + +## Шаг 5: Запуск API + +Наконец, запустите веб‑сервер. + +```csharp +app.Run(); +``` + +Когда вы выполните `dotnet run`, API будет слушать `http://localhost:5000` (или любой выбранный вами порт). Вы можете протестировать его с помощью `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Ожидаемый вывод:** Консоль выведет распознанные символы, например: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Если изображение размыто или язык не поддерживается, OCR‑движок вернёт пустую строку или сообщение об ошибке — обрабатывайте такие случаи в продакшн‑коде. + +## Пограничные случаи и лучшие практики + +### 1. Большие файлы + +Ограничение тела запроса по умолчанию — 30 МБ. Для более крупных сканов может потребоваться изменить его: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Асинхронный OCR + +Некоторые OCR‑библиотеки предоставляют асинхронные методы (`RecognizeAsync`). Если ваша библиотека их поддерживает, замените `ocr.Recognize(img)` на `await ocr.RecognizeAsync(img)` и пометьте лямбда‑выражение как `async`. + +### 3. Соображения безопасности + +- **Проверяйте размер файла** перед загрузкой в память. +- **Очистите имя файла**, если вы когда‑либо будете записывать его на диск. +- **Ограничивайте частоту запросов** к эндпоинту, чтобы избежать атак отказа в обслуживании. + +### 4. Ускорение на GPU + +Если раскомментировать строку `engine.GpuDevice = new GpuDevice(0);` и ваше оборудование поддерживает CUDA или DirectML, вы заметите значительное ускорение, особенно на изображениях высокого разрешения. + +## Полный рабочий пример + +Ниже приведён полный `Program.cs`, который можно скопировать и вставить в новый проект Minimal API. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Сохраните, запустите `dotnet run`, и вы будете готовы **извлекать текст из изображения** по запросу. + +## Заключение + +Мы прошли через **полное, сквозное решение** для извлечения текста из изображения с использованием ASP.NET Core Minimal API. Начиная со scaffolding проекта, мы **зарегистрировали singleton‑OCR‑движок**, создали эндпоинт, который **загружает изображение через POST**, **чтёт multipart‑форму**, и, наконец, **выполняет OCR на изображении**, возвращая чистый простой текст. + +Отсюда вы можете: + +- Добавить JSON‑обёртки для более богатых ответов. +- Подключить базу данных для хранения извлечённого текста. +- Расширить поддержку нескольких языков (`OcrLanguage.Spanish` и др.). + +Паттерн хорошо масштабируется — просто добавьте тот же эндпоинт в более крупный микросервис или разместите его за API‑gateway. + +Есть вопросы по работе с PDF, пакетной обработкой или настройкой GPU? Оставляйте комментарий, и счастливого кодинга! + +## Похожие руководства + +- [Извлечение текста из изображения с использованием 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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/russian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..059b15d3a --- /dev/null +++ b/ocr/russian/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,314 @@ +--- +category: general +date: 2026-05-25 +description: Извлечение текста из изображения с помощью C# и Aspose OCR. Узнайте, + как преобразовать JPG в текст, загрузить изображение для OCR и получить надежные + результаты быстро. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: ru +og_description: Извлеките текст из изображения с помощью C#. Это руководство показывает, + как преобразовать JPG в текст, загрузить изображение для OCR и работать с многоязычным + контентом. +og_title: Извлечение текста из изображения в C# – учебник по Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Извлечение текста из изображения в C# – Полное руководство по Aspose OCR +url: /ru/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Извлечение текста из изображения на C# – Полное руководство по Aspose OCR + +Вы когда‑нибудь задумывались, как **extract text from image** с помощью обычного кода C#? Вы не одиноки. Будь то оцифровка чеков, сканирование вывесок или просто интерес к OCR, возможность извлекать символы из изображения — полезный навык. В этом руководстве мы пройдем полный, готовый к запуску пример, который точно показывает, как **extract text from image** с помощью Aspose.OCR, а также рассмотрим, как **convert jpg to text**, **load image for OCR**, и ответим на классический вопрос «**how to ocr image**» раз и навсегда. + +К концу этого руководства у вас будет автономное консольное приложение, которое читает JPEG‑файл, распознаёт украинский (или любой другой поддерживаемый язык) и выводит результат в консоль. Никаких неопределённых ссылок, никаких недостающих частей — просто готовое решение, которое можно скопировать, вставить и запустить. + +--- + +## Чего вы научитесь + +* Как установить пакет Aspose.OCR через NuGet. +* Точный код, необходимый для **load image for OCR** в C#. +* Как задать язык и действительно **extract text from image**. +* Приёмы для эффективного **convert jpg to text**. +* Распространённые подводные камни и как их избежать. + +Если у вас уже настроена среда разработки .NET, вы готовы приступить. В противном случае раздел «Требования» ниже поможет вам быстро стартовать. + +--- + +## Требования + +| Требование | Почему это важно | +|------------|------------------| +| .NET 6.0 SDK (или новее) | Предоставляет среду выполнения для консольного приложения. | +| Visual Studio 2022 или VS Code | Обеспечивает удобное редактирование и отладку. | +| Интернет‑соединение (при первом запуске) | NuGet необходимо для загрузки Aspose.OCR. | +| JPEG‑изображение, которое вы хотите обработать (например, `ukrainian_sign.jpg`) | Исходный файл для OCR‑движка. | + +> **Pro tip:** Если вы работаете в Linux или macOS, тот же код работает с .NET CLI (`dotnet new console`), так что можете смело обходить тяжёлую IDE. + +--- + +## Шаг 1 – Установить Aspose.OCR через NuGet + +Откройте терминал (или консоль диспетчера пакетов) и выполните: + +```bash +dotnet add package Aspose.OCR +``` + +Эта единственная строка скачивает последние бинарные файлы Aspose.OCR и все транзитивные зависимости. Никакой ручной работы с DLL не требуется. + +--- + +## Шаг 2 – Создать OCR‑движок (Сердце извлечения) + +Теперь, когда библиотека на месте, мы можем создать экземпляр `OcrEngine`. Этот объект отвечает за **extract text from image**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Почему это важно:** Движок инкапсулирует OCR‑алгоритмы, языковые модели и параметры конфигурации. Создавать его один раз и переиспользовать для нескольких изображений — экономично по памяти и быстро. + +--- + +## Шаг 3 – Load image for OCR (И задать язык) + +Следующий шаг — указать движку, какое изображение читать. Здесь как раз и используется фраза **load image for OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Edge case:** Если файл не существует, `Image.FromFile` бросит `FileNotFoundException`. Оберните вызов в блок `try‑catch` в продакшн‑коде. + +--- + +## Шаг 4 – Выполнить OCR и Extract Text + +После загрузки изображения движок может **extract text from image**. Метод `Recognize` делает всю тяжёлую работу. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Если всё прошло успешно, переменная `recognizedText` будет содержать обычный текстовое представление всего, что смог распознать OCR‑движок. + +--- + +## Шаг 5 – Convert JPG to Text (Объединяем всё вместе) + +Код, который мы построили до сих пор, уже **convert jpg to text**, но завернём его в удобный метод, который можно вызывать многократно. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Теперь достаточно выполнить: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Ожидаемый вывод** (усечённый для краткости): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Если изображение содержит английский текст, замените `OcrLanguage.English`, и вы увидите соответствующий вывод. + +--- + +## Шаг 6 – Обработка типовых вопросов «How to OCR Image» + +### 6.1 Можно ли OCR‑ить PNG или BMP? + +Абсолютно. Метод `Image.FromFile` поддерживает все форматы, которые распознаёт System.Drawing, так что просто укажите путь к файлу `.png` или `.bmp`, а остальной код останется без изменений. + +### 6.2 Что делать, если изображение низкого разрешения? + +Точность OCR резко падает ниже 300 dpi. Быстрое решение — увеличить изображение с помощью `Graphics` перед передачей его в движок: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Нужна ли лицензия для Aspose.OCR? + +Aspose предлагает бесплатную пробную версию с водяным знаком. Для продакшн‑использования приобретите лицензию и добавьте: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Полный рабочий пример + +Ниже полностью готовое консольное приложение, демонстрирующее **how to OCR image**, **load image for OCR** и **convert jpg to text** в одном компактном пакете. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Как запустить** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Вы должны увидеть извлечённый текст, напечатанный в консоли, что подтверждает успешное **extract text from image** с помощью C#. + +--- + +## Распространённые подводные камни & Pro Tips + +| Проблема | Почему происходит | Решение | +|----------|-------------------|---------| +| Пустой вывод | Слишком тёмное или низкоконтрастное изображение. | Предобработайте с помощью `Bitmap`, увеличив яркость. | +| Неправильный язык | Свойство `Language` оставлено по умолчанию (английский). | Явно задайте `ocrEngine.Language = OcrLanguage.Ukrainian;` (или нужный вам). | +| Ошибка «Out‑of‑memory» | Очень большие изображения загружаются без освобождения. | Оберните `Image.FromFile` в `using` (как показано). | +| Водяной знак лицензии | Запуск на пробной версии без лицензии. | Примените приобретённую лицензию в начале `Main`. | + +--- + +## Заключение + +Мы рассмотрели всё, что нужно для **extract text from image** в C# — от установки Aspose.OCR, **load image for OCR**, до **convert jpg to text** и работы с многоязычными сценариями. Полный пример программы связывает все части, предоставляя надёжную основу для любого проекта, связанного с OCR. + +Дальше вы можете изучить: + +* **How to OCR image** потоки вместо файлов (использовать `MemoryStream`). +* Добавление пост‑обработки **c# image to text**, например проверку орфографии. +* Интеграцию шага OCR в более крупный конвейер (например, сохранение результатов в базе данных). + +Экспериментируйте с разными языками, форматами изображений и приёмами предобработки. OCR — это и искусство, и наука, и чем больше вы играете, тем лучше результаты. + +Happy coding, and may your images always be readable! + +## Похожие руководства + +- [Извлечение текста из изображения C# с выбором языка с помощью Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/russian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..cc04c1475 --- /dev/null +++ b/ocr/russian/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: Как использовать OCR в C# для извлечения текста из файлов изображений. + Узнайте, как распознавать китайские символы из JPG с помощью Aspose.OCR за несколько + простых шагов. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: ru +og_description: Как использовать OCR в C# для извлечения текста из файлов изображений. + Это руководство показывает, как распознавать китайские символы из JPG с помощью + Aspose.OCR. +og_title: Как использовать OCR в C# – распознавание китайского текста из JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Как использовать OCR в C# — распознавать китайский текст из JPG +url: /ru/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Как использовать OCR в C# – распознавание китайского текста из JPG + +Когда‑нибудь задумывались **как использовать OCR**, чтобы извлечь слова из фотографии, сделанной на телефон? Вы не одиноки. Во многих реальных проектах — подумайте о сканерах чеков, приложениях‑переводчиках или автоматическом вводе данных — вам понадобится **извлекать текст из изображения** быстро и надёжно. + +В этом руководстве мы пройдём через полностью готовый пример, который **распознаёт текст из JPG**‑файлов и даже справляется с сложным случаем **распознавания китайских иероглифов** с помощью языкового пакета **OCR Chinese Simplified**. К концу вы получите автономное консольное приложение, выводящее обнаруженную строку в консоль, без дополнительных ручных загрузок. + +> **Краткое замечание:** Код работает с Aspose.OCR ≥ 23.7, который автоматически загружает языковые ресурсы при первом использовании. Если у вас более старая версия, потребуется добавить язык вручную. + +## Предварительные требования + +Прежде чем начать, убедитесь, что у вас есть: + +- .NET 6.0 SDK или новее (пример ориентирован на .NET 6, но .NET 5 тоже подойдёт) +- Последняя версия Visual Studio 2022 или VS Code с расширением C# +- Интернет‑соединение для первой загрузки языка +- JPG‑изображение, содержащее упрощённый китайский текст (назовём его `chinese_sign.jpg`) + +И всё — без тяжёлых OCR‑движков, без нативных DLL. Достаточно нескольких команд NuGet и пары строк кода. + +## Шаг 1: Установите Aspose.OCR через NuGet + +Во‑первых, нам нужна библиотека OCR. Откройте терминал в папке проекта и выполните: + +```bash +dotnet add package Aspose.OCR +``` + +Или, если предпочитаете UI Visual Studio, щёлкните правой кнопкой **Dependencies → Manage NuGet Packages**, найдите “Aspose.OCR” и нажмите **Install**. + +> **Совет:** Держите пакеты в актуальном состоянии. Новые языковые пакеты и оптимизации появляются в каждом минорном релизе. + +## Шаг 2: Создайте новый консольный проект (если ещё не сделали) + +Если вы начинаете с нуля, создайте новое консольное приложение: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Теперь у вас есть файл `Program.cs`, готовый для кода OCR. + +## Шаг 3: Напишите код OCR – распознавание упрощённого китайского из JPG + +Откройте `Program.cs` и замените его содержимое следующим кодом. Каждая строка прокомментирована, чтобы вы видели *почему* мы делаем тот или иной шаг, а не только *что* делаем. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Что происходит «под капотом»? + +- **`OcrEngine.Language`** указывает Aspose, какой словарь использовать. Выбирая `ChineseSimplified`, мы инструктируем движок искать пакет упрощённого китайского языка. +- **Первичная загрузка**: Когда вызывается `Recognize`, SDK обращается к CDN Aspose, скачивает ≈6 МБ языковой файл, кэширует его локально и затем продолжает OCR. Последующие вызовы мгновенны. +- **`Image.FromFile`** работает с любым растровым форматом, который .NET умеет декодировать — JPG, PNG, BMP — так что вы можете **извлекать текст из изображения** файлов разных типов, а не только JPG. + +## Шаг 4: Запустите приложение и проверьте вывод + +Соберите и запустите: + +```bash +dotnet run +``` + +Вы должны увидеть что‑то вроде: + +``` +=== Recognized Text === +欢迎光临 +``` + +Если консоль выводит мусор или пустую строку, проверьте следующее: + +1. Изображение действительно содержит чёткие, контрастные китайские символы. +2. Путь к файлу правильный (нет лишних пробелов или отсутствующих расширений). +3. Ваш компьютер может достичь `https://download.aspose.com` для загрузки языкового пакета. + +## Шаг 5: Обработка граничных случаев и типичных подводных камней + +### 5.1 Работа с низкокачественными изображениями + +Точность OCR падает, когда исходное изображение размыто, шумно или имеет плохое освещение. Быстрое решение — предобработать изображение: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Запуск в безголовом окружении + +Если вы развёртываете в Linux‑контейнере без GUI, убедитесь, что установлен пакет `libgdiplus` (необходимый для `System.Drawing`): + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Кеширование языкового пакета вручную + +Можно один раз скачать языковой файл и указать Aspose путь к нему через API `License`, что устраняет единовременный сетевой запрос. Это удобно для офлайн‑сценариев. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Полный рабочий пример (всё в одном файле) + +Ниже представлен *полный* код программы, который можно скопировать в `Program.cs`. Никаких скрытых частей, никаких внешних скриптов. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Ожидаемый вывод + +Если JPG содержит фразу “欢迎光临”, консоль выведет: + +``` +=== Recognized Text === +欢迎光临 +``` + +Не стесняйтесь заменять изображение любым другим упрощённым китайским знаком, названием улицы или этикеткой продукта — движок постарается распознать всё как можно лучше. + +## Заключение + +Мы только что рассмотрели **как использовать OCR** в C# для **извлечения текста из изображения**, особенно решая задачу **распознавания китайских символов** в **JPG**. Благодаря загрузке языков «на лету» от Aspose.OCR вы можете держать развертывание лёгким, одновременно поддерживая **OCR Chinese Simplified** из коробки. + +Что дальше? Попробуйте следующие идеи: + +- **Пакетная обработка**: пройдитесь по папке с изображениями и запишите каждый результат в CSV. +- **Комбинация с API перевода**: передайте распознанную строку в Azure Translator для создания многоязычных приложений в реальном времени. +- **Исследуйте другие языки**: замените `OcrLanguage.ChineseSimplified` на `Japanese` или `Arabic` и посмотрите, как тот же код адаптируется. + +Есть вопросы о настройке производительности, лицензировании или интеграции OCR в веб‑службу? Оставляйте комментарий ниже — happy coding! + +--- + +![Скриншот вывода консоли, показывающий, как использовать OCR в C# для распознавания китайского текста из JPG‑изображения](ocr-chinese-demo.png "вывод консоли OCR") + +## Похожие руководства + +- [Извлечение текста из изображения 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](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/russian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/russian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..abf1b5dc6 --- /dev/null +++ b/ocr/russian/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Узнайте, как выполнять OCR русского текста в C# и извлекать текст из + изображения с помощью Aspose OCR. Пошаговый код для быстрой конвертации изображения + в текст на C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: ru +og_description: OCR русского текста в C# стал простым. Узнайте, как извлекать текст + из изображения, конвертировать изображение в текст на C# и загружать изображение + для OCR с помощью Aspose OCR. +og_title: OCR русского текста в C# – Полное руководство по Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR русского текста в C# – Полное руководство по использованию Aspose OCR +url: /ru/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR русского текста в C# – Полное руководство с использованием Aspose OCR + +Когда‑нибудь вам нужно было выполнить OCR русского текста в C#, но вы не знали, какую библиотеку выбрать? Вы не одиноки. Получить чистые, читаемые символы с кириллического изображения может ощущаться как расшифровка секретных сообщений — особенно если не задать правильную языковую модель. + +В этом руководстве мы пройдем практический пример, показывающий, как **извлекать текст из изображения** файлов, выполнять *image to text C#* стиль, и учитывать нюансы распознавания русского языка с помощью Aspose OCR. К концу вы получите готовое к запуску консольное приложение, которое загружает изображение для OCR, выводит распознанную строку и дает прочную основу для более продвинутых сценариев. + +## Что вы узнаете + +- Как установить и настроить **Aspose OCR C#** для поддержки русского языка. +- Точные шаги для **load image for OCR** и вызова движка. +- Советы по работе с распространенными проблемами, такими как отсутствие языковых ресурсов или размытые сканы. +- Способы расширения решения, например пакетная обработка нескольких файлов или настройка порогов уверенности. + +Предыдущий опыт работы с Aspose не требуется; достаточно базовых знаний C# и .NET, чтобы приступить. + +## Требования + +Прежде чем мы начнём, убедитесь, что у вас есть следующее: + +1. **.NET 6.0** (или новее) SDK установлен — код работает как на .NET Core, так и на .NET Framework. +2. **Visual Studio 2022** (или любой предпочитаемый IDE). +3. Пакет **Aspose.OCR for .NET** NuGet — вы можете получить бесплатный пробный ключ с сайта Aspose. +4. Файл **Russian language model** (`rus.traineddata`) — скачайте его со страницы ресурсов Aspose и разместите в папке, на которую будете ссылаться позже. +5. Пример изображения (`russian_doc.png`) с чётким кириллическим текстом. + +Все готово? Отлично — приступим. + +## Шаг 1: Настройка проекта и установка Aspose OCR + +Сначала создайте новый консольный проект: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Затем добавьте пакет Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Совет:** Если вы используете пробную лицензию, держите файл `Aspose.Total.lic` под рукой; вы загрузите его в коде, чтобы избежать водяных знаков. + +После установки пакета откройте `Program.cs`. Вы увидите метод `Main` по умолчанию — замените его содержимое на скелет, который мы построим. + +## Шаг 2: Настройка OCR‑движка для русского языка + +Сердцем операции является объект `OcrEngine`. Нам нужно задать ему две вещи: какой язык распознавать и где искать файлы языковой модели. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Почему это важно:** Если пропустить установку `Language = OcrLanguage.Russian`, движок по умолчанию будет использовать английский, и любые кириллические символы отобразятся как искажённые знаки. `ResourceFolder` указывает на каталог, содержащий файл `rus.traineddata`; без него Aspose выдаст исключение *resource not found*. + +## Шаг 3: Загрузка изображения для OCR + +Теперь нам нужно **load image for OCR**. Aspose OCR работает с `System.Drawing.Image`, поэтому вы можете передать любой поддерживаемый формат (PNG, JPEG, BMP и т.д.). Убедитесь, что путь к файлу правильный; относительные пути подходят, если изображение находится рядом с исполняемым файлом. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Пограничный случай:** Если изображение большое (более 5 МБ), возможно, стоит сначала уменьшить его размер. Точность OCR падает при слишком низком DPI, но огромные файлы могут вызвать нагрузку на память. Быстрое изменение размера можно выполнить с помощью `Graphics`, если необходимо. + +## Шаг 4: Распознавание текста — From Image to Text C# Style + +С движком, настроенным и изображением, загруженным, фактическое распознавание происходит одним вызовом: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Когда вы запустите программу (`dotnet run`), вы должны увидеть что‑то вроде: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Если вывод выглядит как набор бессмысленных символов, проверьте следующее: + +- Файл `rus.traineddata` присутствует в `ResourceFolder`. +- Изображение не слишком размыто; рассмотрите возможность применения простого бинаризующего фильтра перед OCR. +- Настройка языка действительно `OcrLanguage.Russian`. + +## Шаг 5: Тонкая настройка и распространённые подводные камни + +### Регулировка порога уверенности + +Aspose OCR возвращает значение уверенности для каждого символа внутренне. Хотя API не раскрывает его напрямую, вы можете включить **detailed output**, чтобы увидеть, какие слова имеют низкую уверенность: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Если вы замечаете частые ошибки распознавания, попробуйте: + +- **Pre‑processing**: Преобразуйте изображение в градации серого, увеличьте контраст или примените медианный фильтр. +- **DPI settings**: Убедитесь, что изображение имеет минимум 300 DPI для кириллических скриптов. + +### Пакетная обработка нескольких изображений + +Если вам нужно **extract text from image** файлы массово, оберните логику распознавания в цикл: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Теперь каждый PNG получает собственный `.txt` файл — удобно для архивирования документов. + +### Обработка Unicode‑вывода + +Кириллические символы находятся в Unicode, поэтому убедитесь, что кодировка вашей консоли может их отображать: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Разместите эту строку сразу после начала метода `Main`. Без неё вы можете увидеть знаки вопроса (`?`) вместо русских букв. + +## Полный рабочий пример + +Ниже приведён полный готовый к запуску код. Скопируйте и вставьте его в `Program.cs`, скорректируйте пути, и вы готовы к работе. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Ожидаемый вывод** (при условии, что пример изображения содержит «Пример текста на русском языке.»): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Если вы видите что‑то другое, вернитесь к советам по устранению неполадок в Шаге 5. + +## Заключение + +Теперь у вас есть надёжный сквозной пример того, как **ocr russian text** в C# с использованием Aspose OCR. От установки библиотеки, настройки модели русского языка, до загрузки изображения и преобразования его в чистый Unicode‑текст, всё покрыто. + +Помните, ключ к надёжному OCR — хороший исходный материал: чёткие шрифты, достаточный DPI и правильные языковые ресурсы. Овладев основами, вы можете расширить решение до пакетной обработки, интеграции с облачным хранилищем или даже сочетать с AI‑постобработкой для проверки орфографии. + +### Что дальше? + +- Исследуйте расширенные возможности **aspose ocr c#**, такие как анализ макета или вывод в PDF. +- Скомбинируйте это с процессами **extract text from image** в Azure Functions для безсерверной обработки. +- Попробуйте другие языки — просто замените `OcrLanguage.Russian` на `OcrLanguage.English` или другой поддерживаемый код. + +Есть вопросы или проблемное изображение, которое не поддаётся? Оставьте комментарий ниже, и удачной разработки! + +![пример OCR русского текста](ocr-russian-example.png){alt="пример OCR русского текста"} + +## Связанные руководства + +- [Извлечение текста из изображения C# с выбором языка с использованием Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Распознавание текста на изображении с Aspose OCR для нескольких языков](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Извлечение текста из изображения с использованием Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/russian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..895b1adec --- /dev/null +++ b/ocr/russian/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,213 @@ +--- +category: general +date: 2026-05-25 +description: распознавать текст на изображении с помощью Aspose OCR в C#. Узнайте, + как загрузить изображение для OCR, установить язык OCR, создать движок OCR и извлечь + текст из TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: ru +og_description: распознавать текст на изображении с помощью Aspose OCR в C#. Этот + учебник показывает, как создать OCR‑движок, загрузить изображение для OCR, установить + язык OCR и извлечь текст из TIFF. +og_title: Распознавание текста на изображении с помощью Aspose OCR – Полное руководство + по C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Распознавание текста с изображения с помощью Aspose OCR – Полное руководство + по C# +url: /ru/net/text-recognition/recognize-text-from-image-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 – Полное руководство на C# + +Когда‑то вам нужно **распознать текст с изображения**, но вы не знали, какая библиотека обеспечит и скорость, и точность? Вы не одиноки. Во многих проектах по обработке счетов или архивированию главная боль — получить чистый, индексируемый текст из TIFF‑файлов без написания собственного парсера. + +Дело в том, что Aspose OCR for .NET делает весь этот конвейер простым как раз. В этом руководстве мы пройдёмся по всему, что нужно — установке пакета, **созданию OCR‑движка**, загрузке TIFF, установке языка OCR и, наконец, **извлечению текста из TIFF**. К концу вы получите готовое консольное приложение, которое может **распознавать текст с изображения** мгновенно. + +## Требования + +- .NET 6.0 или новее (код работает и с .NET Core, и с .NET Framework) +- Visual Studio 2022 (или любая другая IDE) +- NuGet‑пакет Aspose.OCR (для поддержки GPU требуется дополнение `Aspose.OCR.Gpu`) +- GPU с поддержкой CUDA, если хотите дополнительную скорость (необязательно, но рекомендуется) + +> **Pro tip:** Если у вас нет GPU, просто уберите строку `GpuDevice`, и движок автоматически переключится на CPU. + +## Шаг 1: Установить Aspose OCR и создать OCR‑движок + +Сначала добавьте необходимые пакеты через NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Теперь мы можем **создать OCR‑движок**. Этот объект — сердце процесса; в нём хранится конфигурация, такая как устройство выполнения и ограничения памяти. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Почему это важно:** Привязав движок к GPU, вы резко сокращаете время, необходимое для **распознавания текста с изображения**, особенно при обработке больших пакетов высокоразрешённых TIFF‑файлов. + +## Шаг 2: Загрузить изображение для OCR + +Далее нам нужно **загрузить изображение для OCR**. Aspose.OCR работает с `System.Drawing.Image`, поэтому любой формат, поддерживаемый GDI+ (включая многостраничный TIFF), подходит. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Если вы работаете с многостраничным TIFF, можете перебрать страницы с помощью `image.SelectActiveFrame`, но в большинстве случаев достаточно одного вызова. + +## Шаг 3: Установить язык OCR + +Движок не знает, на каком языке вы сканируете, автоматически. **Установите язык OCR** перед запуском распознавания; иначе вы получите кучу искажённого вывода. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Did you know?** Переключение языков во время выполнения дешево — вы даже можете обработать документ с несколькими языками, меняя это свойство между страницами. + +## Шаг 4: Выполнить распознавание – распознать текст с изображения + +Теперь самая интересная часть: действительно **распознать текст с изображения**. Метод `Recognize` возвращает обычную строку со всеми найденными символами. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Если нужны оценки уверенности или ограничивающие рамки, можно использовать перегрузку, возвращающую объект `OcrResult`, но для большинства задач извлечения достаточно простой строки. + +## Шаг 5: Извлечь текст из TIFF (и обработать многостраничные файлы) + +Когда источник — TIFF, содержащий несколько страниц, вам придётся повторять шаги 2‑4 для каждого кадра. Ниже быстрый цикл, который **извлекает текст из TIFF** постранично: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Код выше выводит извлечённый текст для каждой страницы, что упрощает передачу результатов в базу данных или поисковый индекс. + +## Шаг 6: Отобразить или сохранить извлечённый текст + +Наконец, **отобразим извлечённый текст** и, при желании, запишем его в файл для дальнейшей обработки. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Запуск программы должен вывести распознанные символы и создать `extracted_text.txt` рядом с исходным TIFF. + +--- + +## Часто задаваемые вопросы и особые случаи + +- **Что делать, если мой GPU не обнаружен?** + Удалите строку `GpuDevice`; движок автоматически переключится в режим CPU. Производительность будет ниже, но результаты останутся точными. + +- **Можно ли обрабатывать PNG или JPEG?** + Конечно — `Image.FromFile` работает с любым форматом, поддерживаемым System.Drawing, так что вы можете **загрузить изображение для OCR** независимо от расширения. + +- **Как работать с низкокачественными сканами?** + Увеличьте `ocrEngine.PreprocessOptions.Dpi` перед вызовом `Recognize`. Более высокий DPI даёт движку больше пикселей для анализа, повышая точность. + +- **Есть ли ограничение на размер TIFF?** + Свойство `GpuMemoryLimit` ограничивает использование GPU. Если лимит будет превышен, движок переключится на CPU для оставшихся страниц. + +--- + +## Заключение + +Теперь у вас есть полностью готовый, готовый к продакшену фрагмент кода, который **распознаёт текст с изображения** с помощью Aspose OCR в C#. В руководстве рассмотрены создание OCR‑движка, **загрузка изображения для OCR**, **установка языка OCR** и **извлечение текста из TIFF** — всё с использованием ускорения GPU для повышения скорости. + +Дальше вы можете: + +- Поэкспериментировать с разными языками (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` и т.д.). +- Интегрировать вывод в индексируемый ElasticSearch. +- Добавить постобработку (проверка орфографии, очистка с помощью regex) для улучшения качества данных. + +Попробуйте на своей партии счетов, поиграйте с ограничениями памяти и наблюдайте, как растёт производительность OCR. Приятного кодинга! + +## Похожие руководства + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..c1db54f34 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. +### [Crear motor OCR en C# – Guía completa](./create-ocr-engine-in-c-complete-guide/) +Aprende a crear y configurar un motor OCR en C# paso a paso con Aspose.OCR. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/spanish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..b3face8a3 --- /dev/null +++ b/ocr/spanish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Crea un motor OCR en C# y aprende cómo verificar su modo de evaluación + y el estado de la licencia en unas pocas líneas de código. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: es +og_description: Crea un motor OCR en C# y ve al instante cómo detectar el modo de + evaluación y mostrar el estado de la licencia. +og_title: Crear motor OCR en C# – Guía paso a paso +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Crear motor OCR en C# – Guía completa +url: /es/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Crear OCR Engine en C# – Guía completa + +¿Alguna vez te has preguntado cómo **crear OCR engine** objetos en C# sin buscar entre interminables documentos? No eres el único. Muchos desarrolladores se topan con un obstáculo cuando necesitan iniciar un motor OCR, verificar si está ejecutándose en modo de prueba y mostrar el estado de la licencia a los usuarios. + +En este tutorial recorreremos un ejemplo conciso y de extremo a extremo que **crea un OCR engine**, verifica su **modo de evaluación del OCR engine**, y muestra un mensaje amigable sobre el estado de la licencia. Al final tendrás una aplicación de consola lista para ejecutar y un modelo mental claro para manejar la licencia OCR en tus propios proyectos. + +## Lo que aprenderás + +- Cómo instanciar un `OcrEngine` (el núcleo de cualquier flujo de trabajo OCR). +- Por qué detectar el **modo de evaluación** es importante para el cumplimiento y la experiencia del usuario. +- La mejor manera de **comprobar la licencia OCR** y reaccionar ante estados inesperados. +- Trampas comunes—referencias nulas, manejo de excepciones y desajustes de versiones. + +Sin herramientas externas requeridas más allá del SDK OCR que ya tienes instalado. Si te sientes cómodo con la sintaxis básica de C#, estás listo para comenzar. + +## Requisitos previos + +- .NET 6.0 o posterior (el código compila con .NET Core y .NET Framework). +- Un SDK OCR que exponga una clase `OcrEngine` con una propiedad `IsEvaluation` (por ejemplo, el hipotético `MyOcrSdk`). +- Un editor de texto o IDE (Visual Studio, VS Code, Rider—elige tu favorito). + +Eso es todo. Vamos a sumergirnos. + +## Paso 1: Configurar un nuevo proyecto de consola + +Primero, crea una nueva aplicación de consola para ejecutar el código de forma aislada. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Abre el `Program.cs` generado. Reemplazaremos su contenido con un ejemplo completo que **crea OCR engine** instancias y maneja la licencia. + +## Paso 2: Importar el espacio de nombres del SDK OCR + +Suponiendo que el SDK está referenciado vía NuGet (`MyOcrSdk` es un marcador), agrega la directiva using al inicio del archivo. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Si aún no has agregado el paquete, ejecuta: + +```bash +dotnet add package MyOcrSdk +``` + +> **Consejo profesional:** Mantén tu versión del SDK actualizada; las versiones más recientes a menudo mejoran la detección del modo de evaluación. + +## Paso 3: Crear la instancia del OCR Engine + +Ahora finalmente **creamos OCR engine** objetos. Este es el corazón de cualquier flujo de trabajo OCR—piensa en él como el cerebro que más tarde leerá imágenes. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +¿Por qué es crucial este paso? El `OcrEngine` encapsula toda la configuración, paquetes de idioma y datos de licencia. Sin él, no puedes procesar imágenes ni consultar la bandera de evaluación. + +> **Nota al margen:** Algunos SDK permiten pasar un objeto de configuración al constructor (p. ej., idioma, DPI). Si necesitas ajustes personalizados, modifica la línea en consecuencia. + +## Paso 4: Determinar el modo de evaluación del OCR Engine + +La mayoría de los proveedores de OCR ofrecen una versión de prueba que funciona en **modo de evaluación** hasta que se suministra una clave de licencia válida. Saber si estás en modo de prueba te permite mostrar indicaciones UI apropiadas o restringir ciertas funciones. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +La propiedad `IsEvaluation` devuelve `true` cuando el motor no está licenciado o está usando una prueba limitada en tiempo. Es una forma rápida y fiable de proteger funciones premium. + +### ¿Qué pasa si la propiedad falta? + +Versiones más antiguas del SDK podrían exponer un método como `GetLicenseInfo()` en su lugar. En ese caso, inspeccionarías el objeto devuelto para una bandera `IsTrial`. Siempre consulta el registro de cambios del SDK al actualizar. + +## Paso 5: Mostrar el estado actual de la licencia + +Finalmente, mostremos al usuario si el motor está licenciado o aún en prueba. Una simple escritura en consola hace el truco, pero puedes adaptarla para aplicaciones GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +El operador ternario mantiene el código ordenado, y los mensajes son lo suficientemente claros para usuarios finales o desarrolladores que lean los registros. + +## Ejemplo completo funcionando + +Juntándolo todo, aquí tienes un programa autocontenido que puedes copiar y pegar en `Program.cs` y ejecutar con `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Salida esperada + +- **Compilación de prueba:** + `Running in evaluation mode – limited functionality.` + +- **Compilación con licencia:** + `Licensed – full OCR capabilities enabled.` + +Si el SDK lanza una excepción (p. ej., falta una DLL nativa), el bloque catch imprimirá un mensaje de error útil en lugar de bloquear toda la aplicación. + +## Manejo de casos límite y trampas comunes + +### 1. Instancias de motor nulas + +Aunque el constructor usualmente devuelve un objeto válido, algunos SDK pueden devolver `null` si faltan dependencias nativas requeridas. Protege contra ello: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Expiración de la licencia mientras se ejecuta + +Una licencia de prueba puede expirar a mitad de sesión. Vuelve a consultar periódicamente `IsEvaluation` si tu aplicación permanece activa durante mucho tiempo. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Nombres de propiedades diferentes entre versiones + +Versiones más antiguas podrían exponer `engine.EvaluationMode` o `engine.License.IsTrial`. Cuando actualices, busca en las notas de la versión del SDK cambios que rompan compatibilidad. + +### 4. Escenarios multi‑hilo + +Si inicias varios trabajadores OCR, instancia **un OCR engine por hilo** a menos que el SDK soporte explícitamente compartir de forma segura entre hilos. Compartir un solo motor puede generar condiciones de carrera y lecturas de licencia falsas. + +## Consejos profesionales para uso en producción + +- **Cachea el estado de la licencia** después de la primera verificación para evitar llamadas innecesarias a la propiedad. +- **Registra la clave de licencia** (enmascarada) al iniciar para auditorías—ayuda a los equipos de soporte a diagnosticar problemas de licencia. +- **Proporciona un interruptor UI** que indique a los usuarios que están en modo prueba y ofrezca un botón “Comprar licencia”. +- **Automatiza la renovación de la licencia** usando la API de activación del SDK, si está disponible, para mantener una experiencia de usuario fluida. + +## Conclusión + +Acabamos de **crear OCR engine** objetos en unas pocas líneas, inspeccionado el **modo de evaluación del OCR engine**, y mostrado un mensaje claro del **estado de la licencia OCR**. El ejemplo completo funciona out of the box, maneja errores de forma elegante y destaca el “por qué” detrás de cada paso—para que puedas adaptarlo a escenarios de escritorio, web o servicios. + +A continuación, podrías explorar: + +- Alimentar imágenes a `engine.Recognize` y manejar soporte multilingüe. +- Usar APIs **check OCR license** para activar programáticamente una clave comprada. +- Integrar con frameworks UI (WinForms, WPF, MAUI) para mostrar insignias de licencia. + +Prueba esas opciones, y tendrás una base OCR robusta lista para cualquier aplicación. ¡Feliz codificación! + +## Tutoriales relacionados + +- [Cómo extraer OCR – Configuración OCR](/ocr/english/net/ocr-configuration/) +- [Cómo obtener resultados OCR con Aspose.OCR para .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [Cómo OCR PDF en .NET con Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/ocr-optimization/_index.md b/ocr/spanish/net/ocr-optimization/_index.md index b9a9d4da6..debd0fc10 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. +### [Preprocesar imagen para OCR – Guía completa Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Aprende a aplicar filtros y técnicas de preprocesamiento para mejorar la precisión del OCR con Aspose en C#. ## Preguntas frecuentes diff --git a/ocr/spanish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/spanish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..998c1d879 --- /dev/null +++ b/ocr/spanish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: Preprocese la imagen para OCR con Aspose para mejorar la precisión del + OCR y ejecute OCR en archivos JPEG. Aprenda a extraer texto usando Aspose en un + tutorial claro, paso a paso. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: es +og_description: Preprocese la imagen para OCR con Aspose para mejorar la precisión + del OCR. Siga esta guía para ejecutar OCR en JPEG y extraer texto usando Aspose + en C#. +og_title: Preprocesar imagen para OCR – Tutorial de Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Preprocesar imagen para OCR – Guía completa de Aspose C# +url: /es/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Preprocesar Imagen para OCR – Guía Completa de Aspose C# + +¿Alguna vez te has preguntado cómo **preprocesar imagen para OCR** para que el texto salga limpio cada vez? No eres el único: los desarrolladores luchan constantemente contra escaneos ruidosos, JPEGs de bajo contraste y una iluminación impredecible. ¿La buena noticia? Con unos pocos ajustes inteligentes puedes **mejorar la precisión del OCR** de forma drástica, y Aspose lo hace sin complicaciones. + +En este tutorial recorreremos un ejemplo del mundo real que muestra cómo **ejecutar OCR en JPEG** , aplicar una canalización de procesamiento de imagen personalizada y, finalmente, **extraer texto usando Aspose**. Al final tendrás un fragmento de C# listo para copiar y pegar que podrás insertar en cualquier proyecto .NET. + +## Lo que aprenderás + +- Por qué el preprocesamiento es importante y qué filtros aportan la mayor mejora. +- Cómo configurar `ImageProcessingOptions` de Aspose.OCR para enderezar, eliminar ruido, binarizar y aumentar el contraste. +- El código exacto necesario para **ejecutar OCR en JPEG** y obtener texto limpio. +- Consejos y trampas que mantienen tu canalización OCR robusta en producción. + +No se requiere experiencia previa con Aspose; solo conocimientos básicos de C# y Visual Studio (o tu IDE favorito). ¡Comencemos! + +![Ejemplo de preprocesar imagen para OCR](preprocess-ocr.png "Preprocesar imagen para OCR") + +## Paso 1: Configurar el motor Aspose.OCR – Preprocesar Imagen para OCR + +Lo primero. Necesitamos una instancia de `OcrEngine` y debemos indicarle qué idioma esperamos. En la mayoría de los casos el inglés es el predeterminado, pero puedes cambiarlo por francés, alemán, etc., modificando el enumerado `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Por qué es importante:** El motor es el corazón de la operación; sin él no puedes aplicar ninguno de los filtros de imagen que realmente **preprocesan imagen para OCR**. Piensa en él como la cocina donde se mezclan todos los ingredientes. + +## Paso 2: Construir una Canalización de Procesamiento de Imagen Personalizada – Mejorar la Precisión del OCR + +Ahora viene la parte jugosa. Aspose te permite encadenar varios filtros. A continuación habilitamos cuatro de los más efectivos: + +1. **Deskew** – endereza documentos inclinados (máx. 5° por defecto). +2. **Denoise** – suaviza fondos granulosos. +3. **Binarize** – convierte la imagen a blanco y negro usando un umbral. +4. **ContrastBoost** – hace que los caracteres tenues resalten. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Consejo profesional:** Si tus imágenes de origen ya son nítidas, puedes reducir el `Strength` o desactivar un filtro por completo. El sobreprocesamiento a veces borra caracteres tenues, así que experimenta con muestras reales. + +## Paso 3: Cargar el JPEG (o Cualquier Imagen) y Ejecutar OCR – Ejecutar OCR en JPEG + +Aspose funciona con cualquier formato de imagen que .NET pueda leer—JPEG, PNG, BMP, lo que sea. Así es como alimentas un archivo JPEG al motor y lanzas el proceso de reconocimiento. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**¿Por qué JPEG?** La compresión JPEG a menudo introduce artefactos que confunden al OCR. Nuestra canalización de preprocesamiento, especialmente los pasos de denoise y binarize, mitiga esos problemas, permitiéndote **ejecutar OCR en JPEG** con confianza. + +## Paso 4: Mostrar el Texto Reconocido – Extraer Texto Usando Aspose + +Finalmente, simplemente escribimos el texto en la consola, en un archivo o en cualquier servicio posterior. Para la demostración, la consola es suficiente. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Al ejecutar el programa, deberías ver algo como: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Si la salida se ve distorsionada, vuelve al **Paso 2** y ajusta la configuración de los filtros. Pequeños ajustes suelen producir grandes mejoras en **mejorar la precisión del OCR**. + +## Casos Límite Comunes y Cómo Gestionarlos + +| Situación | Ajuste Sugerido | +|-----------|-----------------| +| **Imágenes muy oscuras** | Incrementa `ContrastBoost.Level` a 1.5 o más. | +| **Inclinación > 5°** | Aumenta `DeskewOptions.MaxAngle` (p. ej., 10.0) o pre‑rota la imagen manualmente. | +| **Texto de color sobre fondo de color** | Usa `BinarizeOptions` con un umbral personalizado o cambia a `AdaptiveBinarizeOptions`. | +| **Archivos grandes ( > 5 MB )** | Carga la imagen en un `MemoryStream` primero para evitar problemas de bloqueo de archivo. | + +Estos ajustes mantienen tu canalización flexible y preparada para el futuro, especialmente cuando necesitas **extraer texto usando Aspose** de fuentes diversas. + +## Ejemplo Completo – Todos los Pasos en un Solo Lugar + +A continuación tienes el programa completo, listo para copiar y pegar. Compila con .NET 6+ y solo requiere el paquete NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Guarda esto como `Program.cs`, añade el paquete Aspose.OCR (`dotnet add package Aspose.OCR`) y ejecuta `dotnet run`. Verás el texto limpiado impreso en la consola. + +## Resumen – Por Qué Funciona Este Enfoque + +- **Preprocesar imagen para OCR**: La canalización elimina las fuentes de error más comunes (inclinación, ruido, bajo contraste). +- **Mejorar la precisión del OCR**: Cada filtro está afinado para aumentar la relación señal‑ruido que el motor percibe. +- **Ejecutar OCR en JPEG**: Incluso las imágenes comprimidas se vuelven legibles tras el enderezado y la binarización. +- **Extraer texto usando Aspose**: El método `Recognize` devuelve una cadena simple, lista para cualquier lógica posterior. + +Juntos, estos pasos te brindan una solución OCR fiable y de nivel de producción en solo unas cuantas líneas. + +## Próximos Pasos y Temas Relacionados + +- **Procesamiento por lotes** – Recorrer una carpeta de imágenes y escribir cada resultado en un archivo `.txt`. +- **Paquetes de idioma** – Cambiar `OcrLanguage.English` por `OcrLanguage.Spanish` o añadir diccionarios personalizados. +- **Extracción de PDF** – Combinar Aspose.OCR con Aspose.PDF para extraer texto directamente de PDFs escaneados. +- **Ajuste de rendimiento** – Ejecutar el motor en paralelo usando `Parallel.ForEach` para cargas de trabajo grandes. + +Siéntete libre de experimentar con los valores de los filtros, probar diferentes formatos de imagen o encadenar filtros adicionales de Aspose como `SharpnessOptions`. El cielo es el límite una vez domines los conceptos básicos. + +--- + +*¡Feliz codificación! Si encuentras algún problema, deja un comentario abajo y lo solucionaremos juntos.* + +## Tutoriales Relacionados + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/spanish/net/text-recognition/_index.md b/ocr/spanish/net/text-recognition/_index.md index 8f06dcbf8..273d7d359 100644 --- a/ocr/spanish/net/text-recognition/_index.md +++ b/ocr/spanish/net/text-recognition/_index.md @@ -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 @@ -55,9 +55,23 @@ Mejore sus aplicaciones .NET con Aspose.OCR para un reconocimiento eficiente del 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. ### [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. +### [Reconocer texto de imagen con Aspose OCR – Guía completa en C#](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Aprenda paso a paso a extraer texto de imágenes usando Aspose OCR en C#, con ejemplos completos y mejores prácticas. +### [Cómo usar OCR en C# – Reconocer texto chino desde JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Aprenda a reconocer texto en chino desde archivos JPG usando Aspose.OCR en C#, con ejemplos claros y paso a paso. +### [OCR de texto ruso en C# – Guía completa usando Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Aprenda a reconocer texto ruso en imágenes usando Aspose OCR con C#, con ejemplos paso a paso y mejores prácticas. +### [Extraer texto de imagen en C# – Guía completa de Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Aprenda paso a paso a extraer texto de imágenes con Aspose OCR en C#, con ejemplos detallados y mejores prácticas. +### [Extraer texto de imagen en ASP.NET Core Minimal API – Guía completa](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Aprenda paso a paso a extraer texto de imágenes usando Aspose OCR en una API mínima de ASP.NET Core, con ejemplos claros y mejores prácticas. +### [Tutorial OCR en C#: Extraer texto de recibos PNG con Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Aprenda a extraer texto de recibos en formato PNG usando Aspose OCR en C#, con ejemplos claros y paso a paso. +### [Convertir TIFF a Texto en C# – Guía completa de OCR por lotes](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Aprenda a convertir archivos TIFF a texto en C# usando Aspose.OCR, procesando múltiples archivos de forma eficiente en una sola operació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/spanish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/spanish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..5c2a4ede1 --- /dev/null +++ b/ocr/spanish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: Tutorial de OCR en C# que muestra cómo cargar un archivo de imagen en + C# y reconocer texto PNG de un recibo usando Aspose OCR – guía paso a paso. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: es +og_description: Tutorial de OCR en C# que te guía paso a paso en la carga de un archivo + de imagen en C# y en el reconocimiento de texto PNG de un recibo usando Aspose OCR. +og_title: Tutorial de OCR en C# – Extraer texto de recibos PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'Tutorial de OCR en C#: Extraer texto de recibos PNG con Aspose' +url: /es/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# tutorial de OCR en c# – Extraer texto de recibos PNG con Aspose + +¿Alguna vez necesitaste un **tutorial de OCR en c#** que realmente funcione sin tener que buscar sin fin en Google? Estás en el lugar correcto. En esta guía **cargaremos un archivo de imagen c#**, **reconoceremos texto png**, y **leeremos los resultados OCR del recibo**, todo mientras te mostramos cómo **realizar OCR en imágenes** con Aspose OCR. + +Comenzaremos instalando el paquete NuGet necesario, revisaremos cada línea de código y terminaremos con un volcado JSON ordenado que podrás canalizar directamente a tu próximo pipeline de datos. Sin relleno, solo una solución práctica y lista para ejecutar. + +## Lo que aprenderás + +- Cómo configurar Aspose OCR en un proyecto .NET 6 (o superior). +- Los pasos exactos para **cargar un archivo de imagen c#** y pasarlo al motor. +- Cómo **reconocer texto png** de una imagen de recibo y capturar el resultado. +- Formas de **leer OCR del recibo** y obtener un JSON bien formateado. +- Consejos para **realizar OCR en imágenes** con diferentes tipos de archivo y manejar problemas comunes. + +**Requisitos previos** +- Visual Studio 2022 (o cualquier IDE que prefieras). +- .NET 6 SDK o una versión más reciente. +- Una imagen PNG de recibo a mano (la llamaremos `receipt.png`). + +Si ya tienes todo eso, vamos a sumergirnos. + +![captura de pantalla del tutorial de OCR en c#](ocr-demo.png "resultado del tutorial de OCR en c# mostrando salida JSON") + +## Tutorial de OCR en c# – Configuración del motor Aspose OCR + +Primero, necesitamos la biblioteca Aspose OCR. Abre tu terminal en la carpeta de la solución y ejecuta: + +```bash +dotnet add package Aspose.OCR +``` + +Ese único comando descarga todo lo necesario, incluidos los binarios nativos para la decodificación de imágenes. Una vez instalado, crea un nuevo proyecto de consola o agrega el código a uno existente. + +### ¿Por qué Aspose? + +Aspose OCR soporta más de 30 idiomas, funciona sin conexión y devuelve un rico objeto `OcrResult`, perfecto para tareas de **realizar OCR en imágenes** donde necesitas más que solo texto plano. + +## Cargar archivo de imagen c# y preparar el recibo + +Ahora que la biblioteca está lista, vamos a **cargar un archivo de imagen c#**. La clase `System.Drawing.Image` hace el trabajo pesado, pero también puedes usar `SkiaSharp` si prefieres una alternativa multiplataforma. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Consejo profesional:** Envuelve el `Image` en una sentencia `using` (como se muestra) para liberar los recursos nativos rápidamente, algo especialmente importante cuando **realizas OCR en imágenes** sobre muchos archivos en un bucle. + +## Reconocer texto PNG con Aspose + +Con la imagen en memoria, el motor ahora puede **reconocer texto png**. Aspose devuelve un `OcrResult` que contiene tanto la cadena cruda como datos detallados de cada palabra reconocida. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +¿Por qué llamar a `RecognizeWithResult` en lugar de usar el más simple `Recognize`? El primero te da acceso a puntuaciones de confianza, cajas delimitadoras y saltos de línea, lo cual es útil si luego necesitas **leer OCR del recibo** para extraer ítems de línea. + +## Leer el resultado OCR del recibo como JSON + +La mayoría de los sistemas posteriores prefieren JSON, así que vamos a serializar el `OcrResult`. El serializador `System.Text.Json` maneja objetos complejos con elegancia, y habilitaremos la indentación para mayor legibilidad. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +El JSON resultante se ve algo así (recortado por brevedad): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Ahora puedes canalizar `jsonResult` a una base de datos, una cola de mensajes o simplemente registrarlo para depuración. + +## Realizar procesamiento OCR de imágenes y mostrar la salida + +Finalmente, imprimimos el JSON en la consola. En una aplicación real probablemente lo escribirías en un archivo o lo enviarías por HTTP, pero la consola facilita la verificación de que todo funcionó. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Ejecuta el programa (`dotnet run`) y deberías ver el JSON bien formateado impreso. Si la imagen del recibo es clara, el texto será preciso; de lo contrario, considera aumentar la resolución de la imagen o aplicar un filtro de preprocesamiento (p. ej., escala de grises, aumento de contraste) antes de enviarla al motor. + +### Manejo de casos límite comunes + +| Situación | Qué hacer | +|-----------|-----------| +| **La imagen está borrosa** | Pre‑procesa con `System.Drawing` para enfocar o aumentar DPI. | +| **El recibo contiene varios idiomas** | Configura `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Procesamiento por lotes grande** | Reutiliza una única instancia de `OcrEngine`; solo cambia la `Image` en cada iteración. | +| **Presión de memoria** | Elimina rápidamente los objetos `Image` y considera `await Task.Run` para pipelines asíncronos. | + +Estos ajustes mantienen tu flujo de **realizar OCR en imágenes** robusto incluso cuando la entrada no es perfecta. + +## Conclusión + +¡Felicidades! Acabas de completar un **tutorial de OCR en c#** que carga una imagen, **reconoce texto png**, y **lee OCR del recibo** como JSON limpio. Los pasos clave (configuración del motor, carga de imagen, ejecución OCR, serialización y visualización) forman una base sólida que puedes ampliar a facturas, pasaportes o cualquier otro documento escaneado. + +### ¿Qué sigue? + +- Experimenta con **cargar archivo de imagen c#** usando `SkiaSharp` para un soporte verdaderamente multiplataforma. +- Profundiza en `OcrResult.Words` para extraer ítems de línea, precios y fechas, ideal para aplicaciones de seguimiento de gastos. +- Combina este tutorial con Azure Functions o AWS Lambda para crear una API sin servidor de procesamiento de recibos. + +Siéntete libre de modificar el código, añadir más imágenes o incluso cambiar a otro paquete de idioma. El mundo del OCR está lleno de sorpresas, y ahora tienes las herramientas para explorarlas. + +¡Feliz codificación, y que tus recibos siempre sean legibles! + + +## Tutoriales relacionados + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Use OCR - Recognize Image without Text Area Detection](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/spanish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..2c9a0d0db --- /dev/null +++ b/ocr/spanish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: Convertir TIFF a texto usando Aspose.OCR en C#. Aprende la conversión + por lotes de imágenes a texto y extrae texto de archivos TIFF de manera eficiente. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: es +og_description: Convertir TIFF a texto con Aspose.OCR. Esta guía muestra la conversión + por lotes de imágenes a texto y cómo extraer texto de archivos TIFF en unas pocas + líneas de C#. +og_title: Convertir TIFF a Texto en C# – Guía Completa de OCR por Lotes +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Convertir TIFF a texto en C# – Guía completa de OCR por lotes +url: /es/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Convertir TIFF a Texto en C# – Guía Completa de OCR por Lotes + +¿Alguna vez necesitaste **convertir TIFF a texto** pero no sabías por dónde empezar? No estás solo—muchos desarrolladores tropiezan con el OCR por lotes al trabajar con documentos escaneados. En este tutorial recorreremos una solución práctica que **extrae texto de archivos TIFF** usando Aspose.OCR, y lo haremos en paralelo para que carpetas grandes terminen en segundos. + +También abordaremos las mejores prácticas de **conversión de imagen a texto por lotes**, así que al final tendrás un fragmento reutilizable que convierte todo un directorio de imágenes escaneadas en archivos *.txt* ordenados—perfectos para indexar, buscar o alimentar análisis posteriores. + +## Lo que Necesitarás + +- **.NET 6.0** o posterior (el código también se compila en .NET Framework) +- Paquete NuGet **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Una carpeta que contenga uno o más archivos *.tif* (el clásico formato de escaneo TIFF) +- Tu IDE favorito (Visual Studio, VS Code, Rider—lo que prefieras) + +Eso es todo. Sin servicios externos, sin claves API, solo puro C# y Aspose. + +![Captura de pantalla de un archivo TIFF siendo procesado y el archivo de texto resultante](/images/ocr-result.png "Resultado de OCR que muestra la salida del TIFF convertido a texto") + +*(Texto alternativo: Captura de pantalla que muestra la salida del TIFF convertido a texto en pantalla)* + +## Paso 1: Configurar el Motor OCR – Convertir TIFF a Texto + +Lo primero, necesitamos una instancia de `OcrEngine` que sepa que debe leer caracteres en inglés. El motor es el corazón de la conversión; configurarlo correctamente garantiza resultados fiables. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Por qué esto importa:* +Aspose.OCR soporta docenas de idiomas. Si trabajas con escaneos multilingües, simplemente cambia `OcrLanguage.English` al valor de enumeración apropiado. Dejar el idioma sin definir obliga al motor a modo de auto‑detección, lo que puede ser más lento y menos preciso. + +## Paso 2: Recopilar Todos los Archivos TIFF – Extraer Texto de TIFF de Forma Eficiente + +A continuación obtenemos cada archivo *.tif* de una carpeta que especifiques. Usar `Directory.GetFiles` nos brinda un arreglo limpio que podemos pasar al procesador por lotes. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Consejo profesional:* La bandera `SearchOption.AllDirectories` puede usarse si tus escaneos están anidados en sub‑carpetas. Solo recuerda que una recursión más profunda puede aumentar el uso de memoria durante el paso por lotes. + +## Paso 3: Ejecutar OCR en Paralelo – Conversión de Imagen a Texto por Lotes + +Ahora la parte divertida. Aspose.OCR incluye un ayudante estático `BatchOcr.RecognizeAll` que acepta un arreglo de rutas de archivo, un motor y una pista de `parallelism`. Crearemos cuatro hilos, lo que en una laptop moderna de cuatro núcleos brinda una aceleración casi lineal. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*¿Por qué paralelismo?* +Escanear un lote de TIFFs de alta resolución puede ser intensivo en CPU. Al distribuir el trabajo entre varios hilos mantenemos todos los núcleos ocupados, reduciendo drásticamente el tiempo total de ejecución. Si lo ejecutas en un servidor con más núcleos, aumenta el valor de `parallelism` en consecuencia. + +## Paso 4: Escribir la Salida – Convertir Imágenes Escaneadas a Archivos TXT + +Finalmente iteramos sobre el diccionario y escribimos cada fragmento de texto en un archivo *.txt* que comparte el nombre base original. Este es el momento en que **convertir imágenes escaneadas a txt** se vuelve una realidad. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Qué hace el código, en lenguaje sencillo + +1. **Crear** un motor OCR configurado para inglés. +2. **Recopilar** cada archivo TIFF de la carpeta objetivo. +3. **Ejecutar** `BatchOcr.RecognizeAll` con cuatro hilos, convirtiendo cada imagen en una cadena. +4. **Iterar** sobre los resultados, cambiando la extensión `.tif` por `.txt` y escribiendo la cadena en disco. + +Ese es todo el flujo de trabajo de **convertir TIFF a texto** en menos de 50 líneas de código. + +## Manejo de Casos Límite – Cuando las Cosas No Van Suavemente + +- **TIFFs faltantes o corruptos** – `BatchOcr` lanzará una `OcrException`. Envuelve la llamada en un `try / catch` si necesitas una degradación elegante. +- **Documentos no ingleses** – cambia `OcrLanguage.English` a `OcrLanguage.Spanish`, `OcrLanguage.French`, etc., o usa `OcrLanguage.AutoDetect`. +- **Imágenes muy grandes** – considera reducir el DPI antes del OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) para ahorrar memoria, aunque podrías perder algo de precisión. +- **Codificación de salida** – si necesitas una página de códigos específica (p.ej., Windows‑1252), pásala a `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Consejos Profesionales para Conversiones por Lotes Robustas + +- **Registrar fallos**: crea una `List failedFiles` y agrega cualquier archivo que lance una excepción; escribe la lista en un registro después del bucle. +- **Reutilizar el motor**: la misma instancia de `OcrEngine` puede reutilizarse en muchos archivos; no la instancies dentro del bucle. +- **Validar el resultado**: un rápido `if (string.IsNullOrWhiteSpace(extractedText))` puede señalar escaneos que estaban en blanco o ilegibles. +- **Combinar con PDF**: si tu fuente es un PDF de varias páginas, convierte cada página a TIFF primero (Aspose.PDF lo hace) y luego ejecuta este lote. + +## Próximos Pasos – Más Allá de la Conversión Simple + +Ahora que puedes **extraer texto de archivos TIFF** en bloque, podrías querer: + +- Alimentar los archivos *.txt* a un índice de búsqueda (Elasticsearch, Azure Cognitive Search). +- Ejecutar detección de idioma en cada resultado para dirigir los documentos a flujos específicos por localidad. +- Generar PDFs buscables superponiendo el texto OCR sobre las imágenes originales (Aspose.PDF nuevamente). + +Todos esos escenarios se basan en la misma idea central: **la conversión de imagen a texto por lotes** es un bloque de construcción para sistemas de procesamiento de documentos más grandes. + +--- + +### Conclusión + +Acabas de aprender cómo **convertir TIFF a texto** usando Aspose.OCR, procesar una carpeta completa en paralelo y guardar cada resultado como un archivo *.txt* limpio. La solución es ligera, totalmente configurable y lista para producción—ya sea que estés digitalizando facturas heredadas, archivando contratos escaneados o impulsando un motor de búsqueda de texto. + +Pruébala, ajusta el paralelismo y comienza a alimentar esos archivos de texto recién creados en cualquier flujo de trabajo que necesites. ¡Feliz OCR! + +--- + +## Tutoriales Relacionados + +- [Extraer Texto de Imágenes Usando la Operación OCR en Carpetas](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extraer Texto de Imagen – 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/spanish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..c572b2b53 --- /dev/null +++ b/ocr/spanish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Aprende a extraer texto de una imagen con una API mínima de ASP.NET Core. + Sube la imagen mediante POST, lee los datos de formulario multipart y realiza OCR + en la imagen. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: es +og_description: Extrae texto de una imagen usando una API mínima de ASP.NET Core. + Esta guía muestra cómo subir una imagen mediante POST, leer datos de formulario + multipart y realizar OCR en la imagen. +og_title: Extraer texto de una imagen en ASP.NET Core – Paso a paso +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Extraer texto de una imagen en ASP.NET Core Minimal API – Guía completa +url: /es/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraer texto de una imagen en ASP.NET Core Minimal API – Guía completa + +¿Alguna vez te has preguntado cómo **extraer texto de una imagen** sin lidiar con frameworks pesados? No estás solo. Muchos desarrolladores necesitan una forma rápida de permitir a los usuarios soltar una foto y obtener de vuelta los caracteres crudos, ya sea escaneando recibos, digitalizando notas manuscritas o alimentando un índice de búsqueda. + +En este tutorial crearemos una pequeña ASP.NET Core Minimal API que **carga imágenes mediante POST**, analiza la carga *multipart/form‑data* y luego **realiza OCR en la imagen** usando un `OcrEngine` singleton. Al final tendrás una aplicación completamente ejecutable que puedes incorporar a cualquier proyecto .NET 8 y comenzar a extraer texto de imágenes de inmediato. + +## Lo que construirás + +- Una aplicación web mínima que escucha en `/ocr`. +- Un endpoint que acepta un archivo de imagen enviado con una solicitud POST `multipart/form-data`. +- Lógica que lee el archivo cargado, lo pasa al motor OCR y devuelve resultados en texto plano. +- Fragmento opcional de aceleración GPU (comentado) para quienes tengan una tarjeta compatible. + +**Requisitos previos** +- .NET 8 SDK (o posterior). +- Familiaridad básica con C# y la línea de comandos. +- Una biblioteca OCR que exponga una clase `OcrEngine` (el ejemplo asume un paquete NuGet hipotético). + +Si tienes eso, vamos a sumergirnos. + +## Paso 1: Configurar el proyecto y agregar el paquete OCR + +Primero, crea un nuevo proyecto web e incorpora la biblioteca OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Consejo profesional:** Mantén tus dependencias actualizadas. Las versiones más recientes a menudo aportan mejoras de rendimiento, especialmente para inferencia acelerada por GPU. + +## Paso 2: Registrar un motor OCR singleton (servicio principal) + +Queremos una única instancia de `OcrEngine` para toda la aplicación—no es necesario crear un nuevo motor por solicitud. Regístralo en el contenedor de servicios del builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**¿Por qué un singleton?** +Crear un motor OCR puede ser costoso—piensa en cargar los pesos de una red neuronal en memoria. Al reutilizar la misma instancia ahorramos ciclos de CPU y RAM, lo que se traduce en tiempos de respuesta más rápidos para cada llamada a `/ocr`. + +## Paso 3: Construir la aplicación + +Ahora materializamos el objeto `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Esa línea parece casi mágica, pero bajo el capó configura el enrutamiento, el middleware y el contenedor DI que acabamos de configurar. + +## Paso 4: Definir el endpoint POST – “Cargar imagen mediante POST” + +Este es el corazón del tutorial: un endpoint que **carga una imagen mediante POST**, lee la carga multipart y entrega los datos al motor OCR. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Desglosando la lógica + +| Paso | Qué ocurre | Por qué es importante | +|------|------------|-----------------------| +| **ReadFormAsync** | Analiza la solicitud *multipart/form-data* entrante. | Sin esto, no puedes acceder a los archivos cargados. | +| **form.Files["image"]** | Obtiene el archivo cuyo nombre de campo de formulario es `image`. | Garantiza un contrato predecible para los llamadores. | +| **Content‑type check** | Verifica que el archivo sea una imagen (p.ej., `image/png`). | Evita que el motor OCR se bloquee con datos que no son imágenes. | +| **Image.FromStream** | Convierte el flujo bruto en un `System.Drawing.Image`. | La biblioteca OCR espera un objeto `Image`, no un arreglo de bytes bruto. | +| **ocr.Recognize(img)** | Llama al motor OCR para **reconocer texto de la imagen**. | Este es el paso central de **realizar OCR en la imagen**. | +| **Results.Text** | Envía de vuelta la respuesta en texto plano. | Un formato simple y consumible para servicios posteriores. | + +## Paso 5: Ejecutar la API + +Finalmente, inicia el servidor web. + +```csharp +app.Run(); +``` + +Cuando ejecutas `dotnet run`, la API escuchará en `http://localhost:5000` (o en el puerto que elijas). Puedes probarla con `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Salida esperada:** La consola imprimirá los caracteres reconocidos, por ejemplo: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Si la imagen está borrosa o el idioma no está soportado, el motor OCR devolverá una cadena vacía o un mensaje de error—maneja esos casos en código de producción. + +## Casos límite y buenas prácticas + +### 1. Archivos grandes + +El límite predeterminado del cuerpo de la solicitud es 30 MB. Para escaneos más grandes podrías necesitar ajustar: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR asíncrono + +Algunas bibliotecas OCR exponen métodos async (`RecognizeAsync`). Si la tuya lo hace, reemplaza `ocr.Recognize(img)` por `await ocr.RecognizeAsync(img)` y marca la lambda como `async`. + +### 3. Consideraciones de seguridad + +- **Validar el tamaño del archivo** antes de cargarlo en memoria. +- **Sanitizar el nombre del archivo** si alguna vez lo escribes en disco. +- **Limitar la tasa** del endpoint para evitar ataques de denegación de servicio. + +### 4. Aceleración GPU + +Si descomentas la línea `engine.GpuDevice = new GpuDevice(0);` y tu hardware soporta CUDA o DirectML, notarás un aumento de velocidad significativo, especialmente en imágenes de alta resolución. + +## Ejemplo completo en funcionamiento + +A continuación se muestra el `Program.cs` completo que puedes copiar y pegar en un nuevo proyecto Minimal API. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Guarda, ejecuta `dotnet run`, y estarás listo para **extraer texto de una imagen** bajo demanda. + +## Conclusión + +Hemos recorrido una **solución completa, de extremo a extremo** para extraer texto de una imagen usando ASP.NET Core Minimal API. Desde la generación del proyecto, **registramos un motor OCR singleton**, construimos un endpoint que **carga una imagen mediante POST**, **lee datos multipart del formulario**, y finalmente **realiza OCR en la imagen** para devolver texto plano limpio. + +Desde aquí puedes: + +- Agregar envoltorios JSON para respuestas más ricas. +- Conectar una base de datos para almacenar el texto extraído. +- Ampliar el soporte a múltiples idiomas (`OcrLanguage.Spanish`, etc.). + +El patrón escala bien—simplemente inserta el mismo endpoint en un microservicio más grande o expónlo detrás de un gateway API. + +¿Tienes preguntas sobre el manejo de PDFs, procesamiento por lotes o afinación de GPU? Deja un comentario, ¡y feliz codificación! + +## Tutoriales relacionados + +- [Extraer texto de una imagen usando Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) +- [Extraer texto de una imagen – Optimización OCR con Aspose.OCR para .NET](/ocr/english/net/ocr-optimization/) +- [Extraer texto de imagen en C# con selección de idioma usando Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/spanish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..00df67be9 --- /dev/null +++ b/ocr/spanish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: Extraiga texto de una imagen usando C# y Aspose OCR. Aprenda cómo convertir + JPG a texto, cargar la imagen para OCR y obtener resultados fiables rápidamente. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: es +og_description: Extrae texto de una imagen con C#. Esta guía muestra cómo convertir + JPG a texto, cargar la imagen para OCR y manejar contenido multilingüe. +og_title: Extraer texto de una imagen en C# – Tutorial de OCR de Aspose +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Extraer texto de una imagen en C# – Guía completa de Aspose OCR +url: /es/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extraer texto de una imagen en C# – Guía completa de Aspose OCR + +¿Alguna vez te has preguntado cómo **extraer texto de una imagen** usando código C# puro? No eres el único. Ya sea que estés digitalizando recibos, escaneando carteles o simplemente tengas curiosidad por el OCR, la capacidad de obtener caracteres de una foto es una habilidad muy útil. En este tutorial recorreremos un ejemplo completo y ejecutable que muestra exactamente cómo **extraer texto de una imagen** con Aspose.OCR, y también cubriremos cómo **convertir jpg a texto**, **cargar imagen para OCR**, y responderemos de una vez por todas a la clásica pregunta “**cómo hacer OCR a una imagen**”. + +Al final de esta guía tendrás una aplicación de consola autosuficiente que lee un archivo JPEG, reconoce ucraniano (o cualquier otro idioma compatible) y muestra el resultado en la consola. Sin referencias vagas, sin piezas faltantes—solo una solución completa que puedes copiar‑pegar y ejecutar. + +--- + +## Qué aprenderás + +* Cómo instalar el paquete NuGet Aspose.OCR. +* El código exacto necesario para **cargar imagen para OCR** en C#. +* Cómo establecer el idioma y realmente **extraer texto de una imagen**. +* Trucos para **convertir jpg a texto** de manera eficiente. +* Obstáculos comunes y cómo evitarlos. + +Si ya tienes un entorno de desarrollo .NET configurado, estás listo para sumergirte. De lo contrario, la sección de requisitos previos a continuación te pondrá al día. + +--- + +## Requisitos previos + +| Requisito | Por qué es importante | +|-------------|----------------| +| .NET 6.0 SDK (o superior) | Proporciona el runtime para la aplicación de consola. | +| Visual Studio 2022 o VS Code | Facilita la edición y depuración. | +| Conexión a Internet (primera ejecución) | NuGet necesita descargar Aspose.OCR. | +| Una imagen JPEG que quieras procesar (p. ej., `ukrainian_sign.jpg`) | El archivo fuente para el motor OCR. | + +> **Consejo profesional:** Si usas Linux o macOS, el mismo código funciona con la CLI de .NET (`dotnet new console`), así que puedes omitir el IDE pesado. + +--- + +## Paso 1 – Instalar Aspose.OCR vía NuGet + +Abre tu terminal (o la Consola del Administrador de Paquetes) y ejecuta: + +```bash +dotnet add package Aspose.OCR +``` + +Esa única línea descarga los binarios más recientes de Aspose.OCR y todas sus dependencias transitivas. No se requiere manipular DLLs manualmente. + +--- + +## Paso 2 – Crear el motor OCR (El corazón de la extracción) + +Ahora que la biblioteca está disponible, podemos crear una instancia de `OcrEngine`. Este objeto es responsable de **extraer texto de una imagen**. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Por qué importa:** El motor encapsula los algoritmos OCR, los modelos de idioma y las opciones de configuración. Instanciarlo una sola vez y reutilizarlo en varias imágenes es tanto eficiente en memoria como rápido. + +--- + +## Paso 3 – Cargar imagen para OCR (y establecer el idioma) + +El siguiente paso es indicarle al motor qué foto leer. Aquí es donde entra en juego la frase **cargar imagen para OCR**. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Caso límite:** Si el archivo no existe, `Image.FromFile` lanza una `FileNotFoundException`. Envuelve la llamada en un bloque try‑catch para código de producción. + +--- + +## Paso 4 – Realizar OCR y extraer texto + +Con la imagen cargada, el motor ahora puede **extraer texto de una imagen**. El método `Recognize` hace el trabajo pesado. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Si todo va bien, `recognizedText` contendrá la representación en texto plano de todo lo que el motor OCR pudo leer. + +--- + +## Paso 5 – Convertir JPG a texto (unificando todo) + +El código que hemos construido hasta ahora ya **convierte jpg a texto**, pero vamos a envolverlo en un método ordenado que puedas llamar repetidamente. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Ahora simplemente puedes hacer: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Salida esperada** (truncada por brevedad): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Si la imagen contiene texto en inglés, cambia `OcrLanguage.English` y verás la salida correspondiente. + +--- + +## Paso 6 – Responder preguntas comunes de “¿Cómo hacer OCR a una imagen?” + +### 6.1 ¿Puedo hacer OCR a un PNG o BMP? + +Absolutamente. El método `Image.FromFile` admite todos los formatos que reconoce System.Drawing, así que solo apunta la ruta a un archivo `.png` o `.bmp` y el resto del código permanece idéntico. + +### 6.2 ¿Y si la imagen tiene baja resolución? + +La precisión del OCR disminuye drásticamente por debajo de 300 dpi. Una solución rápida es escalar la imagen con `Graphics` antes de pasarla al motor: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 ¿Necesito una licencia para Aspose.OCR? + +Aspose ofrece una prueba gratuita con marca de agua. Para uso en producción, compra una licencia y agrega: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Ejemplo completo y funcional + +A continuación tienes una aplicación de consola completa, lista para ejecutar, que demuestra **cómo hacer OCR a una imagen**, **cargar imagen para OCR**, y **convertir jpg a texto** en un solo paquete ordenado. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Cómo ejecutarlo** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Deberías ver el texto extraído impreso en la consola, confirmando que has logrado **extraer texto de una imagen** usando C#. + +--- + +## Trucos y errores comunes + +| Problema | Por qué ocurre | Solución | +|-------|----------------|-----| +| Salida en blanco | Imagen demasiado oscura o con bajo contraste. | Pre‑procesar con `Bitmap` para aumentar el brillo. | +| Idioma incorrecto | Propiedad `Language` dejada en inglés por defecto. | Establece explícitamente `ocrEngine.Language = OcrLanguage.Ukrainian;` (o el idioma que necesites). | +| Error de falta de memoria | Imágenes muy grandes cargadas sin liberar. | Envuelve `Image.FromFile` en un bloque `using` (como se muestra). | +| Marca de agua de licencia | Ejecutando la versión de prueba sin licencia. | Aplica una licencia comprada al inicio de `Main`. | + +--- + +## Conclusión + +Acabamos de cubrir todo lo que necesitas para **extraer texto de una imagen** en C#—desde la instalación de Aspose.OCR, **cargar imagen para OCR**, hasta **convertir jpg a texto** y manejar escenarios multilingües. El programa de ejemplo completo une todas las piezas, dándote una base fiable para cualquier proyecto relacionado con OCR. + +A continuación, podrías explorar: + +* **Cómo hacer OCR a una imagen** a partir de streams en lugar de archivos (usa `MemoryStream`). +* Añadir post‑procesamiento **c# image to text** como corrección ortográfica. +* Integrar el paso OCR en una canalización mayor (p. ej., almacenar resultados en una base de datos). + +Siéntete libre de experimentar con diferentes idiomas, formatos de imagen y trucos de pre‑procesamiento. El OCR es tanto arte como ciencia, y cuanto más juegues, mejores serán los resultados. + +¡Feliz codificación, y que tus imágenes siempre sean legibles! + +## Tutoriales relacionados + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/spanish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..1a9c9254b --- /dev/null +++ b/ocr/spanish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,301 @@ +--- +category: general +date: 2026-05-25 +description: Cómo usar OCR en C# para extraer texto de archivos de imagen. Aprende + a reconocer caracteres chinos de un JPG usando Aspose.OCR en unos pocos pasos simples. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: es +og_description: Cómo usar OCR en C# para extraer texto de archivos de imagen. Esta + guía le muestra cómo reconocer caracteres chinos de un JPG usando Aspose.OCR. +og_title: Cómo usar OCR en C# – Reconocer texto chino desde JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Cómo usar OCR en C# – Reconocer texto chino de un JPG +url: /es/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cómo usar OCR en C# – Reconocer texto chino desde JPG + +¿Alguna vez te has preguntado **cómo usar OCR** para extraer palabras de una foto que tomaste con tu móvil? No estás solo. En muchos proyectos del mundo real —piensa en escáneres de recibos, aplicaciones de traducción o entrada de datos automatizada— necesitarás **extraer texto de imagen** rápidamente y de forma fiable. + +En este tutorial recorreremos un ejemplo completo y ejecutable que **reconoce texto de archivos JPG** e incluso maneja el caso complicado de **reconocer caracteres chinos** usando el paquete de idioma **OCR Chinese Simplified**. Al final, tendrás una aplicación de consola autónoma que imprime la cadena detectada en la consola, sin descargas manuales adicionales. + +> **Nota rápida:** El código funciona con Aspose.OCR ≥ 23.7, que descarga automáticamente los recursos de idioma en el primer uso. Si utilizas una versión anterior, deberás añadir el idioma manualmente. + +## Requisitos previos + +Antes de sumergirnos, asegúrate de contar con: + +- .NET 6.0 SDK o posterior (el ejemplo está dirigido a .NET 6, pero .NET 5 también funciona) +- Una versión reciente de Visual Studio 2022 o VS Code con la extensión C# +- Conexión a internet para la primera descarga del idioma +- Una imagen JPG que contenga texto en chino simplificado (la llamaremos `chinese_sign.jpg`) + +Eso es todo: sin motores OCR pesados, sin manejo de DLL nativas. Solo unos pocos comandos NuGet y un par de líneas de código. + +## Paso 1: Instalar Aspose.OCR vía NuGet + +Lo primero: necesitamos la biblioteca OCR. Abre una terminal en la carpeta de tu proyecto y ejecuta: + +```bash +dotnet add package Aspose.OCR +``` + +O, si prefieres la interfaz de Visual Studio, haz clic derecho en **Dependencies → Manage NuGet Packages**, busca “Aspose.OCR” y pulsa **Install**. + +> **Consejo:** Mantén tus paquetes actualizados. Nuevos paquetes de idioma y mejoras de rendimiento llegan en cada versión menor. + +## Paso 2: Crear un nuevo proyecto de consola (si aún no lo has hecho) + +Si partes de cero, crea una nueva aplicación de consola: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Ahora tendrás un archivo `Program.cs` listo para el código OCR. + +## Paso 3: Escribir el código OCR – Reconocer chino simplificado desde un JPG + +Abre `Program.cs` y reemplaza su contenido con lo siguiente. Cada línea está anotada para que veas *por qué* hacemos cada paso, no solo *qué* hacemos. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### ¿Qué está sucediendo bajo el capó? + +- **`OcrEngine.Language`** indica a Aspose qué diccionario usar. Al seleccionar `ChineseSimplified`, instruimos al motor a buscar el paquete de idioma chino simplificado. +- **Descarga la primera vez**: Cuando se ejecuta `Recognize`, el SDK contacta el CDN de Aspose, descarga el archivo de idioma de ≈6 MB, lo almacena en caché localmente y luego procede con el OCR. Las llamadas posteriores son instantáneas. +- **`Image.FromFile`** funciona con cualquier formato raster que .NET pueda decodificar —JPG, PNG, BMP—, por lo que puedes **extraer texto de imagen** de muchos tipos, no solo JPG. + +## Paso 4: Ejecutar la aplicación y verificar la salida + +Compila y ejecuta: + +```bash +dotnet run +``` + +Deberías ver algo como: + +``` +=== Recognized Text === +欢迎光临 +``` + +Si la consola muestra caracteres ilegibles o una cadena vacía, verifica que: + +1. La imagen realmente contenga caracteres chinos claros y de alto contraste. +2. La ruta del archivo sea correcta (sin espacios extraños ni extensiones faltantes). +3. Tu máquina pueda acceder a `https://download.aspose.com` para descargar el paquete de idioma. + +## Paso 5: Manejo de casos límite y errores comunes + +### 5.1 Tratar imágenes de baja calidad + +La precisión del OCR disminuye cuando la imagen fuente está borrosa, ruidosa o con mala iluminación. Una solución rápida es pre‑procesar la imagen: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Ejecutar en un entorno sin interfaz gráfica + +Si despliegas en un contenedor Linux sin GUI, asegúrate de que la biblioteca `libgdiplus` (requerida por `System.Drawing`) esté instalada: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Cachear el paquete de idioma manualmente + +Puedes descargar el archivo de idioma una vez y apuntar a él mediante la API `License`, lo que elimina la llamada de red única. Esto es útil para escenarios sin conexión. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Ejemplo completo (todo en uno) + +A continuación tienes el programa *completo* que puedes copiar y pegar en `Program.cs`. Sin piezas ocultas, sin scripts externos. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Salida esperada + +Si el JPG contiene la frase “欢迎光临”, la consola imprimirá: + +``` +=== Recognized Text === +欢迎光临 +``` + +Siéntete libre de sustituir la imagen por cualquier otro letrero, nombre de calle o etiqueta de producto en chino simplificado; el motor hará lo mejor posible. + +## Conclusión + +Acabamos de cubrir **cómo usar OCR** en C# para **extraer texto de imagen**, abordando específicamente el desafío de **reconocer caracteres chinos** en un **JPG**. Aprovechando la descarga automática de idiomas de Aspose.OCR, puedes mantener tu despliegue ligero mientras soportas **OCR Chinese Simplified** listo para usar. + +¿Qué sigue? Prueba estas ideas: + +- **Procesamiento por lotes**: recorre una carpeta de imágenes y escribe cada resultado en un CSV. +- **Combinar con APIs de traducción**: envía la cadena reconocida a Azure Translator para aplicaciones multilingües en tiempo real. +- **Explorar otros idiomas**: cambia `OcrLanguage.ChineseSimplified` por `Japanese` o `Arabic` y observa cómo se adapta el mismo código. + +¿Tienes preguntas sobre optimización de rendimiento, licencias o integración de OCR en un servicio web? Deja un comentario abajo — ¡feliz codificación! + +--- + +![Captura de pantalla de la salida de la consola que muestra cómo usar OCR en C# para reconocer texto chino desde una imagen JPG](ocr-chinese-demo.png "salida de la consola de uso de OCR") + + +## Tutoriales relacionados + +- [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/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/spanish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/spanish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..cdc542388 --- /dev/null +++ b/ocr/spanish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,306 @@ +--- +category: general +date: 2026-05-25 +description: Aprende a hacer OCR de texto ruso en C# y extraer texto de una imagen + con Aspose OCR. Código paso a paso para convertir rápidamente una imagen a texto + en C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: es +og_description: OCR de texto ruso en C# hecho fácil. Aprende a extraer texto de una + imagen, convertir imagen a texto en C# y cargar la imagen para OCR con Aspose OCR. +og_title: OCR de texto ruso en C# – Guía completa de Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR de texto ruso en C# – Guía completa usando Aspose OCR +url: /es/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR de texto ruso en C# – Guía completa usando Aspose OCR + +¿Alguna vez necesitaste hacer OCR de texto ruso en C# pero no sabías qué biblioteca confiar? No estás solo. Obtener caracteres limpios y legibles de una imagen cirílica puede sentirse como descifrar mensajes secretos—especialmente si no has configurado el modelo de idioma correcto. + +En este tutorial recorreremos un ejemplo práctico que muestra cómo **extraer texto de archivos de imagen**, convertir *imagen a texto C#* y manejar las particularidades del reconocimiento del idioma ruso con Aspose OCR. Al final tendrás una aplicación de consola lista para ejecutar que carga una imagen para OCR, imprime la cadena reconocida y te brinda una base sólida para escenarios más avanzados. + +## Lo que aprenderás + +- Cómo instalar y configurar **Aspose OCR C#** para soporte del idioma ruso. +- Los pasos exactos para **cargar imagen para OCR** y llamar al motor. +- Consejos para manejar problemas comunes como recursos de idioma faltantes o escaneos borrosos. +- Formas de ampliar la solución, como procesamiento por lotes de varios archivos o ajustar umbrales de confianza. + +No se requiere experiencia previa con Aspose; solo una familiaridad básica con C# y .NET te pondrá en marcha. + +## Requisitos previos + +Antes de sumergirnos, asegúrate de tener lo siguiente: + +1. **.NET 6.0** (o posterior) SDK instalado – el código funciona tanto en .NET Core como en .NET Framework. +2. **Visual Studio 2022** (o cualquier IDE que prefieras). +3. Un paquete NuGet **Aspose.OCR for .NET** – puedes obtener una clave de prueba gratuita desde el sitio web de Aspose. +4. Un archivo de modelo de idioma ruso (`rus.traineddata`) – descárgalo de la página de recursos de Aspose y colócalo en una carpeta que referenciarás más adelante. +5. Una imagen de ejemplo (`russian_doc.png`) que contenga texto cirílico claro. + +¿Tienes todo eso? Genial—comencemos. + +## Paso 1: Configurar el proyecto e instalar Aspose OCR + +Primero, crea un nuevo proyecto de consola: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Ahora agrega el paquete Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Consejo profesional:** Si usas una licencia de prueba, mantén a mano el archivo `Aspose.Total.lic`; lo cargarás en el código para evitar marcas de agua. + +Una vez instalado el paquete, abre `Program.cs`. Verás el método `Main` predeterminado—reemplaza su contenido con el esqueleto que construiremos. + +## Paso 2: Configurar el motor OCR para el idioma ruso + +El corazón de la operación es el objeto `OcrEngine`. Necesitamos indicarle dos cosas: qué idioma reconocer y dónde encontrar los archivos de modelo de idioma. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Por qué es importante:** Si omites establecer `Language = OcrLanguage.Russian`, el motor usa inglés por defecto, y cualquier carácter cirílico aparecerá como símbolos distorsionados. `ResourceFolder` apunta al directorio que contiene el archivo `rus.traineddata`; sin él, Aspose lanza una excepción *resource not found*. + +## Paso 3: Cargar la imagen para OCR + +Ahora necesitamos **cargar imagen para OCR**. Aspose OCR trabaja con `System.Drawing.Image`, por lo que puedes pasar cualquier formato compatible (PNG, JPEG, BMP, etc.). Asegúrate de que la ruta del archivo sea correcta; las rutas relativas están bien si mantienes la imagen junto al ejecutable. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Caso límite:** Si la imagen es grande (más de 5 MB) quizá quieras reducirla primero. La precisión del OCR disminuye cuando el DPI es demasiado bajo, pero los archivos enormes pueden generar presión de memoria. Un redimensionado rápido se puede hacer con `Graphics` si es necesario. + +## Paso 4: Reconocer el texto – De imagen a texto estilo C# + +Con el motor configurado y la imagen cargada, el reconocimiento real es una única llamada: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Al ejecutar el programa (`dotnet run`), deberías ver algo como: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Si la salida parece un galimatías, verifica que: + +- El archivo `rus.traineddata` esté presente en `ResourceFolder`. +- La imagen no esté demasiado borrosa; considera aplicar un filtro de binarización simple antes del OCR. +- La configuración de idioma sea realmente `OcrLanguage.Russian`. + +## Paso 5: Ajuste fino y problemas comunes + +### Ajustar el umbral de confianza + +Aspose OCR devuelve un valor de confianza por carácter internamente. Aunque la API no lo expone directamente, puedes habilitar **salida detallada** para ver qué palabras tienen baja confianza: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Si notas errores frecuentes, prueba: + +- **Pre‑procesamiento**: Convierte la imagen a escala de grises, aumenta el contraste o aplica un filtro mediano. +- **Configuración de DPI**: Asegúrate de que la imagen tenga al menos 300 DPI para scripts cirílicos. + +### Procesamiento por lotes de múltiples imágenes + +Si necesitas **extraer texto de archivos de imagen** en bloque, envuelve la lógica de reconocimiento en un bucle: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Ahora cada PNG obtiene su propio archivo `.txt`—útil para archivado de documentos. + +### Manejo de salida Unicode + +Los caracteres cirílicos son Unicode, así que asegúrate de que la codificación de tu consola pueda mostrarlos: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Coloca esta línea justo después de que comience el método `Main`. Sin ella, podrías ver signos de interrogación (`?`) en lugar de letras rusas. + +## Ejemplo completo funcionando + +A continuación tienes el código completo, listo para ejecutar. Copia‑pega en `Program.cs`, ajusta las rutas y listo. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Salida esperada** (suponiendo que la imagen de ejemplo dice “Пример текста на русском языке."): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Si ves algo diferente, revisa los consejos de solución de problemas en el Paso 5. + +## Conclusión + +Ahora tienes un ejemplo sólido de extremo a extremo de cómo **ocr russian text** en C# usando Aspose OCR. Desde la instalación de la biblioteca, la configuración del modelo de idioma ruso, hasta la carga de una imagen y su conversión a texto Unicode limpio, cada pieza está cubierta. + +Recuerda, la clave para un OCR fiable es contar con material fuente de calidad: fuentes claras, DPI adecuado y los recursos de idioma correctos. Una vez domines lo básico, puedes ampliar a procesamiento por lotes, integrar con almacenamiento en la nube o incluso combinar con post‑procesamiento de IA para corrección ortográfica. + +### ¿Qué sigue? + +- Explora opciones avanzadas de **aspose ocr c#** como análisis de diseño o salida PDF. +- Combínalo con flujos de trabajo **extract text from image** en Azure Functions para procesamiento sin servidor. +- Prueba diferentes idiomas—simplemente cambia `OcrLanguage.Russian` a `OcrLanguage.English` u otro código soportado. + +¿Tienes preguntas o una imagen complicada que no coopera? Deja un comentario abajo, ¡y feliz codificación! + +![ocr russian text example](ocr-russian-example.png){alt="ejemplo de texto OCR en ruso"} + +## Tutoriales relacionados + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/spanish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..0b74fd45c --- /dev/null +++ b/ocr/spanish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: Reconocer texto de una imagen usando Aspose OCR en C#. Aprende cómo cargar + la imagen para OCR, establecer el idioma del OCR, crear el motor OCR y extraer texto + de un TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: es +og_description: Reconocer texto en una imagen usando Aspose OCR en C#. Este tutorial + muestra cómo crear el motor OCR, cargar la imagen para OCR, establecer el idioma + OCR y extraer texto de un TIFF. +og_title: Reconocer texto de una imagen con Aspose OCR – Guía completa de C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Reconocer texto de una imagen con Aspose OCR – Guía completa de C# +url: /es/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# reconocer texto de imagen con Aspose OCR – Guía completa en C# + +¿Alguna vez necesitaste **reconocer texto de una imagen** pero no estabas seguro de qué biblioteca te ofrecería tanto velocidad como precisión? No estás solo. En muchos proyectos de procesamiento de facturas o archivado, el mayor dolor es obtener texto limpio y buscable a partir de archivos TIFF sin escribir un analizador personalizado. + +La cuestión es que Aspose OCR para .NET hace que todo ese flujo sea pan comido. En esta guía repasaremos todo lo que necesitas: instalar el paquete, **crear el motor OCR**, cargar un TIFF, establecer el idioma del OCR y, finalmente, **extraer texto de un TIFF**. Al final tendrás una aplicación de consola lista para ejecutar que puede **reconocer texto de imagen** en un abrir y cerrar de ojos. + +## Requisitos previos + +- .NET 6.0 o posterior (el código funciona también con .NET Core y .NET Framework) +- Visual Studio 2022 (o cualquier IDE que prefieras) +- Paquete NuGet Aspose.OCR (el soporte GPU requiere el complemento `Aspose.OCR.Gpu`) +- Una GPU con soporte CUDA si deseas la velocidad extra (opcional pero recomendado) + +> **Consejo profesional:** Si no tienes una GPU, simplemente omite la línea `GpuDevice` y el motor volverá automáticamente a la CPU. + +## Paso 1: Instalar Aspose OCR y crear el motor OCR + +Primero, agrega los paquetes necesarios vía NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Ahora podemos **crear el motor OCR**. Este objeto es el corazón del proceso; contiene configuraciones como el dispositivo en el que se ejecuta y los límites de memoria. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Por qué es importante:** Al vincular el motor a una GPU reduces drásticamente el tiempo que lleva **reconocer texto de una imagen**, especialmente para lotes grandes de TIFF de alta resolución. + +## Paso 2: Cargar la imagen para OCR + +A continuación, necesitamos **cargar la imagen para OCR**. Aspose.OCR trabaja con `System.Drawing.Image`, así que cualquier formato compatible con GDI+ (incluido TIFF multipágina) funciona sin problemas. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Si estás trabajando con un TIFF multipágina puedes iterar por las páginas usando `image.SelectActiveFrame`, pero para la mayoría de los casos una sola llamada es suficiente. + +## Paso 3: Establecer el idioma del OCR + +El motor no sabe mágicamente qué idioma estás escaneando. **Establece el idioma del OCR** antes de ejecutar el reconocedor; de lo contrario obtendrás una salida muy confusa. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **¿Lo sabías?** Cambiar de idioma en tiempo de ejecución es barato; incluso puedes procesar un documento multilingüe cambiando esta propiedad entre páginas. + +## Paso 4: Realizar el reconocimiento – reconocer texto de imagen + +Ahora la parte divertida: realmente **reconocer texto de imagen**. El método `Recognize` devuelve una cadena simple con todos los caracteres detectados. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Si necesitas puntuaciones de confianza o cajas delimitadoras puedes usar la sobrecarga que devuelve un objeto `OcrResult`, pero para la mayoría de las tareas de extracción la cadena simple es suficiente. + +## Paso 5: Extraer texto de TIFF (y manejar archivos multipágina) + +Cuando la fuente es un TIFF que contiene varias páginas, querrás repetir los pasos 2‑4 para cada fotograma. Aquí tienes un bucle rápido que **extrae texto de TIFF** página por página: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +El código anterior imprime el texto extraído para cada página, lo que facilita canalizar los resultados a una base de datos o a un índice de búsqueda. + +## Paso 6: Mostrar o guardar el texto extraído + +Finalmente, **mostremos el texto extraído** y, opcionalmente, escribámoslo en un archivo para procesarlo más tarde. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Ejecutar el programa debería mostrar los caracteres reconocidos y crear `extracted_text.txt` junto a tu TIFF de origen. + +--- + +## Preguntas frecuentes y casos límite + +- **¿Qué pasa si mi GPU no se detecta?** + Elimina la línea `GpuDevice`; el motor cambiará automáticamente a modo CPU. El rendimiento será más lento, pero los resultados seguirán siendo precisos. + +- **¿Puedo procesar archivos PNG o JPEG?** + Por supuesto—`Image.FromFile` funciona con cualquier formato soportado por System.Drawing, así que puedes **cargar la imagen para OCR** sin importar la extensión. + +- **¿Cómo manejo escaneos de baja resolución?** + Incrementa `ocrEngine.PreprocessOptions.Dpi` antes de llamar a `Recognize`. Un DPI más alto brinda al motor más píxeles para trabajar, mejorando la precisión. + +- **¿Existe un límite al tamaño del TIFF?** + La propiedad `GpuMemoryLimit` limita el uso de GPU. Si alcanzas el límite, el motor pasará a CPU para las páginas restantes. + +--- + +## Conclusión + +Ahora dispones de un fragmento completo y listo para producción que **reconoce texto de imagen** usando Aspose OCR en C#. El tutorial cubrió cómo **crear el motor OCR**, **cargar la imagen para OCR**, **establecer el idioma del OCR** y **extraer texto de TIFF**, todo aprovechando la aceleración GPU para mayor velocidad. + +A partir de aquí podrías: + +- Experimentar con diferentes idiomas (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, etc.). +- Integrar la salida en un índice buscable de ElasticSearch. +- Añadir post‑procesamiento (corrector ortográfico, limpieza con expresiones regulares) para mejorar la calidad de los datos. + +Pruébalo con tu propio lote de facturas, ajusta los límites de memoria y observa cómo el rendimiento del OCR se dispara. ¡Feliz codificación! + +## Tutoriales relacionados + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extract Text from Image – Recognize Line with Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..fc798a0ca 100644 --- a/ocr/swedish/net/ocr-configuration/_index.md +++ b/ocr/swedish/net/ocr-configuration/_index.md @@ -59,8 +59,10 @@ Lås upp potentialen för OCR och .NET‑applikationer med Aspose.OCR. Lär dig Lås upp kraften i OCR‑bildigenkänning i .NET med Aspose.OCR. Extrahera text enkelt från bilder. ### [OCROoperation med språkval i OCR-bildigenkänning](./ocr-operation-with-language-selection/) 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/) +### [OCROoperation med lista i OCR-bildigenning](./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. +### [Skapa OCR‑motor i C# – Komplett guide](./create-ocr-engine-in-c-complete-guide/) +Skapa en OCR‑motor i C# med en komplett steg‑för‑steg‑guide för Aspose.OCR. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/swedish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..be9d26827 --- /dev/null +++ b/ocr/swedish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Skapa en OCR-motor i C# och lär dig hur du kontrollerar dess utvärderingsläge + och licensstatus med några få rader kod. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: sv +og_description: Skapa OCR-motor i C# och se omedelbart hur du upptäcker utvärderingsläge + och visar licensstatus. +og_title: Skapa OCR-motor i C# – Steg‑för‑steg‑guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Skapa OCR-motor i C# – Komplett guide +url: /sv/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Skapa OCR Engine i C# – Komplett guide + +Har du någonsin undrat hur man **skapa OCR engine**-objekt i C# utan att leta igenom ändlösa dokument? Du är inte ensam. Många utvecklare stöter på problem när de behöver starta en OCR engine, verifiera om den körs i provläge, och visa licensstatusen för användarna. + +I den här handledningen går vi igenom ett kortfattat, end‑to‑end‑exempel som **skapar en OCR engine**, kontrollerar dess **OCR engine evaluation mode**, och skriver ut ett vänligt meddelande om licenstillståndet. När du är klar har du en färdig‑att‑köra konsolapp och en tydlig mental modell för att hantera OCR‑licensiering i dina egna projekt. + +## Vad du kommer att lära dig + +- Hur man instansierar en `OcrEngine` (kärnan i alla OCR‑arbetsflöden). +- Varför det är viktigt att upptäcka **evaluation mode** för efterlevnad och användarupplevelse. +- Det bästa sättet att **check OCR license**‑status och reagera på oväntade tillstånd. +- Vanliga fallgropar—null‑referenser, undantagshantering och versionskonflikter. + +Inga externa verktyg krävs utöver OCR SDK:n du redan har installerad. Om du är bekväm med grundläggande C#‑syntax, är du redo att köra. + +## Förutsättningar + +- .NET 6.0 eller senare (koden kompileras med .NET Core och .NET Framework). +- Ett OCR SDK som exponerar en `OcrEngine`‑klass med en `IsEvaluation`‑egenskap (t.ex. det hypotetiska `MyOcrSdk`). +- En textredigerare eller IDE (Visual Studio, VS Code, Rider—välj din favorit). + +Det är allt. Låt oss dyka ner. + +## Steg 1: Skapa ett nytt konsolprojekt + +Först, skapa en ny konsolapp så att du kan köra koden isolerat. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Öppna den genererade `Program.cs`. Vi kommer att ersätta dess innehåll med ett komplett exempel som **skapar OCR engine**‑instanser och hanterar licensiering. + +## Steg 2: Importera OCR SDK‑namnrymden + +Om SDK:n refereras via NuGet (`MyOcrSdk` är en platshållare), lägg till using‑direktivet högst upp i filen. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Om du ännu inte har lagt till paketet, kör: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** Håll din SDK‑version uppdaterad; nyare versioner förbättrar ofta upptäckten av evalueringsläge. + +## Steg 3: Skapa OCR Engine‑instansen + +Nu skapar vi äntligen **OCR engine**‑objekt. Detta är hjärtat i alla OCR‑arbetsflöden—tänk på det som hjärnan som senare kommer att läsa bilder. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Varför är detta steg avgörande? `OcrEngine` kapslar in all konfiguration, språkpaket och licensdata. Utan den kan du inte bearbeta bilder eller fråga efter evalueringsflaggan. + +> **Side note:** Vissa SDK:n låter dig skicka ett konfigurationsobjekt till konstruktorn (t.ex. språk, DPI). Om du behöver anpassade inställningar, ändra raden därefter. + +## Steg 4: Bestäm OCR Engine Evaluation Mode + +De flesta OCR‑leverantörer levererar en provversion som körs i **evaluation mode** tills en giltig licensnyckel tillhandahålls. Att veta om du är i provläge låter dig visa lämpliga UI‑indikatorer eller begränsa vissa funktioner. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation`‑egenskapen returnerar `true` när motorn är olicensierad eller använder en tidsbegränsad provversion. Det är ett snabbt, pålitligt sätt att skydda premiumfunktioner. + +### Vad händer om egenskapen saknas? + +Äldre SDK‑versioner kan exponera en metod som `GetLicenseInfo()` istället. I så fall skulle du inspektera det returnerade objektet för en `IsTrial`‑flagga. Konsultera alltid SDK‑ändringsloggen vid uppgradering. + +## Steg 5: Visa aktuell licensstatus + +Till sist, låt oss visa användaren om motorn är licensierad eller fortfarande i provläge. En enkel console‑write‑line räcker, men du kan anpassa den för GUI‑appar. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Ternäroperatorn håller koden snygg, och meddelandena är tillräckligt tydliga för slutanvändare eller utvecklare som läser loggar. + +## Fullt fungerande exempel + +Sätter vi ihop allt, här är ett självständigt program som du kan kopiera‑klistra in i `Program.cs` och köra med `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Förväntad utskrift + +- **Trial build:** + `Running in evaluation mode – limited functionality.` + +- **Licensed build:** + `Licensed – full OCR capabilities enabled.` + +Om SDK:n kastar ett undantag (t.ex. saknad native DLL) kommer catch‑blocket att skriva ut ett hjälpsamt felmeddelande istället för att krascha hela appen. + +## Hantera kantfall och vanliga fallgropar + +### 1. Null‑instanser av engine + +Även om konstruktorn vanligtvis returnerar ett giltigt objekt, kan vissa SDK:n returnera `null` om nödvändiga native‑beroenden saknas. Skydda mot det: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Licensutgång under körning + +En provlicens kan gå ut mitt i en session. Fråga periodiskt `IsEvaluation` om din app är igång under en längre tid. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Olika egenskapsnamn mellan versioner + +Äldre versioner kan exponera `engine.EvaluationMode` eller `engine.License.IsTrial`. När du uppgraderar, sök i SDK‑release‑noteringar efter brytande förändringar. + +### 4. Multi‑trådade scenarier + +Om du startar flera OCR‑arbetare, instansiera **en OCR engine per tråd** om inte SDK:n uttryckligen stödjer trådsäker delning. Att dela en enda engine kan leda till race‑conditions och felaktiga licensavläsningar. + +## Pro‑tips för produktionsanvändning + +- **Cache the licensing status** efter den första kontrollen för att undvika onödiga egenskapsanrop. +- **Log the license key** (maskerad) vid start för revisionsspår—hjälper supportteam att diagnostisera licensproblem. +- **Provide a UI toggle** som informerar användare att de är i provläge och erbjuder en “Buy License”-knapp. +- **Automate license renewal** med SDK:ns aktiverings‑API, om tillgängligt, för att hålla användarupplevelsen sömlös. + +## Slutsats + +Vi har precis **skapat OCR engine**‑objekt på några få rader, inspekterat **OCR engine evaluation mode** och skrivit ut ett tydligt **OCR licensing status**‑meddelande. Det fullständiga exemplet körs direkt, hanterar fel på ett elegant sätt och belyser “varför” bakom varje steg—så att du kan anpassa det till desktop, web eller service‑sidor. + +Nästa steg, du kan utforska: + +- Mata in bilder i `engine.Recognize` och hantera flerspråkigt stöd. +- Använda **check OCR license**‑API:er för att programatiskt aktivera en köpt nyckel. +- Integrera med UI‑ramverk (WinForms, WPF, MAUI) för att visa licens‑märken. + +Prova dem, så har du en robust OCR‑grund som är klar för alla applikationer. Lycka till med kodningen! + +## Relaterade handledningar + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/ocr-optimization/_index.md b/ocr/swedish/net/ocr-optimization/_index.md index c5eb6aaed..b7dacd2c8 100644 --- a/ocr/swedish/net/ocr-optimization/_index.md +++ b/ocr/swedish/net/ocr-optimization/_index.md @@ -53,6 +53,9 @@ Dyka ner i OCR‑världen med Aspose.OCR för .NET. Vår handledning om [perform Förbättra OCR‑noggrannheten med Aspose.OCR för .NET genom att utforska [preprocessing filters](./preprocessing-filters-for-image/). Ladda ner nu och upptäck hur du finjusterar dina bilder innan igenkänning. Denna handledning säkerställer sömlös integration, vilket ökar noggrannhet och effektivitet. +### [Förbehandla bild för OCR – Komplett Aspose C#-guide](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Lär dig steg‑för‑steg hur du förbehandlar bilder för optimal OCR med Aspose i C#. + ## Resultatkorrektion med stavningskontroll i OCR Image Recognition Uppnå oöverträffad OCR‑noggrannhet med [Aspose.OCR för .NET](./result-correction-with-spell-checking/). Vår handledning om resultatkorrektion med stavningskontroll ger dig möjlighet att anpassa ordböcker, korrigera stavningar och säkerställa felfri textigenkänning utan ansträngning. Dyka ner i en värld av precision med Aspose.OCR. @@ -70,6 +73,8 @@ Utforska sömlös OCR‑integration med Aspose.OCR för .NET. Identifiera text f Lås upp potentialen i Aspose.OCR för .NET med vår omfattande guide. Lär dig steg‑för‑steg hur du förbereder rektanglar för bildigenkänning. Höj dina .NET‑applikationer med sömlös OCR‑integration. ### [Förbehandlingsfilter för bild i OCR Image Recognition](./preprocessing-filters-for-image/) Utforska Aspose.OCR för .NET. Öka OCR‑noggrannheten med förbehandlingsfilter. Ladda ner nu för sömlös integration. +### [Förbehandla bild för OCR – Komplett Aspose C#-guide](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Lär dig steg‑för‑steg hur du förbehandlar bilder för optimal OCR med Aspose i C#. ### [Resultatkorrektion med stavningskontroll i OCR Image Recognition](./result-correction-with-spell-checking/) 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/) diff --git a/ocr/swedish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/swedish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..6ad3b7628 --- /dev/null +++ b/ocr/swedish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,230 @@ +--- +category: general +date: 2026-05-25 +description: Förbehandla bild för OCR med Aspose för att förbättra OCR‑noggrannheten + och köra OCR på JPEG‑filer. Lär dig hur du extraherar text med Aspose i en tydlig + steg‑för‑steg‑handledning. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: sv +og_description: Förbehandla bilden för OCR med Aspose för att förbättra OCR‑noggrannheten. + Följ den här guiden för att köra OCR på JPEG och extrahera text med Aspose i C#. +og_title: Förbehandla bild för OCR – Aspose C#‑handledning +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Förbehandla bild för OCR – Komplett Aspose C#-guide +url: /sv/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Förbehandla bild för OCR – Komplett Aspose C#-guide + +Har du någonsin undrat hur man **preprocess image for OCR** så att texten blir ren varje gång? Du är inte ensam—utvecklare kämpar ständigt med brusiga skanningar, lågkontrast‑JPEG‑bilder och oförutsägbar belysning. Den goda nyheten? Med några smarta justeringar kan du **improve OCR accuracy** dramatiskt, och Aspose gör det smärtfritt. + +I den här handledningen går vi igenom ett verkligt exempel som visar hur du **run OCR on JPEG**‑bilder, applicerar en anpassad bild‑behandlingspipeline och slutligen **extract text using Aspose**. När du är klar har du ett färdigt C#‑snutt som du kan klistra in i vilket .NET‑projekt som helst. + +## Vad du kommer att lära dig + +- Varför förbehandling är viktig och vilka filter som ger den största vinsten. +- Hur du konfigurerar Aspose.OCR:s `ImageProcessingOptions` för att räta upp, ta bort brus, binarisera och öka kontrasten. +- Den exakta koden som behövs för att **run OCR on JPEG**‑filer och hämta ren text. +- Tips och fallgropar som håller din OCR‑pipeline robust i produktion. + +Ingen tidigare erfarenhet av Aspose krävs; bara en grundläggande C#‑bakgrund och Visual Studio (eller din favoriteditor). Låt oss börja. + +![Preprocess image for OCR example](preprocess-ocr.png "Preprocess image for OCR") + +## Steg 1: Ställ in Aspose.OCR‑motorn – Preprocess Image for OCR + +Först och främst. Vi behöver en `OcrEngine`‑instans och vi måste tala om för den vilket språk vi förväntar oss. I de flesta fall är engelska standard, men du kan byta till franska, tyska osv. genom att ändra `OcrLanguage`‑enumen. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Why this matters:** Motorn är hjärtat i operationen; utan den kan du inte applicera någon av de bildfilter som faktiskt **preprocess image for OCR**. Tänk på den som köket där alla ingredienser blandas. + +## Steg 2: Bygg en anpassad bild‑behandlingspipeline – Improve OCR Accuracy + +Nu kommer den saftiga delen. Aspose låter dig kedja flera filter tillsammans. Nedan aktiverar vi fyra av de mest effektiva: + +1. **Deskew** – räta upp lutande dokument (max 5° som standard). +2. **Denoise** – jämnar ut korniga bakgrunder. +3. **Binarize** – konverterar bilden till svart‑vitt med ett tröskelvärde. +4. **ContrastBoost** – får svaga tecken att sticka ut. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro tip:** Om dina källbilder redan är skarpa kan du sänka `Strength` eller stänga av ett filter helt. Överbearbetning kan ibland radera svaga tecken, så experimentera med riktiga prover. + +## Steg 3: Ladda JPEG (eller någon bild) och kör OCR – Run OCR on JPEG + +Aspose fungerar med alla bildformat som .NET kan läsa—JPEG, PNG, BMP, du namnger dem. Så här matar du en JPEG‑fil i motorn och startar igenkänningsprocessen. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Why JPEG?** JPEG‑komprimering introducerar ofta artefakter som förvirrar OCR. Vår förbehandlingspipeline, särskilt steg för brusreducering och binarisering, mildrar dessa problem och låter dig **run OCR on JPEG** med förtroende. + +## Steg 4: Output det igenkända texten – Extract Text Using Aspose + +Till sist skriver vi helt enkelt ut texten till konsolen, en fil eller någon downstream‑tjänst. För demonstrationsändamål räcker konsolen. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +När du kör programmet bör du se något liknande: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Om utskriften ser förvrängd ut, gå tillbaka till **Step 2** och justera filterinställningarna. Små justeringar ger ofta stora förbättringar i **improve OCR accuracy**. + +## Vanliga kantfall och hur du hanterar dem + +| Situation | Föreslagen justering | +|-----------|----------------------| +| **Mycket mörka bilder** | Öka `ContrastBoost.Level` till 1.5 eller högre. | +| **Snedvridning > 5°** | Höj `DeskewOptions.MaxAngle` (t.ex. 10.0) eller förrotera bilden manuellt. | +| **Färgad text på färgad bakgrund** | Använd `BinarizeOptions` med ett eget tröskelvärde eller byt till `AdaptiveBinarizeOptions`. | +| **Stora filer ( > 5 MB )** | Läs in bilden i en `MemoryStream` först för att undvika fil‑lås‑problem. | + +Dessa justeringar håller din pipeline flexibel och framtidssäker, särskilt när du behöver **extract text using Aspose** från olika källor. + +## Fullständigt fungerande exempel – Alla steg på ett ställe + +Nedan är det kompletta, kopiera‑och‑klistra‑klara programmet. Det kompileras med .NET 6+ och kräver endast `Aspose.OCR`‑NuGet‑paketet. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Spara detta som `Program.cs`, lägg till Aspose.OCR‑paketet (`dotnet add package Aspose.OCR`) och kör `dotnet run`. Du kommer att se den rensade texten skriven till konsolen. + +## Sammanfattning – Varför detta tillvägagångssätt fungerar + +- **Preprocess image for OCR**: Pipen tar bort de vanligaste felkällorna (snedvridning, brus, låg kontrast). +- **Improve OCR accuracy**: Varje filter är fininställt för att öka signal‑till‑brus‑förhållandet som motorn ser. +- **Run OCR on JPEG**: Även komprimerade bilder blir läsbara efter räta upp‑ och binariseringsteg. +- **Extract text using Aspose**: `Recognize`‑metoden returnerar en ren sträng, redo för vidare logik. + +Tillsammans ger dessa steg dig en pålitlig OCR‑lösning i produktionsklass på bara några få rader kod. + +## Nästa steg och relaterade ämnen + +- **Batch processing** – Loopa igenom en mapp med bilder och skriv varje resultat till en `.txt`‑fil. +- **Language packs** – Byt `OcrLanguage.English` mot `OcrLanguage.Spanish` eller lägg till egna ordböcker. +- **PDF extraction** – Kombinera Aspose.OCR med Aspose.PDF för att extrahera text direkt från skannade PDF‑filer. +- **Performance tuning** – Kör motorn parallellt med `Parallel.ForEach` för stora arbetsbelastningar. + +Känn dig fri att experimentera med filtervärdena, prova olika bildformat eller kedja ytterligare Aspose‑filter som `SharpnessOptions`. Himlen är gränsen när du har bemästrat grunderna. + +--- + +*Happy coding! If you hit any snags, drop a comment below and we’ll troubleshoot together.* + +## Relaterade handledningar + +- [Preprocess Image OCR with Aspose.OCR Filters for .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [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/swedish/net/text-recognition/_index.md b/ocr/swedish/net/text-recognition/_index.md index fbefcc10b..377868511 100644 --- a/ocr/swedish/net/text-recognition/_index.md +++ b/ocr/swedish/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Förbättra dina .NET-applikationer med Aspose.OCR för effektiv bildtextigenkä 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. ### [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. +### [Känn igen text från bild med Aspose OCR – Komplett C#-guide](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Lär dig steg-för-steg hur du med Aspose OCR extraherar text från bilder i en komplett C#-guide. +### [Konvertera TIFF till text i C# – Komplett batch-OCR-guide](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Lär dig hur du med Aspose.OCR konverterar TIFF-filer till text i batchprocesser med en komplett C#-guide. +### [Hur du använder OCR i C# – Känn igen kinesisk text från JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Lär dig steg-för-steg hur du med Aspose.OCR i C# extraherar kinesisk text från JPG-bilder. +### [OCR rysk text i C# – Komplett guide med Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Lär dig steg-för-steg hur du med Aspose OCR i C# extraherar rysk text från bilder. +### [Extrahera text från bild i C# – Komplett Aspose OCR-guide](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Steg-för-steg-guide för att med Aspose OCR extrahera text från bilder i C#. +### [Extrahera text från bild i ASP.NET Core Minimal API – Komplett guide](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Lär dig steg-för-steg hur du med Aspose OCR extraherar text från bilder i en ASP.NET Core Minimal API. +### [c# OCR-handledning – Extrahera text från PNG-kvitton med Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Lär dig hur du med Aspose OCR i C# extraherar text från PNG‑kvitton för smidig datahantering. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/swedish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..87e2996b8 --- /dev/null +++ b/ocr/swedish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR-handledning som visar hur man laddar en bildfil i c# och känner + igen png‑text från ett kvitto med Aspose OCR – steg‑för‑steg‑guide. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: sv +og_description: c# OCR-handledning som visar hur du laddar en bildfil i c# och känner + igen png‑text från ett kvitto med Aspose OCR. +og_title: c# OCR-handledning – Extrahera text från PNG‑kvitton +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR-handledning: Extrahera text från PNG‑kvitton med Aspose' +url: /sv/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR‑handledning – Extrahera text från PNG‑kvitton med Aspose + +Har du någonsin behövt en **c# OCR‑handledning** som faktiskt får jobbet gjort utan oändligt Googlande? Du är på rätt plats. I den här guiden kommer vi att **load image file c#**, **recognize png text** och **read receipt OCR**‑resultat, samtidigt som vi visar hur du **perform OCR image**‑bearbetning med Aspose OCR. + +Vi börjar med att installera det nödvändiga NuGet‑paketet, går igenom varje kodrad och avslutar med en prydlig JSON‑dump som du kan skicka direkt till din nästa datapipeline. Inga onödiga utsvävningar, bara en praktisk, kör‑klar lösning. + +## Vad du kommer att lära dig + +- Hur du sätter upp Aspose OCR i ett .NET 6‑projekt (eller senare). +- De exakta stegen för att **load an image file c#** och skicka den till motorn. +- Hur du **recognize png text** från ett kvitto‑foto och fånga resultatet. +- Sätt att **read receipt OCR**‑utdata som snyggt formaterad JSON. +- Tips för **perform OCR image**‑operationer på olika filtyper och hur du hanterar vanliga fallgropar. + +**Förkunskaper** +- Visual Studio 2022 (eller någon annan IDE du föredrar). +- .NET 6 SDK eller nyare. +- En PNG‑kvitto‑bild till hands (vi kallar den `receipt.png`). + +Om du har detta, låt oss dyka ner. + +![c# OCR‑handledning skärmbild](ocr-demo.png "c# OCR‑handledning resultat som visar JSON‑utdata") + +## c# OCR‑handledning – Installera Aspose OCR‑motor + +Först och främst behöver vi Aspose OCR‑biblioteket. Öppna terminalen i lösningsmappen och kör: + +```bash +dotnet add package Aspose.OCR +``` + +Detta enkla kommando hämtar allt som behövs, inklusive inhemska binärer för bildavkodning. När det är installerat, skapa ett nytt konsolprojekt eller lägg till koden i ett befintligt. + +### Varför Aspose? + +Aspose OCR stödjer över 30 språk, fungerar offline och returnerar ett rikt `OcrResult`‑objekt – perfekt för **perform OCR image**‑uppgifter där du behöver mer än bara ren text. + +## Load image file c# och förbered kvittot + +Nu när biblioteket är på plats, låt oss **load image file c#**. Klassen `System.Drawing.Image` sköter det tunga arbetet, men du kan också använda `SkiaSharp` om du föredrar ett plattformsoberoende alternativ. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Proffstips:** Lägg `Image` i ett `using`‑block (som visas) för att frigöra inhemska resurser omedelbart – särskilt viktigt när du **perform OCR image** på många filer i en loop. + +## Recognize PNG text med Aspose + +Med bilden i minnet kan motorn nu **recognize png text**. Aspose returnerar ett `OcrResult` som innehåller både den råa strängen och detaljerad data om varje igenkännt ord. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Varför anropa `RecognizeWithResult` istället för den enklare `Recognize`? Det förra ger dig tillgång till förtroendescore, avgränsningsrutor och radbrytningar – praktiskt om du senare behöver **read receipt OCR** för att extrahera radposter. + +## Read receipt OCR‑resultat som JSON + +De flesta downstream‑system älskar JSON, så låt oss serialisera `OcrResult`. Serialisatorn `System.Text.Json` hanterar komplexa objekt elegant, och vi aktiverar indentering för läsbarhet. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +Den resulterande JSON‑strängen ser ungefär ut så här (trimmad för korthet): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Du kan nu skicka `jsonResult` till en databas, ett meddelandekö eller helt enkelt logga den för felsökning. + +## Perform OCR Image Processing och visa utdata + +Till sist skriver vi ut JSON till konsolen. I en riktig applikation skulle du troligen skriva den till en fil eller skicka den via HTTP, men konsolen gör det enkelt att verifiera att allt fungerar. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Kör programmet (`dotnet run`) så bör du se den snyggt formaterade JSON‑strängen skriven. Om kvittobilden är tydlig blir texten exakt; om den är suddig, överväg att öka bildens upplösning eller applicera ett förbehandlingsfilter (t.ex. gråskala, kontrastökning) innan du matar den till motorn. + +### Hantera vanliga edge‑cases + +| Situation | Vad du gör | +|-----------|------------| +| **Bilden är suddig** | Förbehandla med `System.Drawing` för att skärpa eller öka DPI. | +| **Kvitton innehåller flera språk** | Sätt `ocrEngine.Language = OcrLanguage.English \| OcrLanguage.Spanish;` | +| **Storskalig batch‑bearbetning** | Återanvänd en enda `OcrEngine`‑instans; byt bara `Image` varje iteration. | +| **Minnespress** | Disposera `Image`‑objekt omedelbart och överväg `await Task.Run` för asynkrona pipelines. | + +Dessa justeringar håller ditt **perform OCR image**‑flöde robust även när indata inte är perfekt. + +## Sammanfattning + +Grattis – du har precis slutfört en **c# OCR‑handledning** som laddar en bild, **recognize png text** och **read receipt OCR**‑utdata som ren JSON. De grundläggande stegen (motorinställning, bildladdning, OCR‑körning, serialisering och visning) bildar en solid grund som du kan bygga vidare på för fakturor, pass, eller andra skannade dokument. + +### Vad blir nästa steg? + +- Experimentera med **load image file c#** via `SkiaSharp` för sann plattformsoberoende support. +- Gräv djupare i `OcrResult.Words` för att extrahera radposter, priser och datum – perfekt för utgiftsspårnings‑appar. +- Kombinera den här handledningen med Azure Functions eller AWS Lambda för att bygga ett serverlöst kvitto‑bearbetnings‑API. + +Känn dig fri att justera koden, lägga till fler bilder eller byta till ett annat språkpaket. OCR‑världen är full av överraskningar, och nu har du verktygen för att utforska dem. + +Lycka till med kodandet, och må dina kvitton alltid vara läsbara! + + +## Relaterade handledningar + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Use OCR - Recognize Image without Text Area Detection](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/swedish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..ea8db1333 --- /dev/null +++ b/ocr/swedish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-05-25 +description: Konvertera TIFF till text med Aspose.OCR i C#. Lär dig batchkonvertering + av bilder till text och extrahera text från TIFF‑filer effektivt. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: sv +og_description: Konvertera TIFF till text med Aspose.OCR. Denna guide visar batchkonvertering + av bild till text och hur du extraherar text från TIFF-filer i några få rader C#. +og_title: Konvertera TIFF till text i C# – Komplett batch‑OCR‑guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Konvertera TIFF till text i C# – Komplett batch‑OCR‑guide +url: /sv/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Konvertera TIFF till text i C# – Komplett batch-OCR-guide + +Har du någonsin behövt **konvertera TIFF till text** men varit osäker på var du ska börja? Du är inte ensam—många utvecklare stöter på problem med batch-OCR när de hanterar skannade dokument. I den här handledningen går vi igenom en praktisk lösning som **extraherar text från TIFF**‑filer med Aspose.OCR, och vi gör det parallellt så att stora mappar blir klara på sekunder. + +Vi kommer också att beröra bästa praxis för **batch bild‑till‑text‑konvertering**, så att du i slutet har ett återanvändbart kodsnutt som omvandlar en hel katalog med skannade bilder till prydliga *.txt*-filer—perfekt för indexering, sökning eller för att mata in i efterföljande analyser. + +## Vad du behöver + +- **.NET 6.0** eller senare (koden kompileras även på .NET Framework) +- **Aspose.OCR for .NET** NuGet‑paket (`Install-Package Aspose.OCR`) +- En mapp som innehåller en eller flera *.tif*-filer (det klassiska TIFF‑skanningsformatet) +- Din favorit‑IDE (Visual Studio, VS Code, Rider—vad du än föredrar) + +Det är allt. Inga externa tjänster, inga API‑nycklar, bara ren C# och Aspose. + +![Skärmbild av en TIFF‑fil som bearbetas och den resulterande textfilen](/images/ocr-result.png "OCR‑resultat som visar konverterad TIFF till text‑utdata") + +*(Alt‑text: Skärmbild som visar konverterad TIFF till text‑utdata på skärmen)* + +## Steg 1: Ställ in OCR‑motorn – Konvertera TIFF till text + +Först och främst behöver vi en `OcrEngine`‑instans som vet att den ska läsa engelska tecken. Motorn är hjärtat i konverteringen; att konfigurera den korrekt säkerställer pålitliga resultat. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Varför detta är viktigt:* +Aspose.OCR stöder dussintals språk. Om du hanterar flerspråkiga skanningar, ändra helt enkelt `OcrLanguage.English` till rätt enum‑värde. Att låta språket vara odefinierat tvingar motorn till auto‑detekteringsläge, vilket kan vara långsammare och mindre exakt. + +## Steg 2: Samla alla TIFF‑filer – Extrahera text från TIFF effektivt + +Nästa steg hämtar varje *.tif*-fil från en mapp du anger. Genom att använda `Directory.GetFiles` får vi en ren array som vi kan skicka till batch‑processorn. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro‑tips:* Flaggan `SearchOption.AllDirectories` kan användas om dina skanningar ligger i undermappar. Kom bara ihåg att djupare rekursion kan öka minnesanvändningen under batch‑steget. + +## Steg 3: Utför parallell OCR – Batch bild‑till‑text‑konvertering + +Nu kommer den roliga delen. Aspose.OCR levereras med en statisk hjälpfunktion `BatchOcr.RecognizeAll` som accepterar en array av filsökvägar, en motor och ett `parallelism`‑tips. Vi startar fyra trådar, vilket på en modern quad‑core‑laptop ger nästan linjär hastighetsökning. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Varför parallellism?* +Att skanna en batch med högupplösta TIFF‑filer kan vara CPU‑intensivt. Genom att fördela arbetet över flera trådar håller vi alla kärnor upptagna, vilket kraftigt minskar total körtid. Om du kör detta på en server med fler kärnor, öka `parallelism`‑värdet därefter. + +## Steg 4: Skriv utdata – Konvertera skannade bild‑TXT‑filer + +Till sist loopar vi igenom ordboken och skriver varje textstycke till en *.txt*-fil som har samma grundnamn som originalet. Detta är ögonblicket då **convert scanned images txt** blir verklighet. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Vad koden gör, på enkel svenska + +1. **Skapa** en OCR‑motor inställd på engelska. +2. **Samla** varje TIFF‑fil från mål‑mappen. +3. **Kör** `BatchOcr.RecognizeAll` med fyra trådar, vilket omvandlar varje bild till en sträng. +4. **Loop** över resultaten, byter `.tif`‑ändelsen till `.txt` och skriver strängen till disk. + +Det är hela **convert TIFF to text**‑arbetsflödet på under 50 kodrader. + +## Hantera kantfall – När saker inte går smidigt + +- **Saknade eller korrupta TIFF‑filer** – `BatchOcr` kastar ett `OcrException`. Omge anropet med ett `try / catch` om du behöver en mjuk nedtrappning. +- **Icke‑engelska dokument** – ändra `OcrLanguage.English` till `OcrLanguage.Spanish`, `OcrLanguage.French` osv., eller använd `OcrLanguage.AutoDetect`. +- **Mycket stora bilder** – överväg att sänka DPI innan OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) för att spara minne, även om du kan förlora lite noggrannhet. +- **Utdata‑kodning** – om du behöver en specifik kodsida (t.ex. Windows‑1252), skicka den till `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Pro‑tips för robusta batch‑konverteringar + +- **Logga fel**: skapa en `List failedFiles` och lägg till varje fil som kastar ett undantag; skriv listan till en logg efter loopen. +- **Återanvänd motorn**: samma `OcrEngine`‑instans kan återanvändas för många filer; skapa den inte i loopen. +- **Validera resultatet**: en snabb `if (string.IsNullOrWhiteSpace(extractedText))` kan flagga skanningar som var tomma eller oläsliga. +- **Kombinera med PDF**: om din källa är en flersidig PDF, konvertera varje sida till TIFF först (Aspose.PDF gör det) och kör sedan denna batch. + +## Nästa steg – Gå bortom enkel konvertering + +Nu när du kan **extrahera text från TIFF**‑filer i bulk, kanske du vill: + +- Mata *.txt*-filerna i ett sökindex (Elasticsearch, Azure Cognitive Search). +- Köra språkdetection på varje resultat för att dirigera dokument till lokalspecifika pipelines. +- Generera sökbara PDF‑filer genom att lägga OCR‑texten över de ursprungliga bilderna (Aspose.PDF igen). + +Alla dessa scenarier bygger på samma grundidé: **batch image to text conversion** är en byggsten för större dokument‑bearbetningssystem. + +--- + +### Slutsats + +Du har precis lärt dig hur du **konverterar TIFF till text** med Aspose.OCR, bearbetar en hel mapp parallellt och sparar varje resultat som en ren *.txt*-fil. Lösningen är lättviktig, fullt konfigurerbar och klar för produktion—oavsett om du digitaliserar äldre fakturor, arkiverar skannade kontrakt eller driver en textsökmotor. + +Prova den, justera parallellismen, och börja mata in de nygenererade textfilerna i vilket arbetsflöde du än behöver. Lycka till med OCR! + +--- + +## Relaterade handledningar + +- [Extrahera text från bilder med OCR‑operation på mappar](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extrahera text från bild – OCR‑optimering med Aspose.OCR för .NET](/ocr/english/net/ocr-optimization/) +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/swedish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..8476bb321 --- /dev/null +++ b/ocr/swedish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,303 @@ +--- +category: general +date: 2026-05-25 +description: Lär dig hur du extraherar text från en bild med ett minimalt ASP.NET + Core‑API. Ladda upp bild via POST, läs multipart‑formulärdata och utför OCR på bilden. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: sv +og_description: Extrahera text från bild med ett minimalt ASP.NET Core‑API. Denna + guide visar hur du laddar upp en bild via POST, läser multipart‑formulärdata och + utför OCR på bilden. +og_title: Extrahera text från bild i ASP.NET Core – Steg för steg +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Extrahera text från bild i ASP.NET Core Minimal API – Komplett guide +url: /sv/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahera text från bild i ASP.NET Core Minimal API – Komplett guide + +Har du någonsin undrat hur man **extraherar text från bild** utan att kämpa med tunga ramverk? Du är inte ensam. Många utvecklare behöver ett snabbt sätt att låta användare släppa en bild och få tillbaka de råa tecknen, oavsett om det handlar om att skanna kvitton, digitalisera handskrivna anteckningar eller driva ett sökindex. + +I den här handledningen kommer vi att starta ett litet ASP.NET Core Minimal API som **laddar upp bild via POST**, analyserar *multipart/form‑data*‑payloaden och sedan **utför OCR på bild** med en singleton `OcrEngine`. I slutet har du en fullt körbar app som du kan lägga in i vilket .NET 8‑projekt som helst och börja extrahera text från bild omedelbart. + +## Vad du kommer att bygga + +- En minimal webbapp som lyssnar på `/ocr`. +- En endpoint som accepterar en bildfil som skickas med en `multipart/form-data` POST‑förfrågan. +- Logik som läser den uppladdade filen, matar den till OCR‑motorn och returnerar ren‑textresultat. +- Valfritt GPU‑accelerationssnutt (kommenterad) för dem med ett kompatibelt kort. + +**Förutsättningar** +- .NET 8 SDK (eller senare). +- Grundläggande kunskap om C# och kommandoraden. +- Ett OCR‑bibliotek som exponerar en `OcrEngine`‑klass (exemplet förutsätter ett hypotetiskt NuGet‑paket). + +Om du har detta, låt oss dyka ner. + +## Steg 1: Ställ in projektet och lägg till OCR‑paketet + +Först, skapa ett nytt webbprojekt och hämta OCR‑biblioteket. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Proffstips:** Håll dina beroenden uppdaterade. Nyare versioner ger ofta prestandaförbättringar, särskilt för GPU‑accelererad inferens. + +## Steg 2: Registrera en singleton‑OCR‑motor (primär tjänst) + +Vi vill ha en enda `OcrEngine`‑instans för hela appen—ingen anledning att starta en ny motor per begäran. Registrera den i builderns service‑container. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Varför en singleton?** +Att skapa en OCR‑motor kan vara dyrt—tänk på att ladda neurala nätverksvikter i minnet. Genom att återanvända samma instans sparar vi både CPU‑cykler och RAM, vilket ger snabbare svarstider för varje `/ocr`‑anrop. + +## Steg 3: Bygg applikationen + +Nu materialiserar vi `WebApplication`‑objektet. + +```csharp +var app = builder.Build(); +``` + +Den raden ser nästan magisk ut, men under huven kopplar den upp routing, middleware och DI‑containern som vi just konfigurerade. + +## Steg 4: Definiera POST‑endpointen – “Ladda upp bild via POST” + +Här är hjärtat i handledningen: en endpoint som **laddar upp bild via POST**, läser multipart‑payloaden och överlämnar data till OCR‑motorn. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Genomgång av logiken + +| Steg | Vad händer | Varför det är viktigt | +|------|------------|-----------------------| +| **ReadFormAsync** | Tolkar den inkommande *multipart/form-data*‑förfrågan. | Utan detta kan du inte komma åt de uppladdade filerna. | +| **form.Files["image"]** | Hämtar filen vars formulärfält‑namn är `image`. | Säkerställer ett förutsägbart kontrakt för anroparna. | +| **Content‑type check** | Kontrollerar att filen är en bild (t.ex. `image/png`). | Förhindrar att OCR‑motorn kraschar på icke‑bilddata. | +| **Image.FromStream** | Konverterar den råa strömmen till ett `System.Drawing.Image`. | OCR‑biblioteket förväntar sig ett `Image`‑objekt, inte en rå byte‑array. | +| **ocr.Recognize(img)** | Anropar OCR‑motorn för att **känna igen text från bild**. | Detta är det centrala steget **utföra OCR på bild**. | +| **Results.Text** | Skickar tillbaka ren‑text‑svaret. | Ett enkelt, konsumerbart format för nedströms tjänster. | + +## Steg 5: Kör API:t + +Till sist, starta webbservern. + +```csharp +app.Run(); +``` + +När du kör `dotnet run` kommer API:t att lyssna på `http://localhost:5000` (eller en port du väljer). Du kan testa det med `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Förväntad output:** Konsolen kommer att skriva ut de igenkända tecknen, t.ex.: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Om bilden är suddig eller språket inte stöds kommer OCR‑motorn att returnera en tom sträng eller ett felmeddelande—hantera dessa fall i produktionskod. + +## Särskilda fall & bästa praxis + +### 1. Stora filer + +Standardgränsen för request‑body är 30 MB. För större skanningar kan du behöva justera: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asynkron OCR + +Vissa OCR‑bibliotek exponerar asynkrona metoder (`RecognizeAsync`). Om ditt gör det, ersätt `ocr.Recognize(img)` med `await ocr.RecognizeAsync(img)` och markera lambda‑uttrycket som `async`. + +### 3. Säkerhetsaspekter + +- **Validera filstorlek** innan du laddar den i minnet. +- **Sanitera filnamnet** om du någonsin skriver det till disk. +- **Rate‑limit** endpointen för att undvika denial‑of‑service‑attacker. + +### 4. GPU‑acceleration + +Om du avkommenterar raden `engine.GpuDevice = new GpuDevice(0);` och din hårdvara stödjer CUDA eller DirectML, kommer du märka en tydlig hastighetsökning, särskilt på högupplösta bilder. + +## Fullt fungerande exempel + +Nedan är den kompletta `Program.cs` som du kan kopiera‑klistra in i ett nytt Minimal API‑projekt. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Spara, kör `dotnet run`, och du är redo att **extrahera text från bild** på begäran. + +## Slutsats + +Vi har gått igenom en **komplett, end‑to‑end‑lösning** för att extrahera text från bild med ASP.NET Core Minimal API. Från projekt‑scaffolding har vi **registrerat en singleton‑OCR‑motor**, byggt en endpoint som **laddar upp bild via POST**, **läser multipart‑form‑data**, och slutligen **utför OCR på bild** för att returnera ren ren‑text. + +Från här kan du: + +- Lägg till JSON‑omslag för rikare svar. +- Anslut en databas för att lagra den extraherade texten. +- Utöka stöd till flera språk (`OcrLanguage.Spanish`, etc.). + +Mönstret skalar bra—släng bara samma endpoint i en större mikrotjänst eller exponera den bakom en API‑gateway. + +Har du frågor om hantering av PDF‑filer, batch‑behandling eller GPU‑optimering? Lämna en kommentar, och lycka till med kodandet! + +## Relaterade handledningar + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/swedish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..09bd93a33 --- /dev/null +++ b/ocr/swedish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,294 @@ +--- +category: general +date: 2026-05-25 +description: Extrahera text från bild med C# och Aspose OCR. Lär dig hur du konverterar + jpg till text, laddar bild för OCR och får pålitliga resultat snabbt. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: sv +og_description: Extrahera text från bild med C#. Den här guiden visar hur du konverterar + jpg till text, laddar bild för OCR och hanterar flerspråkigt innehåll. +og_title: Extrahera text från en bild i C# – Aspose OCR-handledning +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Extrahera text från bild i C# – Komplett Aspose OCR‑guide +url: /sv/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Extrahera text från bild i C# – Komplett Aspose OCR-guide + +Har du någonsin undrat hur man **extract text from image** med vanlig C#-kod? Du är inte ensam. Oavsett om du digitaliserar kvitton, skannar skyltar eller bara är nyfiken på OCR, är förmågan att dra ut tecken ur en bild en praktisk färdighet. I den här handledningen går vi igenom ett komplett, körbart exempel som visar exakt hur man **extract text from image** med Aspose.OCR, och vi kommer också att täcka hur man **convert jpg to text**, **load image for OCR**, och svara på den klassiska frågan “**how to ocr image**” en gång för alla. + +I slutet av den här guiden har du en självständig konsolapp som läser en JPEG‑fil, känner igen ukrainska (eller något annat stödjert språk) och skriver ut resultatet i konsolen. Inga vaga referenser, inga saknade delar – bara en komplett lösning som du kan kopiera och köra. + +--- + +## Vad du kommer att lära dig + +* Hur man installerar Aspose.OCR NuGet‑paketet. +* Den exakta koden som behövs för att **load image for OCR** i C#. +* Hur man ställer in språket och faktiskt **extract text from image**. +* Tips för att **convert jpg to text** effektivt. +* Vanliga fallgropar och hur man undviker dem. + +Om du redan har en .NET‑utvecklingsmiljö på plats är du redo att dyka in. Annars får du allt du behöver i avsnittet för förutsättningar nedan. + +--- + +## Förutsättningar + +| Krav | Varför det är viktigt | +|------|-----------------------| +| .NET 6.0 SDK (or newer) | Tillhandahåller runtime för konsolappen. | +| Visual Studio 2022 or VS Code | Gör redigering och felsökning enklare. | +| Internet connection (first run) | NuGet måste ladda ner Aspose.OCR. | +| A JPEG image you want to process (e.g., `ukrainian_sign.jpg`) | Källfilen för OCR‑motorn. | + +> **Pro tip:** Om du använder Linux eller macOS fungerar samma kod med .NET‑CLI (`dotnet new console`), så känn dig fri att hoppa över den tunga IDE:n. + +## Steg 1 – Installera Aspose.OCR via NuGet + +Öppna din terminal (eller Package Manager Console) och kör: + +```bash +dotnet add package Aspose.OCR +``` + +Den enda raden hämtar de senaste Aspose.OCR‑binärerna och alla transitiva beroenden. Ingen manuell DLL‑hantering krävs. + +## Steg 2 – Skapa OCR‑motorn (Kärnan i extraktionen) + +Nu när biblioteket är på plats kan vi skapa en instans av `OcrEngine`. Detta objekt ansvarar för **extracting text from image**‑data. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Varför detta är viktigt:** Motorn kapslar in OCR‑algoritmerna, språkmodellerna och konfigurationsalternativen. Att instansiera den en gång och återanvända den för flera bilder är både minnes‑effektivt och snabbt. + +## Steg 3 – Ladda bild för OCR (och ställ in språket) + +Nästa steg är att tala om för motorn vilken bild som ska läsas. Det är här frasen **load image for OCR** kommer in. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Kantfall:** Om filen inte finns kastar `Image.FromFile` ett `FileNotFoundException`. Omslut anropet i ett try‑catch‑block för produktionskod. + +## Steg 4 – Utför OCR och extrahera text + +Med bilden laddad kan motorn nu **extract text from image**. Metoden `Recognize` gör det tunga arbetet. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Om allt går bra kommer `recognizedText` att innehålla den rena textrepresentationen av allt som OCR‑motorn kunde läsa. + +## Steg 5 – Konvertera JPG till text (sätt ihop allt) + +Koden vi har byggt hittills redan **convert jpg to text**, men låt oss paketera den i en snygg metod som du kan anropa upprepade gånger. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Nu kan du helt enkelt göra: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Förväntad output** (avkortad för korthet): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Om bilden innehåller engelsk text, ändra `OcrLanguage.English` så kommer du att se motsvarande output. + +## Steg 6 – Hantera vanliga “How to OCR Image”-frågor + +### 6.1 Kan jag OCR:a en PNG eller BMP? + +Absolut. Metoden `Image.FromFile` stödjer alla format som System.Drawing känner igen, så peka bara sökvägen till en `.png`‑ eller `.bmp`‑fil och resten av koden förblir identisk. + +### 6.2 Vad händer om bilden har låg upplösning? + +OCR‑noggrannheten sjunker dramatiskt under 300 dpi. En snabb lösning är att skala upp bilden med `Graphics` innan den matas in i motorn: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Behöver jag en licens för Aspose.OCR? + +Aspose erbjuder en gratis provperiod med vattenstämpel. För produktionsanvändning, köp en licens och lägg till: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +## Fullt fungerande exempel + +Nedan är ett komplett, färdigt att köra konsolprogram som demonstrerar **how to OCR image**, **load image for OCR**, och **convert jpg to text** i ett snyggt paket. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Hur du kör det** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Du bör se den extraherade texten skriven i konsolen, vilket bekräftar att du framgångsrikt **extract text from image** med C#. + +## Vanliga fallgropar & pro‑tips + +| Problem | Varför det händer | Lösning | +|---------|-------------------|---------| +| Tomt resultat | Bilden är för mörk eller har låg kontrast. | Förprocessa med `Bitmap` för att öka ljusstyrkan. | +| Fel språk | `Language`‑egenskapen lämnades på standardengelska. | Ange explicit `ocrEngine.Language = OcrLanguage.Ukrainian;` (eller ditt mål). | +| Minnesbrist‑fel | Mycket stora bilder laddas utan att frigöras. | Omslut `Image.FromFile` i ett `using`‑block (som visas). | +| Licensvattenstämpel | Kör på en provversion utan licens. | Applicera en köpt licens tidigt i `Main`. | + +## Slutsats + +Vi har precis gått igenom allt du behöver för att **extract text from image** i C# – från att installera Aspose.OCR, **loading image for OCR**, till **convert jpg to text** och hantera flerspråkiga scenarier. Det kompletta exempelprogrammet knyter ihop alla delar och ger dig en pålitlig grund för alla OCR‑relaterade projekt. + +Nästa steg, du kan utforska: + +* **How to OCR image**‑strömmar istället för filer (använd `MemoryStream`). +* Lägga till **c# image to text**‑efterbehandling som stavningskontroll. +* Integrera OCR‑steget i en större pipeline (t.ex. lagra resultat i en databas). + +Känn dig fri att experimentera med olika språk, bildformat och förbehandlingstrick. OCR är lika mycket en konst som en vetenskap, och ju mer du leker, desto bättre blir resultaten. + +Lycka till med kodandet, och må dina bilder alltid vara läsbara! + +## Relaterade handledningar + +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extrahera text från bild – OCR‑optimering med Aspose.OCR för .NET](/ocr/english/net/ocr-optimization/) +- [Hur man extraherar text från bild genom att förbereda rektanglar i OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/swedish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..90f5afca7 --- /dev/null +++ b/ocr/swedish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-05-25 +description: Hur man använder OCR i C# för att extrahera text från bildfiler. Lär + dig att känna igen kinesiska tecken från en JPG med Aspose.OCR i några enkla steg. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: sv +og_description: Hur man använder OCR i C# för att extrahera text från bildfiler. Denna + guide visar hur du känner igen kinesiska tecken från en JPG med hjälp av Aspose.OCR. +og_title: Hur man använder OCR i C# – Känn igen kinesisk text från JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Hur man använder OCR i C# – Känn igen kinesisk text från JPG +url: /sv/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hur man använder OCR i C# – Känna igen kinesisk text från JPG + +Har du någonsin undrat **hur man använder OCR** för att hämta ord ur en bild du tog med din telefon? Du är inte ensam. I många verkliga projekt—tänk kvittoskannrar, översättningsappar eller automatiserad datainmatning—kommer du behöva **extrahera text från bild** filer snabbt och pålitligt. + +I den här handledningen går vi igenom ett komplett, körbart exempel som **recognizes text from JPG** filer och även hanterar det knepiga fallet **recognize Chinese characters** med hjälp av **OCR Chinese Simplified** språkpaketet. I slutet har du en självständig konsolapp som skriver ut den upptäckta strängen till konsolen, utan extra manuella nedladdningar. + +> **Snabb notering:** Koden fungerar med Aspose.OCR ≥ 23.7, som automatiskt hämtar språkresurser vid första användning. Om du använder en äldre version måste du lägga till språket manuellt. + +## Förutsättningar + +- .NET 6.0 SDK eller senare (exemplet riktar sig mot .NET 6, men .NET 5 fungerar också) +- En recent version of Visual Studio 2022 eller VS Code med C#-tillägget +- En internetanslutning för den första språknedladdningen +- En JPG‑bild som innehåller förenklad kinesisk text (vi kallar den `chinese_sign.jpg`) + +Det är allt—inga tunga OCR‑motorer, ingen hantering av inhemska DLL‑filer. Bara några NuGet‑kommandon och ett par kodrader. + +## Steg 1: Installera Aspose.OCR via NuGet + +Först och främst: vi behöver OCR‑biblioteket. Öppna en terminal i din projektmapp och kör: + +```bash +dotnet add package Aspose.OCR +``` + +Eller, om du föredrar Visual Studio‑gränssnittet, högerklicka på **Dependencies → Manage NuGet Packages**, sök efter “Aspose.OCR” och klicka på **Install**. + +> **Pro tip:** Håll dina paket uppdaterade. Nya språkpaket och prestandaförbättringar kommer i varje mindre version. + +## Steg 2: Skapa ett nytt konsolprojekt (om du inte redan har gjort det) + +Om du börjar från början, skapa en ny konsolapp: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Nu har du en `Program.cs`‑fil klar för OCR‑koden. + +## Steg 3: Skriv OCR‑koden – Känna igen förenklad kinesiska från en JPG + +Öppna `Program.cs` och ersätt dess innehåll med följande. Varje rad är kommenterad så att du kan se *varför* vi gör varje steg, inte bara *vad* vi gör. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Vad händer under huven? + +- **`OcrEngine.Language`** talar om för Aspose vilket lexikon som ska användas. Genom att välja `ChineseSimplified` instruerar vi motorn att leta efter språkpaketet för förenklad kinesiska. +- **First‑time download**: När `Recognize` körs kontaktar SDK:et Aspose:s CDN, hämtar ≈6 MB språkfilen, cachar den lokalt och fortsätter sedan med OCR. Efterföljande anrop är omedelbara. +- **`Image.FromFile`** fungerar med vilket rasterformat som helst som .NET kan avkoda—JPG, PNG, BMP—så du kan **extract text from image** filer av många typer, inte bara JPG. + +## Steg 4: Kör applikationen och verifiera output + +Bygg och kör: + +```bash +dotnet run +``` + +Du bör se något liknande: + +``` +=== Recognized Text === +欢迎光临 +``` + +Om konsolen skriver ut nonsens eller en tom sträng, dubbelkolla att: + +1. Bilden faktiskt innehåller tydliga, högkontrast kinesiska tecken. +2. Filvägen är korrekt (inga extra mellanslag eller saknade filändelser). +3. Din maskin kan nå `https://download.aspose.com` för språkpaketet. + +## Steg 5: Hantera kantfall och vanliga fallgropar + +### 5.1 Hantera lågkvalitativa bilder + +OCR‑noggrannheten minskar när källbilden är suddig, brusig eller har dålig belysning. En snabb lösning är att förbehandla bilden: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Köra i en huvudlös miljö + +Om du distribuerar till en Linux‑container utan GUI, se till att `libgdiplus`‑biblioteket (krävs för `System.Drawing`) är installerat: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Cacha språkpaketet manuellt + +Du kan ladda ner språkfilen en gång och peka Aspose på den via `License`‑API:t, vilket eliminerar det engångsnätverksanropet. Detta är praktiskt för offline‑scenarier. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Fullt fungerande exempel (allt i ett) + +Nedan är det *kompletta* programmet som du kan kopiera och klistra in i `Program.cs`. Inga dolda delar, inga externa skript. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Förväntad output + +Om JPG‑filen innehåller frasen “欢迎光临”, kommer konsolen att skriva ut: + +``` +=== Recognized Text === +欢迎光临 +``` + +Känn dig fri att ersätta bilden med någon annan förenklad kinesisk skylt, gatunamn eller produktetikett—motorn kommer göra sitt bästa. + +## Slutsats + +Vi har precis gått igenom **how to use OCR** i C# för att **extract text from image** filer, specifikt att tackla utmaningen att **recognize Chinese characters** i en **JPG**. Genom att utnyttja Aspose.OCR:s dynamiska språknedladdning kan du hålla din distribution lättviktig samtidigt som du stödjer **OCR Chinese Simplified** direkt ur lådan. + +Vad blir nästa? Prova dessa idéer: + +- **Batch processing**: Loopa igenom en mapp med bilder och skriv varje resultat till en CSV. +- **Combine with translation APIs**: Skicka den igenkända strängen till Azure Translator för real‑tids flerspråkiga appar. +- **Explore other languages**: Byt `OcrLanguage.ChineseSimplified` mot `Japanese` eller `Arabic` och se hur samma kod anpassas. + +Har du frågor om prestandaoptimering, licensiering eller att integrera OCR i en webbtjänst? Lämna en kommentar nedan—lycka till med kodandet! + +--- + +![Skärmbild av konsolutdata som visar hur man använder OCR i C# för att känna igen kinesisk text från en JPG‑bild](ocr-chinese-demo.png "hur man använder OCR konsolutdata") + +## Relaterade handledningar + +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [känna igen text i bild med Aspose OCR för flera språk](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Hur man extraherar text från bild genom att förbereda rektanglar i OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/swedish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/swedish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..d9c4943fb --- /dev/null +++ b/ocr/swedish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: Lär dig hur du OCR:ar rysk text i C# och extraherar text från bild med + Aspose OCR. Steg‑för‑steg‑kod för att snabbt konvertera bild till text i C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: sv +og_description: OCR av rysk text i C# gjort enkelt. Lär dig att extrahera text från + en bild, konvertera bild till text i C# och ladda bild för OCR med Aspose OCR. +og_title: OCR rysk text i C# – Komplett Aspose OCR-guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR rysk text i C# – Komplett guide med Aspose OCR +url: /sv/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR rysk text i C# – Komplett guide med Aspose OCR + +Har du någonsin behövt OCR rysk text i C# men varit osäker på vilket bibliotek du ska lita på? Du är inte ensam. Att få rena, läsbara tecken från en kyrillisk bild kan kännas som att avkoda hemliga meddelanden—särskilt om du inte har ställt in rätt språkmodell. + +I den här handledningen går vi igenom ett praktiskt exempel som visar hur du **extract text from image**-filer, konverterar *image to text C#*-stil, och hanterar nyanserna i rysk språkövervakning med Aspose OCR. I slutet har du en färdig körbar konsolapp som laddar en bild för OCR, skriver ut den igenkända strängen, och ger dig en solid grund för mer avancerade scenarier. + +## Vad du kommer att lära dig + +- Hur du installerar och konfigurerar **Aspose OCR C#** för stöd för ryska språk. +- De exakta stegen för att **load image for OCR** och anropa motorn. +- Tips för att hantera vanliga fallgropar som saknade språkresurser eller suddiga skanningar. +- Sätt att utöka lösningen, såsom batchbearbetning av flera filer eller justering av förtroendetrösklar. + +Ingen tidigare erfarenhet av Aspose krävs; bara en grundläggande förtrogenhet med C# och .NET räcker för att komma igång. + +## Förutsättningar + +Innan vi dyker ner, se till att du har följande: + +1. **.NET 6.0** (eller senare) SDK installerat – koden fungerar både på .NET Core och .NET Framework. +2. **Visual Studio 2022** (eller någon IDE du föredrar). +3. Ett **Aspose.OCR for .NET** NuGet‑paket – du kan hämta en gratis provnyckel från Aspose‑webbplatsen. +4. En **Russian language model**-fil (`rus.traineddata`) – ladda ner den från Aspose‑resurssidan och placera den i en mapp som du senare refererar till. +5. En exempelbild (`russian_doc.png`) som innehåller tydlig kyrillisk text. + +Har du allt? Bra—låt oss börja. + +## Steg 1: Skapa projektet och installera Aspose OCR + +Först, skapa ett nytt konsolprojekt: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Lägg sedan till Aspose OCR‑paketet: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Om du använder en provlicens, håll `Aspose.Total.lic`‑filen tillgänglig; du laddar den i koden för att undvika vattenstämplar. + +När paketet är installerat, öppna `Program.cs`. Du kommer att se standard‑`Main`‑metoden—ersätt dess innehåll med skelettet vi ska bygga. + +## Steg 2: Konfigurera OCR‑motorn för ryskt språk + +Kärnan i operationen är objektet `OcrEngine`. Vi måste tala om två saker för den: vilket språk som ska kännas igen och var språkmodell‑filerna finns. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Varför detta är viktigt:** Om du hoppar över att sätta `Language = OcrLanguage.Russian` så använder motorn engelska som standard, och alla kyrilliska tecken visas som förvrängda symboler. `ResourceFolder` pekar på katalogen som innehåller `rus.traineddata`‑filen; utan den kastar Aspose ett *resource not found*-undantag. + +## Steg 3: Ladda bilden för OCR + +Nu måste vi **load image for OCR**. Aspose OCR fungerar med `System.Drawing.Image`, så du kan skicka in vilket stödformat som helst (PNG, JPEG, BMP osv.). Se till att filsökvägen är korrekt; relativa sökvägar fungerar bra om du har bilden bredvid den körbara filen. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** Om bilden är stor (över 5 MB) kan du vilja skala ner den först. OCR‑noggrannheten sjunker när DPI är för låg, men stora filer kan orsaka minnespress. En snabb storleksändring kan göras med `Graphics` om det behövs. + +## Steg 4: Känn igen texten – Från bild till text i C#‑stil + +Med motorn konfigurerad och bilden laddad är den faktiska igenkänningen ett enda anrop: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +När du kör programmet (`dotnet run`) bör du se något liknande: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Om utskriften ser ut som nonsens, dubbelkolla att: + +- `rus.traineddata`‑filen finns i `ResourceFolder`. +- Bilden är inte för suddig; överväg att applicera ett enkelt binariseringfilter före OCR. +- Språkinställningen verkligen är `OcrLanguage.Russian`. + +## Steg 5: Finjustering och vanliga fallgropar + +### Justering av förtroendetröskel + +Aspose OCR returnerar ett förtroendevärde per tecken internt. Även om API:et inte exponerar det direkt, kan du aktivera **detailed output** för att se vilka ord som hade låg förtroendegrad: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Om du märker frekventa feligenkänningar, prova: + +- **Pre‑processing**: Konvertera bilden till gråskala, öka kontrasten, eller applicera ett medianfilter. +- **DPI settings**: Säkerställ att bilden är minst 300 DPI för kyrilliska skript. + +### Batchbearbetning av flera bilder + +Om du behöver **extract text from image**‑filer i bulk, omslut igenkänningslogiken i en loop: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Nu får varje PNG sin egen `.txt`‑motsvarighet—praktiskt för dokumentarkivering. + +### Hantera Unicode‑utdata + +Cyrilliska tecken är Unicode, så se till att din konsolkodning kan visa dem: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Placera den här raden precis efter att `Main`‑metoden startar. Utan den kan du se frågetecken (`?`) istället för ryska bokstäver. + +## Fullt fungerande exempel + +Nedan är den kompletta, färdigkörbara koden. Kopiera‑klistra in den i `Program.cs`, justera sökvägarna, så är du klar. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Förväntad utskrift** (förutsatt att exempelbilden säger “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Om du ser något annat, gå tillbaka till felsökningstipsen i Steg 5. + +## Slutsats + +Du har nu ett gediget, end‑to‑end‑exempel på hur du **ocr russian text** i C# med Aspose OCR. Från att installera biblioteket, konfigurera den ryska språkmodellen, till att ladda en bild och konvertera den till ren Unicode‑text, varje del är täckt. + +Kom ihåg, nyckeln till pålitlig OCR är bra källmaterial: tydliga typsnitt, tillräcklig DPI och rätt språkresurser. När du behärskar grunderna kan du utöka till batchbearbetning, integrera med molnlagring, eller till och med kombinera med AI‑efterbehandling för stavningskontroll. + +### Vad blir nästa? + +- Utforska avancerade alternativ för **aspose ocr c#**, såsom layoutanalys eller PDF‑utmatning. +- Kombinera detta med **extract text from image**‑arbetsflöden i Azure Functions för serverlös bearbetning. +- Prova olika språk—byt helt enkelt `OcrLanguage.Russian` till `OcrLanguage.English` eller någon annan stödd kod. + +Har du frågor eller en knepig bild som inte samarbetar? Lämna en kommentar nedan, och lycka till med kodandet! + +![ocr russian text example](ocr-russian-example.png){alt="exempel på OCR rysk text"} + +## Relaterade handledningar + +- [Extrahera bildtext i C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Känn igen text i bild med Aspose OCR för flera språk](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Extrahera text från bild med Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/swedish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..fa275a415 --- /dev/null +++ b/ocr/swedish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,210 @@ +--- +category: general +date: 2026-05-25 +description: igenkänna text från bild med Aspose OCR i C#. Lär dig hur du laddar bild + för OCR, ställer in OCR-språk, skapar OCR-motor och extraherar text från TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: sv +og_description: Känn igen text från en bild med Aspose OCR i C#. Denna handledning + visar hur du skapar en OCR-motor, laddar en bild för OCR, ställer in OCR-språk och + extraherar text från en TIFF. +og_title: igenkänn text från bild med Aspose OCR – Komplett C#‑guide +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Känn igen text från bild med Aspose OCR – Komplett C#‑guide +url: /sv/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# igenkänna text från bild med Aspose OCR – Komplett C# Guide + +Har du någonsin behövt **igenkänna text från bild** men varit osäker på vilket bibliotek som ger både hastighet och noggrannhet? Du är inte ensam. I många fakturahanterings‑ eller arkiveringsprojekt är den största smärtan att få ren, sökbar text ur TIFF‑filer utan att skriva en egen parser. + +Här är grejen: Aspose OCR för .NET gör hela pipeline till en barnlek. I den här guiden går vi igenom allt du behöver—installera paketet, **creating OCR engine**, ladda en TIFF, ställa in OCR‑språket och slutligen **extracting text from TIFF**. I slutet har du en färdig konsolapp som kan **recognize text from image**‑filer på ett ögonblick. + +## Förutsättningar + +- .NET 6.0 eller senare (koden fungerar även med .NET Core och .NET Framework) +- Visual Studio 2022 (eller någon IDE du föredrar) +- Aspose.OCR NuGet‑paket (GPU‑stöd kräver `Aspose.OCR.Gpu`‑tillägget) +- Ett GPU med CUDA‑stöd om du vill ha extra hastighet (valfritt men rekommenderas) + +> **Pro tip:** Om du inte har ett GPU, hoppa bara över raden `GpuDevice` så kommer motorn automatiskt att falla tillbaka till CPU. + +## Steg 1: Installera Aspose OCR och skapa OCR‑motor + +Först, lägg till de nödvändiga paketen via NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Nu kan vi **create OCR engine**. Detta objekt är hjärtat i processen; det innehåller konfiguration såsom enheten att köra på och minnesgränser. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Varför detta är viktigt:** Genom att binda motorn till ett GPU minskar du dramatiskt tiden det tar att **recognize text from image**, särskilt för stora batcher av högupplösta TIFF‑filer. + +## Steg 2: Ladda bild för OCR + +Nästa steg, vi behöver **load image for OCR**. Aspose.OCR fungerar med `System.Drawing.Image`, så alla format som stöds av GDI+ (inklusive flersidiga TIFF) fungerar. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Om du hanterar en flersidig TIFF kan du loopa igenom sidorna med `image.SelectActiveFrame`, men för de flesta scenarier räcker ett enda anrop. + +## Steg 3: Ställ in OCR‑språk + +Motorn vet inte magiskt vilket språk du skannar. **Set OCR language** innan du kör igenkännaren; annars får du mycket förvrängd output. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Visste du?** Att byta språk vid körning är billigt—du kan till och med bearbeta ett blandat språk‑dokument genom att ändra denna egenskap mellan sidor. + +## Steg 4: Utför igenkänning – Recognize Text from Image + +Nu det roliga: faktiskt **recognize text from image**. Metoden `Recognize` returnerar en vanlig sträng med alla upptäckta tecken. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Om du behöver förtroendescore eller avgränsningsrutor kan du använda overloaden som returnerar ett `OcrResult`‑objekt, men för de flesta extraktionsuppgifter räcker den vanliga strängen. + +## Steg 5: Extrahera text från TIFF (och hantera flersidiga filer) + +När källan är en TIFF som innehåller flera sidor vill du upprepa steg 2‑4 för varje ram. Här är en snabb loop som **extracts text from TIFF** sida för sida: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Koden ovan skriver ut den extraherade texten för varje sida, vilket gör det enkelt att skicka resultaten till en databas eller ett sökindex. + +## Steg 6: Visa eller spara den extraherade texten + +Till sist, låt oss **display the extracted text** och eventuellt skriva den till en fil för senare bearbetning. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Att köra programmet bör skriva ut de igenkända tecknen och skapa `extracted_text.txt` bredvid din käll‑TIFF. + +--- + +## Vanliga frågor & kantfall + +- **What if my GPU isn’t detected?** + Ta bort raden `GpuDevice`; motorn kommer automatiskt att växla till CPU‑läge. Prestandan blir långsammare men resultaten förblir korrekta. + +- **Can I process PNG or JPEG files?** + Absolut—`Image.FromFile` fungerar med alla format som stöds av System.Drawing, så du kan **load image for OCR** oavsett filändelse. + +- **How do I handle low‑resolution scans?** + Öka `ocrEngine.PreprocessOptions.Dpi` innan du anropar `Recognize`. Högre DPI ger motorn fler pixlar att arbeta med, vilket förbättrar noggrannheten. + +- **Is there a limit to the size of the TIFF?** + Egenskapen `GpuMemoryLimit` begränsar GPU‑användning. Om du når gränsen kommer motorn att falla tillbaka till CPU för de återstående sidorna. + +--- + +## Slutsats + +Du har nu ett komplett, produktionsklart kodexempel som **recognize text from image**‑filer med Aspose OCR i C#. Handledningen täckte hur man **create OCR engine**, **load image for OCR**, **set OCR language** och **extract text from TIFF**—allt medan du utnyttjar GPU‑acceleration för hastighet. + +Från och med nu kan du: + +- Experimentera med olika språk (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, etc.). +- Integrera outputen i ett sökbart ElasticSearch‑index. +- Lägg till efterbearbetning (stavningskontroll, regex‑rengöring) för att förbättra datakvaliteten. + +Prova det på din egen fakturabatch, justera minnesgränserna, och se OCR‑prestandan skjuta i höjden. Lycka till med kodningen! + +## Relaterade handledningar + +- [Extrahera bildtext C# med språkval med Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Hur man extraherar text från bild genom att förbereda rektanglar i OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Extrahera text från bild – igenkänn rad med Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..194a1cbf2 100644 --- a/ocr/thai/net/ocr-configuration/_index.md +++ b/ocr/thai/net/ocr-configuration/_index.md @@ -65,6 +65,8 @@ weight: 24 ### [OCROperation with List in OCR Image Recognition](./ocr-operation-with-list/) ปลดล็อกศักยภาพของ Aspose.OCR for .NET ทำการจดจำภาพด้วย OCR ผ่านรายการได้อย่างง่ายดาย เพิ่มผลผลิตและการสกัดข้อมูลในแอปพลิเคชันของคุณ +### [สร้างเครื่องมือ OCR ใน C# – คู่มือฉบับสมบูรณ์](./create-ocr-engine-in-c-complete-guide/) + ### การใช้งานทั่วไป - **ดึงข้อความจากภาพ** ของใบแจ้งหนี้ที่สแกนเพื่อการบัญชีอัตโนมัติ. - ทำดัชนีอาร์ไคฟ์เอกสารขนาดใหญ่เพื่อเป็นคลังข้อมูลที่ค้นหาได้. @@ -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/thai/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/thai/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..0bc561779 --- /dev/null +++ b/ocr/thai/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,264 @@ +--- +category: general +date: 2026-05-25 +description: สร้างเครื่องมือ OCR ด้วย C# และเรียนรู้วิธีตรวจสอบโหมดประเมินผลและสถานะการให้สิทธิ์ในไม่กี่บรรทัดของโค้ด. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: th +og_description: สร้างเครื่องมือ OCR ด้วย C# และดูได้ทันทีว่าตรวจจับโหมดประเมินค่าอย่างไรและแสดงสถานะการให้สิทธิ์ใช้งาน +og_title: สร้างเครื่องมือ OCR ด้วย C# – คู่มือขั้นตอนต่อขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: สร้าง OCR Engine ด้วย C# – คู่มือฉบับสมบูรณ์ +url: /th/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# สร้าง OCR Engine ใน C# – คู่มือฉบับสมบูรณ์ + +เคยสงสัยไหมว่าจะแนวทาง **create OCR engine** อย่างไรใน C# โดยไม่ต้องค้นหาเอกสารที่ไม่มีที่สิ้นสุด? คุณไม่ได้เป็นคนเดียวที่เจอปัญหา นักพัฒนาหลายคนเจออุปสรรคเมื่อพวกเขาต้องสร้าง OCR engine, ตรวจสอบว่าอยู่ในโหมดทดลองหรือไม่, และแสดงสถานะการให้สิทธิ์ใช้งานให้ผู้ใช้ทราบ + +ในบทแนะนำนี้ เราจะเดินผ่านตัวอย่างสั้น ๆ แบบครบวงจรที่ **creates an OCR engine**, ตรวจสอบ **OCR engine evaluation mode**, และพิมพ์ข้อความที่เป็นมิตรเกี่ยวกับสถานะการให้สิทธิ์ใช้งาน เมื่อจบคุณจะได้แอปคอนโซลที่พร้อมรันและโมเดลความคิดที่ชัดเจนสำหรับการจัดการการให้สิทธิ์ OCR ในโปรเจคของคุณเอง + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีสร้างอินสแตนซ์ของ `OcrEngine` (หัวใจของกระบวนการ OCR ใด ๆ) +- ทำไมการตรวจจับ **evaluation mode** ถึงสำคัญสำหรับการปฏิบัติตามและประสบการณ์ผู้ใช้ +- วิธีที่ดีที่สุดในการ **check OCR license** สถานะและตอบสนองต่อสถานะที่ไม่คาดคิด +- ข้อผิดพลาดทั่วไป—null references, exception handling, และ version mismatches + +ไม่ต้องใช้เครื่องมือภายนอกเพิ่มเติมนอกจาก OCR SDK ที่คุณได้ติดตั้งไว้แล้ว หากคุณคุ้นเคยกับไวยากรณ์พื้นฐานของ C# คุณก็พร้อมแล้ว + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 หรือใหม่กว่า (โค้ดนี้คอมไพล์ได้กับ .NET Core และ .NET Framework) +- OCR SDK ที่เปิดเผยคลาส `OcrEngine` พร้อมคุณสมบัติ `IsEvaluation` (เช่น ตัวอย่างสมมติ `MyOcrSdk`) +- โปรแกรมแก้ไขข้อความหรือ IDE (Visual Studio, VS Code, Rider—เลือกตามที่คุณชอบ) + +เท่านี้แหละ. มาเริ่มกันเลย + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจคคอนโซลใหม่ + +แรกสุด สร้างแอปคอนโซลใหม่เพื่อให้คุณสามารถรันโค้ดแยกจากกันได้ + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +เปิดไฟล์ `Program.cs` ที่สร้างขึ้น เราจะเปลี่ยนเนื้อหาเป็นตัวอย่างสมบูรณ์ที่ **creates OCR engine** อินสแตนซ์และจัดการการให้สิทธิ์ + +## ขั้นตอนที่ 2: นำเข้า Namespace ของ OCR SDK + +สมมติว่า SDK ถูกอ้างอิงผ่าน NuGet (`MyOcrSdk` เป็นเพียงตัวแทน) ให้เพิ่มคำสั่ง using ที่ส่วนบนของไฟล์ + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +หากคุณยังไม่ได้เพิ่มแพ็กเกจ ให้รัน: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro tip:** ควรอัปเดตเวอร์ชัน SDK ของคุณให้เป็นเวอร์ชันล่าสุด; รุ่นใหม่มักปรับปรุงการตรวจจับ evaluation‑mode + +## ขั้นตอนที่ 3: สร้างอินสแตนซ์ของ OCR Engine + +ตอนนี้เราจึง **create OCR engine** อ็อบเจกต์แล้ว นี่คือหัวใจของกระบวนการ OCR ใด ๆ—คิดว่าเป็นสมองที่จะอ่านภาพต่อไป + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +ทำไมขั้นตอนนี้ถึงสำคัญ? `OcrEngine` รวมการตั้งค่าทั้งหมด, แพ็คภาษาต่าง ๆ, และข้อมูลการให้สิทธิ์ หากไม่มีคุณไม่สามารถประมวลผลภาพหรือสอบถามแฟล็ก evaluation ได้ + +> **Side note:** SDK บางตัวอนุญาตให้คุณส่งอ็อบเจกต์การตั้งค่าไปยังคอนสตรัคเตอร์ (เช่น language, DPI). หากต้องการตั้งค่าที่กำหนดเอง ให้แก้ไขบรรทัดนั้นตามต้องการ + +## ขั้นตอนที่ 4: ตรวจสอบ OCR Engine Evaluation Mode + +ผู้จำหน่าย OCR ส่วนใหญ่จะให้เวอร์ชันทดลองที่ทำงานใน **evaluation mode** จนกว่าจะมีคีย์ใบอนุญาตที่ถูกต้อง การรู้ว่าคุณอยู่ในโหมดทดลองช่วยให้คุณแสดง UI ที่เหมาะสมหรือจำกัดฟีเจอร์บางอย่าง + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +คุณสมบัติ `IsEvaluation` จะคืนค่า `true` เมื่อ engine ไม่ได้รับใบอนุญาตหรือใช้การทดลองที่มีเวลาจำกัด นี่เป็นวิธีที่รวดเร็วและเชื่อถือได้ในการปกป้องฟีเจอร์พรีเมี่ยม + +### ถ้าคุณสมบัติหายไป? + +เวอร์ชัน SDK เก่ากว่าอาจเปิดเผยเมธอดเช่น `GetLicenseInfo()` แทน ในกรณีนั้นคุณจะต้องตรวจสอบอ็อบเจกต์ที่คืนค่ามาว่ามีแฟล็ก `IsTrial` หรือไม่ ควรตรวจสอบ changelog ของ SDK เสมอเมื่ออัปเกรด + +## ขั้นตอนที่ 5: แสดงสถานะการให้สิทธิ์ปัจจุบัน + +สุดท้าย ให้แสดงให้ผู้ใช้เห็นว่า engine มีใบอนุญาตหรือยังอยู่ในโหมดทดลอง คำสั่ง console write‑line อย่างง่ายก็ทำได้ แต่คุณสามารถปรับใช้กับแอป GUI ได้ + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +ตัวดำเนินการ ternary ทำให้โค้ดดูเรียบร้อย และข้อความชัดเจนพอสำหรับผู้ใช้ปลายทางหรือผู้พัฒนาที่อ่านล็อก + +## ตัวอย่างทำงานเต็มรูปแบบ + +รวมทุกอย่างเข้าด้วยกัน นี่คือโปรแกรมแบบ self‑contained ที่คุณสามารถคัดลอก‑วางลงใน `Program.cs` แล้วรันด้วย `dotnet run` + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +- **รุ่นทดลอง:** + `Running in evaluation mode – limited functionality.` + +- **รุ่นที่มีใบอนุญาต:** + `Licensed – full OCR capabilities enabled.` + +หาก SDK โยนข้อยกเว้น (เช่น ไฟล์ DLL เนทีฟหาย) บล็อก catch จะพิมพ์ข้อความแสดงข้อผิดพลาดที่เป็นประโยชน์แทนการทำแอปทั้งหมดหยุดทำงาน + +## การจัดการกรณีขอบและข้อผิดพลาดทั่วไป + +### 1. อินสแตนซ์ Engine ที่เป็น null + +แม้ว่าคอนสตรัคเตอร์มักจะคืนอ็อบเจกต์ที่ถูกต้อง, SDK บางตัวอาจคืนค่า `null` หากไม่มีการพึ่งพาเนทีฟที่จำเป็น ควรป้องกันไว้: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. การหมดอายุใบอนุญาตขณะทำงาน + +ใบอนุญาตทดลองอาจหมดอายุระหว่างเซสชัน ควรสอบถาม `IsEvaluation` อย่างสม่ำเสมอหากแอปของคุณทำงานต่อเนื่องเป็นเวลานาน + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. ชื่อคุณสมบัติที่แตกต่างกันระหว่างเวอร์ชัน + +รุ่นเก่าอาจเปิดเผย `engine.EvaluationMode` หรือ `engine.License.IsTrial`. เมื่ออัปเกรด ให้ค้นหาใน release notes ของ SDK เพื่อหาการเปลี่ยนแปลงที่ทำให้โค้ดเสีย + +### 4. สถานการณ์หลายเธรด + +หากคุณสร้าง OCR workers หลายตัว, ให้สร้าง **one OCR engine per thread** เว้นแต่ SDK จะสนับสนุนการแชร์แบบ thread‑safe อย่างชัดเจน การแชร์ engine เดียวอาจทำให้เกิด race conditions และการอ่านสถานะการให้สิทธิ์ที่ผิดพลาด + +## เคล็ดลับสำหรับการใช้งานใน Production + +- **Cache the licensing status** หลังจากการตรวจสอบครั้งแรกเพื่อหลีกเลี่ยงการเรียกคุณสมบัติที่ไม่จำเป็น +- **Log the license key** (masked) เมื่อเริ่มต้นเพื่อเป็น audit trail—ช่วยทีมสนับสนุนวิเคราะห์ปัญหาการให้สิทธิ์ +- **Provide a UI toggle** ที่บอกผู้ใช้ว่าพวกเขาอยู่ในโหมดทดลองและเสนอปุ่ม “Buy License” +- **Automate license renewal** ด้วยการใช้ activation API ของ SDK หากมี เพื่อให้ประสบการณ์ผู้ใช้ต่อเนื่อง + +## สรุป + +เราเพิ่ง **created OCR engine** อ็อบเจกต์ในไม่กี่บรรทัด, ตรวจสอบ **OCR engine evaluation mode**, และพิมพ์ข้อความ **OCR licensing status** ที่ชัดเจน ตัวอย่างเต็มทำงานได้ทันที, จัดการข้อผิดพลาดอย่างราบรื่น, และอธิบาย “ทำไม” ของแต่ละขั้นตอน—เพื่อให้คุณปรับใช้กับเดสก์ท็อป, เว็บ, หรือเซอร์วิส‑ไซด์ได้ + +ต่อไปคุณอาจสำรวจ: + +- ส่งภาพเข้า `engine.Recognize` และจัดการการสนับสนุนหลายภาษา +- ใช้ **check OCR license** API เพื่อเปิดใช้งานคีย์ที่ซื้อโดยโปรแกรม +- ผสานกับ UI framework (WinForms, WPF, MAUI) เพื่อแสดงไอคอนการให้สิทธิ์ + +ลองทำตามดู แล้วคุณจะมีพื้นฐาน OCR ที่แข็งแกร่งพร้อมสำหรับแอปพลิเคชันใด ๆ ขอให้เขียนโค้ดสนุก! + +## บทแนะนำที่เกี่ยวข้อง + +- [วิธีการดึงข้อมูล OCR – การตั้งค่า OCR](/ocr/english/net/ocr-configuration/) +- [วิธีรับผลลัพธ์ OCR ด้วย Aspose.OCR สำหรับ .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [วิธี OCR PDF ใน .NET ด้วย Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/ocr-optimization/_index.md b/ocr/thai/net/ocr-optimization/_index.md index f298064cd..f57a285fa 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 หลายหน้าเป็นเอกสารได้อย่างง่ายดายด้วยคู่มือขั้นตอนต่อขั้นตอนที่ครอบคลุมนี้. +### [การเตรียมภาพสำหรับ OCR – คู่มือ Aspose C# ฉบับสมบูรณ์](./preprocess-image-for-ocr-complete-aspose-c-guide/) +เรียนรู้วิธีการเตรียมภาพอย่างละเอียดเพื่อเพิ่มความแม่นยำ OCR ด้วย Aspose.OCR ใน C# + ## คำถามที่พบบ่อย **Q:** ฉันสามารถแยกข้อความจากไฟล์ภาพที่มีหลายภาษาได้หรือไม่? diff --git a/ocr/thai/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/thai/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..a0ca43ad8 --- /dev/null +++ b/ocr/thai/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,231 @@ +--- +category: general +date: 2026-05-25 +description: เตรียมภาพสำหรับ OCR ด้วย Aspose เพื่อปรับปรุงความแม่นยำของ OCR และทำ + OCR บนไฟล์ JPEG เรียนรู้วิธีดึงข้อความด้วย Aspose ผ่านบทเรียนที่ชัดเจนและเป็นขั้นตอน. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: th +og_description: เตรียมภาพล่วงหน้าสำหรับ OCR ด้วย Aspose เพื่อเพิ่มความแม่นยำของ OCR. + ทำตามคำแนะนำนี้เพื่อทำ OCR บนไฟล์ JPEG และดึงข้อความโดยใช้ Aspose ใน C#. +og_title: เตรียมภาพสำหรับ OCR – บทเรียน Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: การเตรียมภาพสำหรับ OCR – คู่มือ Aspose C# ฉบับสมบูรณ์ +url: /th/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# การเตรียมภาพสำหรับ OCR – คู่มือ Aspose C# ฉบับสมบูรณ์ + +เคยสงสัยว่าจะแก้ไขภาพสำหรับ OCR อย่างไรให้ข้อความออกมาสะอาดทุกครั้ง? คุณไม่ได้เป็นคนเดียว—นักพัฒนาต้องต่อสู้กับสแกนที่มีเสียงรบกวน, JPEG ที่คอนทราสต์ต่ำ, และแสงที่ไม่คงที่อย่างต่อเนื่อง. ข่าวดีคือ? ด้วยการปรับแต่งเล็กน้อยคุณสามารถ **ปรับปรุงความแม่นยำของ OCR** อย่างมาก และ Aspose ทำให้เป็นเรื่องง่าย. + +ในบทแนะนำนี้เราจะเดินผ่านตัวอย่างจากโลกจริงที่แสดงให้คุณเห็นวิธี **run OCR on JPEG** ภาพ, ใช้ pipeline การประมวลผลภาพแบบกำหนดเอง, และสุดท้าย **extract text using Aspose**. เมื่อจบคุณจะได้สคริปต์ C# ที่พร้อมคัดลอกและวางที่คุณสามารถใส่ลงในโปรเจกต์ .NET ใดก็ได้. + +![ตัวอย่างการเตรียมภาพสำหรับ OCR](preprocess-ocr.png "การเตรียมภาพสำหรับ OCR") + +## สิ่งที่คุณจะได้เรียนรู้ + +- ทำไมการเตรียมภาพจึงสำคัญและฟิลเตอร์ใดให้ผลลัพธ์ที่ดีที่สุด. +- วิธีกำหนดค่า `ImageProcessingOptions` ของ Aspose.OCR สำหรับการแก้ไขการเอียง, การลดสัญญาณรบกวน, การทำไบนารี, และการเพิ่มคอนทราสต์. +- โค้ดที่จำเป็นเพื่อ **run OCR on JPEG** ไฟล์และดึงข้อความที่สะอาด. +- เคล็ดลับและข้อควรระวังที่ทำให้ pipeline OCR ของคุณมั่นคงในสภาพการผลิต. + +ไม่จำเป็นต้องมีประสบการณ์กับ Aspose มาก่อน; เพียงพื้นฐาน C# และ Visual Studio (หรือ IDE ที่คุณชื่นชอบ) เท่านั้น. มาเริ่มกันเลย. + +## ขั้นตอนที่ 1: ตั้งค่า Aspose.OCR Engine – การเตรียมภาพสำหรับ OCR + +อย่างแรกเลย เราต้องการอินสแตนซ์ของ `OcrEngine` และต้องบอกว่าต้องการภาษาที่คาดหวัง. ในส่วนใหญ่ภาษาอังกฤษเป็นค่าเริ่มต้น, แต่คุณสามารถเปลี่ยนเป็นภาษาฝรั่งเศส, เยอรมัน ฯลฯ โดยการเปลี่ยนค่า enum `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**ทำไมเรื่องนี้สำคัญ:** Engine เป็นหัวใจของการทำงาน; หากไม่มีคุณไม่สามารถใช้ฟิลเตอร์ภาพใด ๆ ที่จริง ๆ แล้ว **preprocess image for OCR** ได้. คิดว่าเป็นห้องครัวที่ส่วนผสมทั้งหมดถูกผสมเข้าด้วยกัน. + +## ขั้นตอนที่ 2: สร้าง Pipeline การประมวลผลภาพแบบกำหนดเอง – ปรับปรุงความแม่นยำของ OCR + +ต่อมาคือส่วนที่สำคัญ. Aspose ให้คุณเชื่อมต่อฟิลเตอร์หลายตัวเข้าด้วยกัน. ด้านล่างเราเปิดใช้งานสี่ฟิลเตอร์ที่มีประสิทธิภาพที่สุด: + +1. **Deskew** – ทำให้เอกสารที่เอียงตรงขึ้น (ค่าเริ่มต้นสูงสุด 5°). +2. **Denoise** – ทำให้พื้นหลังที่มีเม็ดเกรนเรียบขึ้น. +3. **Binarize** – แปลงภาพเป็นสีขาว‑ดำโดยใช้ค่า threshold. +4. **ContrastBoost** – ทำให้ตัวอักษรที่จางชัดเจนขึ้น. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**เคล็ดลับ:** หากภาพต้นฉบับของคุณคมอยู่แล้ว คุณสามารถลดค่า `Strength` ลงหรือปิดฟิลเตอร์ทั้งหมดได้. การประมวลผลเกินไปอาจลบตัวอักษรที่จางได้, ดังนั้นลองทดลองกับตัวอย่างจริง. + +## ขั้นตอนที่ 3: โหลด JPEG (หรือภาพใดก็ได้) และทำ OCR – ทำ OCR บน JPEG + +Aspose ทำงานกับรูปแบบภาพใด ๆ ที่ .NET สามารถอ่านได้—JPEG, PNG, BMP, ตามที่คุณต้องการ. นี่คือวิธีที่คุณใส่ไฟล์ JPEG เข้าไปใน engine และเริ่มกระบวนการจดจำ. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**ทำไมต้อง JPEG?** การบีบอัด JPEG มักทำให้เกิดอาร์ติแฟคที่ทำให้ OCR สับสน. pipeline การเตรียมภาพของเรา, โดยเฉพาะขั้นตอน denoise และ binarize, ช่วยลดปัญหาเหล่านี้, ทำให้คุณ **run OCR on JPEG** อย่างมั่นใจ. + +## ขั้นตอนที่ 4: แสดงข้อความที่จดจำได้ – ดึงข้อความด้วย Aspose + +สุดท้ายเราจะเขียนข้อความไปยังคอนโซล, ไฟล์, หรือบริการ downstream ใด ๆ. เพื่อการสาธิต, คอนโซลก็เพียงพอ. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +เมื่อคุณรันโปรแกรม, คุณควรเห็นผลลัพธ์ประมาณนี้: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +หากผลลัพธ์ดูเป็นอักขระผิด, กลับไปที่ **Step 2** และปรับค่าฟิลเตอร์. การปรับเล็กน้อยมักให้ผลลัพธ์ใหญ่ในการ **improve OCR accuracy**. + +## กรณีขอบที่พบบ่อยและวิธีจัดการ + +| Situation | Suggested Adjustment | +|-----------|----------------------| +| **ภาพที่มืดมาก** | Increase `ContrastBoost.Level` to 1.5 or higher. | +| **เอียง > 5°** | Raise `DeskewOptions.MaxAngle` (e.g., 10.0) or pre‑rotate the image manually. | +| **ข้อความสีบนพื้นหลังสี** | Use `BinarizeOptions` with a custom threshold or switch to `AdaptiveBinarizeOptions`. | +| **ไฟล์ขนาดใหญ่ ( > 5 MB )** | Load the image into a `MemoryStream` first to avoid file‑lock issues. | + +การปรับแต่งเหล่านี้ทำให้ pipeline ของคุณยืดหยุ่นและพร้อมสำหรับอนาคต, โดยเฉพาะเมื่อคุณต้อง **extract text using Aspose** จากแหล่งที่หลากหลาย. + +## ตัวอย่างทำงานเต็มรูปแบบ – ทุกขั้นตอนในที่เดียว + +ด้านล่างเป็นโปรแกรมที่สมบูรณ์พร้อมคัดลอกและวาง. + +It compiles with .NET 6+ and only requires the `Aspose.OCR` NuGet package. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +บันทึกไฟล์นี้เป็น `Program.cs`, เพิ่มแพคเกจ Aspose.OCR (`dotnet add package Aspose.OCR`), แล้วรัน `dotnet run`. คุณจะเห็นข้อความที่ทำความสะอาดแล้วแสดงบนคอนโซล. + +## สรุป – ทำไมวิธีนี้ถึงได้ผล + +- **Preprocess image for OCR**: Pipeline นี้ลบแหล่งข้อผิดพลาดที่พบบ่อยที่สุด (เอียง, สัญญาณรบกวน, คอนทราสต์ต่ำ). +- **Improve OCR accuracy**: ฟิลเตอร์แต่ละตัวถูกปรับให้เพิ่มอัตราส่วนสัญญาณต่อสัญญาณรบกวนที่ engine เห็น. +- **Run OCR on JPEG**: แม้ภาพที่บีบอัดก็อ่านออกได้หลังจากการแก้เอียงและการทำไบนารี. +- **Extract text using Aspose**: เมธอด `Recognize` คืนค่าเป็นสตริงธรรมดา, พร้อมใช้ในตรรกะ downstream ใด ๆ. + +ร่วมกัน, ขั้นตอนเหล่านี้มอบโซลูชัน OCR ระดับ production‑grade ที่เชื่อถือได้ในไม่กี่บรรทัด. + +## ขั้นตอนต่อไปและหัวข้อที่เกี่ยวข้อง + +- **Batch processing** – วนลูปผ่านโฟลเดอร์ของภาพและเขียนผลลัพธ์แต่ละไฟล์ไปยังไฟล์ `.txt`. +- **Language packs** – เปลี่ยน `OcrLanguage.English` เป็น `OcrLanguage.Spanish` หรือเพิ่มพจนานุกรมกำหนดเอง. +- **PDF extraction** – รวม Aspose.OCR กับ Aspose.PDF เพื่อดึงข้อความโดยตรงจาก PDF ที่สแกน. +- **Performance tuning** – รัน engine แบบขนานโดยใช้ `Parallel.ForEach` สำหรับงานจำนวนมาก. + +อย่าลังเลที่จะทดลองค่าฟิลเตอร์, ลองรูปแบบภาพต่าง ๆ, หรือเชื่อมต่อฟิลเตอร์ Aspose เพิ่มเติมเช่น `SharpnessOptions`. ไม่มีขีดจำกัดเมื่อคุณเชี่ยวชาญพื้นฐานแล้ว. + +--- + +*ขอให้เขียนโค้ดอย่างสนุก! หากเจอปัญหาใด ๆ, ทิ้งคอมเมนต์ด้านล่างและเราจะช่วยแก้ไขร่วมกัน.* + +## บทแนะนำที่เกี่ยวข้อง + +- [การเตรียมภาพ OCR ด้วยฟิลเตอร์ Aspose.OCR สำหรับ .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [ดึงข้อความจากภาพ – การปรับแต่ง 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/text-recognition/_index.md b/ocr/thai/net/text-recognition/_index.md index 7001ea592..017b2cd73 100644 --- a/ocr/thai/net/text-recognition/_index.md +++ b/ocr/thai/net/text-recognition/_index.md @@ -55,9 +55,24 @@ url: /th/net/text-recognition/ ปลดล็อกศักยภาพของ OCR ใน .NET ด้วย Aspose.OCR แยกข้อความจาก PDF ได้อย่างง่ายดาย ดาวน์โหลดทันทีเพื่อประสบการณ์การบูรณาการที่ราบรื่น ### [จดจำตารางในการจดจำรูปภาพ OCR](./recognize-table/) ปลดล็อกศักยภาพของ Aspose.OCR สำหรับ .NET ด้วยคำแนะนำที่ครอบคลุมเกี่ยวกับการจดจำตารางในการจดจำรูปภาพ OCR +### [จดจำข้อความจากภาพด้วย Aspose OCR – คู่มือ C# ฉบับสมบูรณ์](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +เรียนรู้วิธีจดจำข้อความจากภาพด้วย Aspose OCR ใน C# อย่างละเอียด พร้อมตัวอย่างโค้ดและขั้นตอนครบถ้วน +### [วิธีใช้ OCR ใน C# – จดจำข้อความภาษาจีนจาก JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +เรียนรู้วิธีใช้ Aspose.OCR ใน C# เพื่อจดจำข้อความภาษาจีนจากไฟล์ JPG อย่างแม่นยำและง่ายดาย +### [OCR ข้อความภาษารัสเซียใน C# – คู่มือฉบับสมบูรณ์โดยใช้ Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +เรียนรู้วิธีจดจำข้อความภาษารัสเซียจากภาพใน C# ด้วย Aspose OCR อย่างละเอียด พร้อมขั้นตอนและตัวอย่างโค้ด +### [ดึงข้อความจากภาพใน C# – คู่มือ Aspose OCR ฉบับสมบูรณ์](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +เรียนรู้ขั้นตอนเต็มที่ในการใช้ Aspose OCR กับ C# เพื่อดึงข้อความจากภาพอย่างแม่นยำ พร้อมตัวอย่างโค้ดและคำแนะนำที่ครบถ้วน +### [ดึงข้อความจากภาพใน ASP.NET Core Minimal API – คู่มือฉบับสมบูรณ์](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +เรียนรู้วิธีดึงข้อความจากภาพโดยใช้ ASP.NET Core Minimal API อย่างครบถ้วน พร้อมตัวอย่างโค้ดและขั้นตอนที่ชัดเจน +### [บทแนะนำ OCR ด้วย C#: ดึงข้อความจากใบเสร็จ PNG ด้วย Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +เรียนรู้วิธีใช้ Aspose OCR ใน C# เพื่อดึงข้อความจากใบเสร็จรูป PNG อย่างแม่นยำและง่ายดาย +### [แปลง TIFF เป็นข้อความใน C# – คู่มือ OCR แบบแบตช์ครบวงจร](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +เรียนรู้วิธีแปลงไฟล์ TIFF เป็นข้อความด้วย 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/thai/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/thai/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..2e7540fad --- /dev/null +++ b/ocr/thai/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: บทแนะนำ OCR ด้วย C# ที่แสดงวิธีโหลดไฟล์รูปภาพด้วย C# และจดจำข้อความ PNG + จากใบเสร็จโดยใช้ Aspose OCR – คู่มือแบบขั้นตอนต่อขั้นตอน. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: th +og_description: บทเรียน OCR ด้วย C# ที่แนะนำขั้นตอนการโหลดไฟล์รูปภาพด้วย C# และการจดจำข้อความ + PNG จากใบเสร็จโดยใช้ Aspose OCR. +og_title: c# OCR tutorial – ดึงข้อความจากใบเสร็จ PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'บทเรียน OCR ด้วย C#: ดึงข้อความจากใบเสร็จ PNG ด้วย Aspose' +url: /th/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR tutorial – ดึงข้อความจากใบเสร็จ PNG ด้วย Aspose + +Ever needed a **c# OCR tutorial** that actually gets the job done without endless Googling? You're in the right place. In this guide we'll **load image file c#**, **recognize png text**, and **read receipt OCR** results, all while showing you how to **perform OCR image** processing with Aspose OCR. + +We'll start by installing the required NuGet package, walk through each line of code, and finish with a tidy JSON dump you can pipe straight into your next data‑pipeline. No fluff, just a practical, ready‑to‑run solution. + +## สิ่งที่คุณจะได้เรียนรู้ + +- วิธีตั้งค่า Aspose OCR ในโครงการ .NET 6 (หรือใหม่กว่า) +- ขั้นตอนที่แม่นยำเพื่อ **load an image file c#** และส่งให้ engine +- วิธี **recognize png text** จากภาพใบเสร็จและจับผลลัพธ์ +- วิธีการ **read receipt OCR** ผลลัพธ์เป็น JSON ที่จัดรูปแบบอย่างสวยงาม +- เคล็ดลับสำหรับการทำ **perform OCR image** บนไฟล์ประเภทต่าง ๆ และการจัดการกับปัญหาทั่วไป + +**ข้อกำหนดเบื้องต้น** +- Visual Studio 2022 (หรือ IDE ใดก็ได้ที่คุณชอบ) +- .NET 6 SDK หรือใหม่กว่า +- ภาพใบเสร็จ PNG ที่พร้อมใช้งาน (เราจะเรียกมันว่า `receipt.png`) + +ถ้าคุณมีทั้งหมดนี้แล้ว, ไปเริ่มกันเลย. + +![ภาพหน้าจอ c# OCR tutorial](ocr-demo.png "ผลลัพธ์ของ c# OCR tutorial แสดง JSON output") + +## c# OCR Tutorial – การตั้งค่า Aspose OCR Engine + +First off, we need the Aspose OCR library. Open your terminal in the solution folder and run: + +```bash +dotnet add package Aspose.OCR +``` + +That single command pulls in everything required, including native binaries for image decoding. Once installed, create a new console project or add the code to an existing one. + +### ทำไมต้องใช้ Aspose? + +Aspose OCR รองรับภาษามากกว่า 30 ภาษา ทำงานแบบออฟไลน์ และคืนค่าอ็อบเจ็กต์ `OcrResult` ที่เต็มรูปแบบ—เหมาะสำหรับงาน **perform OCR image** ที่คุณต้องการมากกว่าข้อความธรรมดา. + +## Load image file c# and เตรียมใบเสร็จ + +Now that the library is ready, let’s **load image file c#**. The `System.Drawing.Image` class does the heavy lifting, but you could also use `SkiaSharp` if you prefer a cross‑platform alternative. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **เคล็ดลับ:** ห่อ `Image` ด้วยคำสั่ง `using` (ตามที่แสดง) เพื่อปล่อยทรัพยากรเนทีฟโดยเร็ว—สำคัญมากเมื่อคุณ **perform OCR image** กับไฟล์หลายไฟล์ในลูป. + +## Recognize PNG text with Aspose + +With the image in memory, the engine can now **recognize png text**. Aspose returns an `OcrResult` that contains both the raw string and detailed data about each recognized word. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Why call `RecognizeWithResult` instead of the simpler `Recognize`? The former gives you access to confidence scores, bounding boxes, and line breaks—handy if you later need to **read receipt OCR** for line‑item extraction. + +## Read receipt OCR Result as JSON + +Most downstream systems love JSON, so let’s serialize the `OcrResult`. The `System.Text.Json` serializer handles complex objects gracefully, and we’ll enable indentation for readability. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +The resulting JSON looks something like this (trimmed for brevity): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +You can now pipe `jsonResult` into a database, a message queue, or simply log it for debugging. + +## Perform OCR Image Processing and แสดงผลลัพธ์ + +Finally, output the JSON to the console. In a real‑world app you’d probably write it to a file or send it over HTTP, but the console makes it easy to verify everything worked. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Run the program (`dotnet run`) and you should see the nicely formatted JSON printed. If the receipt image is clear, the text will be spot‑on; if not, consider increasing the image resolution or applying a preprocessing filter (e.g., grayscale, contrast boost) before feeding it to the engine. + +### การจัดการกรณีขอบที่พบบ่อย + +| Situation | What to do | +|-----------|------------| +| **ภาพเบลอ** | Pre‑process with `System.Drawing` to sharpen or increase DPI. | +| **ใบเสร็จมีหลายภาษา** | Set `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **การประมวลผลเป็นชุดใหญ่** | Reuse a single `OcrEngine` instance; only change the `Image` each iteration. | +| **ความกดดันของหน่วยความจำ** | Dispose `Image` objects promptly and consider `await Task.Run` for async pipelines. | + +These tweaks keep your **perform OCR image** workflow robust even when the input isn’t perfect. + +## สรุป + +Congratulations—you’ve just completed a **c# OCR tutorial** that loads an image, **recognizes png text**, and **reads receipt OCR** output as clean JSON. The core steps (engine setup, image loading, OCR execution, serialization, and display) form a solid foundation you can extend to invoices, passports, or any other scanned document. + +### ขั้นตอนต่อไป? + +- ทดลองใช้ **load image file c#** กับ `SkiaSharp` เพื่อสนับสนุนแบบข้ามแพลตฟอร์มจริง +- ศึกษา `OcrResult.Words` ให้ลึกขึ้นเพื่อดึงรายการ, ราคา, และวันที่—เหมาะกับแอปติดตามค่าใช้จ่าย +- ผสานบทเรียนนี้กับ Azure Functions หรือ AWS Lambda เพื่อสร้าง API การประมวลผลใบเสร็จแบบ serverless + +Feel free to tweak the code, throw in more images, or even switch to a different language pack. The world of OCR is full of surprises, and now you have the tools to explore them. + +Happy coding, and may your receipts always be readable! + +## บทเรียนที่เกี่ยวข้อง + +- [ดึงข้อความจากภาพ C# ด้วยการเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [ดึงข้อความจากภาพ – การปรับแต่ง OCR ด้วย Aspose.OCR สำหรับ .NET](/ocr/english/net/ocr-optimization/) +- [วิธีใช้ OCR - จดจำภาพโดยไม่ต้องตรวจจับพื้นที่ข้อความ](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/thai/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..2530d6de8 --- /dev/null +++ b/ocr/thai/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,203 @@ +--- +category: general +date: 2026-05-25 +description: แปลงไฟล์ TIFF เป็นข้อความโดยใช้ Aspose.OCR ใน C# เรียนรู้การแปลงภาพเป็นข้อความแบบชุดและสกัดข้อความจากไฟล์ + TIFF อย่างมีประสิทธิภาพ +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: th +og_description: แปลง TIFF เป็นข้อความด้วย Aspose.OCR คู่มือนี้แสดงการแปลงภาพเป็นข้อความเป็นชุดและวิธีดึงข้อความจากไฟล์ + TIFF ด้วยไม่กี่บรรทัดของ C# +og_title: แปลง TIFF เป็นข้อความใน C# – คู่มือ OCR แบบแบตช์ครบถ้วน +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: แปลง TIFF เป็นข้อความใน C# – คู่มือ OCR แบบแบตช์ครบวงจร +url: /th/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# แปลง TIFF เป็นข้อความใน C# – คู่มือ OCR แบบแบตช์เต็มรูปแบบ + +เคยต้อง **แปลง TIFF เป็นข้อความ** แต่ไม่รู้ว่าจะเริ่มต้นอย่างไรหรือไม่? คุณไม่ได้อยู่คนเดียว—นักพัฒนาหลายคนเจอปัญหา OCR แบบแบตช์เมื่อทำงานกับเอกสารสแกน ในบทแนะนำนี้เราจะพาคุณผ่านโซลูชันเชิงปฏิบัติที่ **ดึงข้อความจากไฟล์ TIFF** ด้วย Aspose.OCR และเราจะทำแบบขนานเพื่อให้โฟลเดอร์ขนาดใหญ่เสร็จในไม่กี่วินาที + +เรายังจะพูดถึงแนวปฏิบัติที่ดีที่สุดของ **การแปลงรูปภาพเป็นข้อความแบบแบตช์** ด้วย ดังนั้นเมื่อจบคุณจะได้สคริปต์ที่ใช้ซ้ำได้ซึ่งเปลี่ยนไดเรกทอรีทั้งหมดของรูปสแกนเป็นไฟล์ *.txt* ที่เรียบร้อย—เหมาะสำหรับการทำดัชนี การค้นหา หรือการป้อนเข้าสู่การวิเคราะห์ต่อเนื่อง + +## สิ่งที่คุณต้องเตรียม + +- **.NET 6.0** หรือใหม่กว่า (โค้ดยังคอมไพล์บน .NET Framework ได้เช่นกัน) +- **Aspose.OCR for .NET** NuGet package (`Install-Package Aspose.OCR`) +- โฟลเดอร์ที่มีไฟล์ *.tif* หนึ่งไฟล์หรือมากกว่า (รูปแบบสแกน TIFF คลาสสิก) +- IDE ที่คุณชอบ (Visual Studio, VS Code, Rider—อะไรก็ตามที่คุณถนัด) + +แค่นั้นแหละ ไม่ต้องใช้บริการภายนอก ไม่ต้องมี API key เพียงแค่ C# แท้ ๆ กับ Aspose + +![Screenshot of a TIFF file being processed and the resulting text file](/images/ocr-result.png "OCR result showing converted TIFF to text output") + +*(ข้อความแทนภาพ: ภาพหน้าจอแสดงการแปลง TIFF เป็นข้อความบนหน้าจอ)* + +## ขั้นตอนที่ 1: ตั้งค่า OCR Engine – แปลง TIFF เป็นข้อความ + +ก่อนอื่นเราต้องมีอินสแตนซ์ `OcrEngine` ที่รู้ว่าจะอ่านอักขระภาษาอังกฤษ เครื่องนี้คือหัวใจของการแปลง; การตั้งค่าให้ถูกต้องจะทำให้ได้ผลลัพธ์ที่เชื่อถือได้ + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*ทำไมเรื่องนี้ถึงสำคัญ:* +Aspose.OCR รองรับหลายสิบภาษา หากคุณต้องจัดการกับสแกนหลายภาษา เพียงเปลี่ยน `OcrLanguage.English` เป็นค่า enum ที่เหมาะสม การไม่กำหนดภาษาจะทำให้เครื่องเข้าสู่โหมดตรวจจับอัตโนมัติ ซึ่งอาจช้ากว่าและแม่นยำน้อยลง + +## ขั้นตอนที่ 2: รวบรวมไฟล์ TIFF ทั้งหมด – ดึงข้อความจาก TIFF อย่างมีประสิทธิภาพ + +ต่อไปเราจะดึงไฟล์ *.tif* ทุกไฟล์จากโฟลเดอร์ที่คุณระบุ การใช้ `Directory.GetFiles` จะให้แอเรย์ที่สะอาดซึ่งเราสามารถส่งต่อให้ตัวประมวลผลแบตช์ได้ + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*เคล็ดลับมืออาชีพ:* ธง `SearchOption.AllDirectories` สามารถใช้ได้หากสแกนของคุณอยู่ในโฟลเดอร์ย่อย จำไว้ว่าการทำซ้ำลึกอาจเพิ่มการใช้หน่วยความจำในขั้นตอนแบตช์ + +## ขั้นตอนที่ 3: ทำ OCR แบบขนาน – การแปลงรูปภาพเป็นข้อความแบบแบตช์ + +ตอนนี้เป็นส่วนที่สนุก Aspose.OCR มีตัวช่วยแบบสแตติก `BatchOcr.RecognizeAll` ที่รับอาร์เรย์ของพาธไฟล์, engine, และคำแนะนำ `parallelism` เราจะเปิดใช้สี่เธรด ซึ่งบนแล็ปท็อปคอร์ดสี่คอร์สมัยใหม่ให้ความเร็วที่เกือบเชิงเส้น + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*ทำไมต้องใช้การทำงานขนาน?* +การสแกนแบตช์ของ TIFF ความละเอียดสูงอาจใช้ CPU มาก การกระจายงานไปหลายเธรดทำให้ทุกคอร์ทำงานเต็มที่ ลดระยะเวลาการทำงานอย่างมาก หากคุณรันบนเซิร์ฟเวอร์ที่มีคอร์มากขึ้น ให้เพิ่มค่า `parallelism` ตามจำนวนคอร์ + +## ขั้นตอนที่ 4: เขียนผลลัพธ์ – แปลงรูปสแกนเป็นไฟล์ TXT + +สุดท้ายเราจะวนลูปผ่านดิกชันนารีและเขียนข้อความแต่ละส่วนลงไฟล์ *.txt* ที่ใช้ชื่อฐานเดียวกับไฟล์ต้นฉบับ นี่คือจุดที่ **convert scanned images txt** กลายเป็นความจริง + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### สิ่งที่โค้ดทำ, อธิบายเป็นภาษาอังกฤษง่าย ๆ + +1. **สร้าง** อินสแตนซ์ของ OCR engine ที่ตั้งค่าเป็นภาษาอังกฤษ. +2. **รวบรวม** ไฟล์ TIFF ทุกไฟล์จากโฟลเดอร์เป้าหมาย. +3. **เรียกใช้** `BatchOcr.RecognizeAll` ด้วยสี่เธรด, แปลงแต่ละภาพเป็นสตริง. +4. **วนลูป** ผลลัพธ์, แทนที่นามสกุล `.tif` ด้วย `.txt` และเขียนสตริงลงดิสก์. + +นี่คือเวิร์กโฟลว์ **convert TIFF to text** ทั้งหมดภายในไม่เกิน 50 บรรทัดของโค้ด + +## จัดการกับกรณีขอบ – เมื่อสิ่งต่าง ๆ ไม่เป็นไปตามที่คาด + +- **ไฟล์ TIFF ที่หายหรือเสีย** – `BatchOcr` จะโยน `OcrException` ให้ห่อการเรียกใน `try / catch` หากต้องการการทำงานแบบล่ม gracefully. +- **เอกสารที่ไม่ใช่ภาษาอังกฤษ** – เปลี่ยน `OcrLanguage.English` เป็น `OcrLanguage.Spanish`, `OcrLanguage.French` เป็นต้น หรือใช้ `OcrLanguage.AutoDetect`. +- **ภาพขนาดใหญ่มาก** – พิจารณาลด DPI ก่อน OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) เพื่อประหยัดหน่วยความจำ แม้อาจสูญเสียความแม่นยำบ้าง. +- **การเข้ารหัสผลลัพธ์** – หากต้องการ code page เฉพาะ (เช่น Windows‑1252) ให้ส่งผ่านไปยัง `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## เคล็ดลับมืออาชีพสำหรับการแปลงแบตช์ที่มั่นคง + +- **บันทึกความล้มเหลว**: สร้าง `List failedFiles` แล้วเพิ่มไฟล์ที่เกิดข้อผิดพลาด; เขียนรายการนี้ลงไฟล์ล็อกหลังลูป. +- **ใช้ engine ซ้ำ**: อินสแตนซ์ `OcrEngine` เดียวกันสามารถใช้ซ้ำได้หลายไฟล์; อย่าสร้างใหม่ภายในลูป. +- **ตรวจสอบผลลัพธ์**: การตรวจ `if (string.IsNullOrWhiteSpace(extractedText))` อย่างรวดเร็วสามารถระบุสแกนที่ว่างหรืออ่านไม่ออก. +- **รวมกับ PDF**: หากแหล่งของคุณเป็น PDF หลายหน้า ให้แปลงแต่ละหน้าเป็น TIFF ก่อน (Aspose.PDF ทำได้) แล้วรันแบตช์นี้ต่อ. + +## ขั้นตอนต่อไป – ไปไกลกว่าการแปลงแบบง่าย + +เมื่อคุณสามารถ **ดึงข้อความจากไฟล์ TIFF** เป็นจำนวนมากได้แล้ว คุณอาจต้องการ: + +- ป้อนไฟล์ *.txt* ไปยังดัชนีการค้นหา (Elasticsearch, Azure Cognitive Search). +- รันการตรวจจับภาษาในแต่ละผลลัพธ์เพื่อส่งเอกสารไปยัง pipeline ตามภาษาที่เหมาะสม. +- สร้าง PDF ที่ค้นหาได้โดยวางข้อความ OCR กลับบนภาพต้นฉบับ (ใช้ Aspose.PDF อีกครั้ง). + +ทุกสถานการณ์เหล่านี้อิงจากแนวคิดหลักเดียวกัน: **batch image to text conversion** เป็นบล็อกสร้างระบบประมวลผลเอกสารที่ใหญ่ขึ้น + +--- + +### สรุป + +คุณเพิ่งเรียนรู้วิธี **แปลง TIFF เป็นข้อความ** ด้วย Aspose.OCR, ประมวลผลโฟลเดอร์ทั้งหมดแบบขนาน, และบันทึกผลลัพธ์แต่ละไฟล์เป็น *.txt* ที่เรียบร้อย โซลูชันนี้เบา, ปรับแต่งได้เต็มที่, พร้อมใช้งานในโปรดักชัน—ไม่ว่าจะเป็นการดิจิไทซ์ใบแจ้งหนี้เก่า, การเก็บสำเนาสัญญาที่สแกน, หรือการขับเคลื่อนเครื่องมือค้นหาข้อความ + +ลองใช้ ปรับค่า parallelism ตามต้องการ แล้วเริ่มป้อนไฟล์ข้อความใหม่เหล่านี้เข้าสู่ workflow ที่คุณต้องการ Happy OCRing! + +--- + + +## บทแนะนำที่เกี่ยวข้อง + +- [ดึงข้อความจากรูปภาพโดยใช้การทำ OCR บนโฟลเดอร์](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [ดึงข้อความจากรูปภาพ – การปรับแต่ง 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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/thai/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..a2bb99737 --- /dev/null +++ b/ocr/thai/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,302 @@ +--- +category: general +date: 2026-05-25 +description: เรียนรู้วิธีดึงข้อความจากรูปภาพด้วย API ASP.NET Core ขั้นต่ำ อัปโหลดรูปภาพผ่าน + POST อ่านข้อมูลแบบ multipart form และทำ OCR บนรูปภาพ. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: th +og_description: ดึงข้อความจากภาพโดยใช้ ASP.NET Core API แบบ Minimal คู่มือนี้แสดงวิธีอัปโหลดภาพผ่าน + POST, อ่านข้อมูลแบบ multipart form, และทำ OCR บนภาพ +og_title: สกัดข้อความจากภาพใน ASP.NET Core – ทีละขั้นตอน +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: สกัดข้อความจากรูปภาพใน ASP.NET Core Minimal API – คู่มือฉบับสมบูรณ์ +url: /th/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดึงข้อความจากภาพใน ASP.NET Core Minimal API – คู่มือฉบับสมบูรณ์ + +เคยสงสัยไหมว่า **ดึงข้อความจากภาพ** อย่างไรโดยไม่ต้องพึ่งพาเฟรมเวิร์กขนาดใหญ่? คุณไม่ได้อยู่คนเดียว นักพัฒนาหลายคนต้องการวิธีที่รวดเร็วให้ผู้ใช้ลากรูปภาพแล้วได้ข้อความดิบกลับมา ไม่ว่าจะเป็นการสแกนใบเสร็จ, แปลงโน้ตมือเขียนเป็นดิจิทัล, หรือเสริมดัชนีการค้นหา + +ในบทเรียนนี้เราจะสร้าง ASP.NET Core Minimal API ขนาดเล็กที่ **อัปโหลดภาพผ่าน POST**, แยก payload แบบ *multipart/form‑data*, แล้ว **perform OCR on image** ด้วย singleton `OcrEngine` เมื่อเสร็จคุณจะได้แอปที่พร้อมรันที่สามารถใส่ลงในโปรเจกต์ .NET 8 ใดก็ได้และเริ่มดึงข้อความจากภาพได้ทันที + +## สิ่งที่คุณจะสร้าง + +- แอปเว็บขนาดเล็กที่รับฟังที่ `/ocr` +- Endpoint ที่รับไฟล์ภาพผ่านคำขอ `multipart/form-data` แบบ POST +- โลจิกที่อ่านไฟล์ที่อัปโหลด, ส่งให้ OCR engine, แล้วคืนผลเป็นข้อความธรรมดา +- ตัวอย่างการเร่งความเร็วด้วย GPU (คอมเมนต์ไว้) สำหรับผู้ที่มีการ์ดที่รองรับ + +**ข้อกำหนดเบื้องต้น** +- .NET 8 SDK (หรือใหม่กว่า) +- ความคุ้นเคยพื้นฐานกับ C# และ command line +- ไลบรารี OCR ที่มีคลาส `OcrEngine` (ตัวอย่างสมมติว่ามี NuGet package) + +ถ้าคุณมีทั้งหมดนี้แล้ว ไปต่อกันเลย + +## ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์และเพิ่มแพคเกจ OCR + +แรกเริ่มสร้างโปรเจกต์เว็บใหม่และดึงไลบรารี OCR เข้ามา + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **เคล็ดลับ:** คอยอัปเดต dependencies ของคุณ เวอร์ชันใหม่มักมาพร้อมกับประสิทธิภาพที่ดีขึ้น โดยเฉพาะการ inference ที่เร่งด้วย GPU + +## ขั้นตอนที่ 2: ลงทะเบียน Singleton OCR Engine (บริการหลัก) + +เราต้องการอินสแตนซ์ `OcrEngine` เพียงหนึ่งตัวสำหรับทั้งแอป – ไม่ต้องสร้าง engine ใหม่ทุกคำขอ ลงทะเบียนใน service container ของ builder + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**ทำไมต้องเป็น singleton?** +การสร้าง OCR engine มีค่าใช้จ่ายสูง – คิดถึงการโหลดน้ำหนักของ neural‑network เข้า memory การใช้อินสแตนซ์เดียวช่วยประหยัด CPU และ RAM ทำให้เวลาตอบสนองของทุกคำขอ `/ocr` เร็วขึ้น + +## ขั้นตอนที่ 3: สร้างแอปพลิเคชัน + +ตอนนี้เราจะ materialize วัตถุ `WebApplication` + +```csharp +var app = builder.Build(); +``` + +บรรทัดนั้นดูเหมือนเวทมนตร์ แต่เบื้องหลังมันได้เชื่อม routing, middleware, และ DI container ที่เราตั้งค่าไว้แล้ว + +## ขั้นตอนที่ 4: กำหนด POST Endpoint – “Upload Image via POST” + +นี่คือหัวใจของบทเรียน: endpoint ที่ **upload image via POST**, อ่าน payload แบบ multipart, แล้วส่งข้อมูลให้ OCR engine + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### วิเคราะห์โลจิก + +| ขั้นตอน | สิ่งที่เกิดขึ้น | ทำไมถึงสำคัญ | +|------|--------------|----------------| +| **ReadFormAsync** | แยกคำขอ *multipart/form-data* ที่เข้ามา | หากไม่มีคุณจะไม่สามารถเข้าถึงไฟล์ที่อัปโหลดได้ | +| **form.Files["image"]** | ดึงไฟล์ที่มีชื่อฟิลด์ `image` | ทำให้สัญญา (contract) กับผู้เรียกคาดเดาได้ | +| **Content‑type check** | ตรวจสอบว่าไฟล์เป็นภาพ (เช่น `image/png`) | ป้องกัน OCR engine จากการทำงานกับข้อมูลที่ไม่ใช่ภาพ | +| **Image.FromStream** | แปลงสตรีมดิบเป็น `System.Drawing.Image` | ไลบรารี OCR ต้องการอ็อบเจ็กต์ `Image` ไม่ใช่ byte array | +| **ocr.Recognize(img)** | เรียก OCR engine เพื่อ **how to recognize text from image** | นี่คือขั้นตอนหลักของ **perform OCR on image** | +| **Results.Text** | ส่งกลับผลลัพธ์เป็นข้อความธรรมดา | รูปแบบง่ายต่อการใช้งานต่อในบริการอื่น | + +## ขั้นตอนที่ 5: รัน API + +สุดท้าย เริ่มเว็บเซิร์ฟเวอร์ + +```csharp +app.Run(); +``` + +เมื่อคุณรัน `dotnet run` API จะฟังที่ `http://localhost:5000` (หรือพอร์ตที่คุณกำหนด) คุณสามารถทดสอบด้วย `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**ผลลัพธ์ที่คาดหวัง:** คอนโซลจะแสดงอักขระที่จำได้ เช่น: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +หากภาพเบลอหรือภาษาที่ใช้ไม่รองรับ OCR engine จะคืนสตริงว่างหรือข้อความข้อผิดพลาด – ควรจัดการกรณีเหล่านี้ในโค้ด production + +## กรณีขอบและแนวปฏิบัติที่ดีที่สุด + +### 1. ไฟล์ขนาดใหญ่ + +ขีดจำกัด body ของคำขอเริ่มต้นที่ 30 MB หากต้องจัดการสแกนที่ใหญ่กว่านี้อาจต้องปรับ: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR แบบอะซิงโครนัส + +บางไลบรารี OCR มีเมธอด async (`RecognizeAsync`) หากมีให้แทนที่ `ocr.Recognize(img)` ด้วย `await ocr.RecognizeAsync(img)` และทำให้ lambda เป็น `async` + +### 3. พิจารณาด้านความปลอดภัย + +- **ตรวจสอบขนาดไฟล์** ก่อนโหลดเข้าสู่ memory +- **ทำความสะอาดชื่อไฟล์** หากต้องบันทึกลงดิสก์ +- **จำกัดอัตราการเรียก** endpoint เพื่อป้องกันการโจมตีแบบ denial‑of‑service + +### 4. การเร่งความเร็วด้วย GPU + +หากคุณยกคอมเมนต์บรรทัด `engine.GpuDevice = new GpuDevice(0);` และฮาร์ดแวร์รองรับ CUDA หรือ DirectML คุณจะเห็นความเร็วเพิ่มขึ้นอย่างชัดเจน โดยเฉพาะกับภาพความละเอียดสูง + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นไฟล์ `Program.cs` เต็มรูปแบบที่คุณสามารถคัดลอก‑วางลงในโปรเจกต์ Minimal API ใหม่ + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +บันทึก, รัน `dotnet run`, แล้วคุณพร้อม **extract text from image** ตามต้องการ + +## สรุป + +เราได้เดินผ่าน **โซลูชันครบวงจร** สำหรับการดึงข้อความจากภาพด้วย ASP.NET Core Minimal API ตั้งแต่การสร้างโครงงาน, **ลงทะเบียน singleton OCR engine**, สร้าง endpoint ที่ **uploads image via POST**, **read multipart form data**, และสุดท้าย **perform OCR on image** เพื่อคืนผลเป็น plain‑text + +ต่อจากนี้คุณสามารถ: + +- เพิ่ม wrapper แบบ JSON เพื่อให้ผลลัพธ์มีรายละเอียดมากขึ้น +- เชื่อมต่อฐานข้อมูลเพื่อเก็บข้อความที่ดึงได้ +- รองรับหลายภาษา (`OcrLanguage.Spanish` เป็นต้น) + +แพทเทิร์นนี้ขยายได้ง่าย – เพียงแค่ใส่ endpoint เดียวกันลงในไมโครเซอร์วิสที่ใหญ่ขึ้นหรือเปิดให้ผ่าน API gateway + +มีคำถามเกี่ยวกับการจัดการ PDF, การประมวลผลเป็นชุด, หรือการปรับ GPU? แสดงความคิดเห็นได้เลย, Happy coding! + +## บทเรียนที่เกี่ยวข้อง + +- [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/thai/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/thai/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..12018a3cf --- /dev/null +++ b/ocr/thai/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: ดึงข้อความจากภาพด้วย C# และ Aspose OCR. เรียนรู้วิธีแปลง JPG เป็นข้อความ, + โหลดภาพสำหรับ OCR, และรับผลลัพธ์ที่เชื่อถือได้อย่างรวดเร็ว. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: th +og_description: ดึงข้อความจากภาพด้วย C#. คู่มือนี้แสดงวิธีแปลง JPG เป็นข้อความ, โหลดภาพสำหรับ + OCR, และจัดการเนื้อหาหลายภาษา. +og_title: ดึงข้อความจากภาพใน C# – บทเรียน Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: สกัดข้อความจากภาพใน C# – คู่มือ Aspose OCR ฉบับสมบูรณ์ +url: /th/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ดึงข้อความจากรูปภาพใน C# – คู่มือ Aspose OCR ฉบับเต็ม + +เคยสงสัยไหมว่า **ดึงข้อความจากรูปภาพ** ด้วยโค้ด C# ธรรมดาจะทำอย่างไร? คุณไม่ได้เป็นคนเดียว ไม่ว่าคุณจะกำลังแปลงใบเสร็จ, สแกนป้ายโฆษณา, หรือแค่อยากรู้เรื่อง OCR ความสามารถในการดึงอักขระจากรูปภาพเป็นทักษะที่มีประโยชน์ ในบทแนะนำนี้เราจะเดินผ่านตัวอย่างเต็มที่สามารถรันได้ซึ่งแสดงวิธี **ดึงข้อความจากรูปภาพ** ด้วย Aspose.OCR พร้อมทั้งครอบคลุมวิธี **แปลง jpg เป็นข้อความ**, **โหลดรูปภาพสำหรับ OCR**, และตอบคำถามคลาสสิก “**วิธี OCR รูปภาพ**” อย่างถาวร + +เมื่ออ่านคู่มือนี้จนจบ คุณจะมีแอปคอนโซลที่ทำงานอิสระซึ่งอ่านไฟล์ JPEG, จำแนกภาษายูเครน (หรือภาษาอื่นที่รองรับ) และพิมพ์ผลลัพธ์ลงคอนโซล ไม่ต้องอ้างอิงที่คลุมเครือ ไม่ต้องหาชิ้นส่วนที่หายไป—เพียงโซลูชันครบถ้วนที่คุณคัดลอก‑วางและรันได้ + +--- + +## สิ่งที่คุณจะได้เรียนรู้ + +* วิธีติดตั้งแพคเกจ NuGet ของ Aspose.OCR +* โค้ดที่จำเป็นเพื่อ **โหลดรูปภาพสำหรับ OCR** ใน C# +* วิธีตั้งค่าภาษาและ **ดึงข้อความจากรูปภาพ** จริง ๆ +* เคล็ดลับสำหรับการ **แปลง jpg เป็นข้อความ** อย่างมีประสิทธิภาพ +* ปัญหาที่พบบ่อยและวิธีหลีกเลี่ยง + +ถ้าคุณมีสภาพแวดล้อมการพัฒนา .NET ตั้งไว้แล้ว คุณพร้อมจะดำดิ่งต่อ หากยังไม่มี ส่วน “ข้อกำหนดเบื้องต้น” ด้านล่างจะช่วยให้คุณพร้อม + +--- + +## ข้อกำหนดเบื้องต้น + +| ความต้องการ | ทำไมจึงสำคัญ | +|-------------|----------------| +| .NET 6.0 SDK (หรือใหม่กว่า) | ให้ runtime สำหรับแอปคอนโซล | +| Visual Studio 2022 หรือ VS Code | ทำให้การแก้ไขและดีบักง่ายขึ้น | +| การเชื่อมต่ออินเทอร์เน็ต (ครั้งแรก) | NuGet ต้องดาวน์โหลด Aspose.OCR | +| ภาพ JPEG ที่คุณต้องการประมวลผล (เช่น `ukrainian_sign.jpg`) | ไฟล์ต้นทางสำหรับเครื่อง OCR | + +> **เคล็ดลับ:** หากคุณใช้ Linux หรือ macOS โค้ดเดียวกันทำงานได้กับ .NET CLI (`dotnet new console`) ดังนั้นคุณสามารถข้าม IDE ที่หนักได้เลย + +--- + +## ขั้นตอนที่ 1 – ติดตั้ง Aspose.OCR ผ่าน NuGet + +เปิดเทอร์มินัล (หรือ Package Manager Console) แล้วรัน: + +```bash +dotnet add package Aspose.OCR +``` + +บรรทัดเดียวนี้จะดึงไบนารีล่าสุดของ Aspose.OCR และทุก dependency ที่เกี่ยวข้อง ไม่ต้องจัดการ DLL ด้วยตนเอง + +--- + +## ขั้นตอนที่ 2 – สร้าง OCR Engine (หัวใจของการสกัด) + +เมื่อไลบรารีพร้อม เราสามารถสร้างอินสแตนซ์ของ `OcrEngine` ได้ วัตถุนี้รับผิดชอบ **การดึงข้อความจากรูปภาพ** + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **ทำไมถึงสำคัญ:** Engine จะบรรจุอัลกอริทึม OCR, โมเดลภาษา, และตัวเลือกการกำหนดค่า การสร้างครั้งเดียวและใช้ซ้ำหลายภาพช่วยประหยัดหน่วยความจำและเร็วขึ้น + +--- + +## ขั้นตอนที่ 3 – โหลดรูปภาพสำหรับ OCR (และตั้งค่าภาษา) + +ขั้นตอนต่อไปคือบอก Engine ว่าจะอ่านรูปภาพไหน นี่คือจุดที่วลี **โหลดรูปภาพสำหรับ OCR** เข้ามาใช้ + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **กรณีขอบ:** หากไฟล์ไม่มีอยู่ `Image.FromFile` จะโยน `FileNotFoundException` ควรห่อการเรียกในบล็อก try‑catch สำหรับโค้ด production + +--- + +## ขั้นตอนที่ 4 – ทำ OCR และดึงข้อความ + +เมื่อโหลดรูปภาพแล้ว Engine สามารถ **ดึงข้อความจากรูปภาพ** ได้แล้ว เมธอด `Recognize` จะทำงานหนักให้ + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +หากทุกอย่างเป็นไปด้วยดี `recognizedText` จะมีข้อความแบบ plain‑text ของทุกอย่างที่ Engine สามารถอ่านได้ + +--- + +## ขั้นตอนที่ 5 – แปลง JPG เป็นข้อความ (รวมทุกอย่างไว้ในเมธอดเดียว) + +โค้ดที่เราสร้างจนถึงตอนนี้แล้ว **แปลง jpg เป็นข้อความ** อยู่แล้ว แต่เราจะห่อไว้ในเมธอดที่เรียกได้หลายครั้ง + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +จากนั้นคุณสามารถเรียกง่าย ๆ แบบนี้: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**ผลลัพธ์ที่คาดหวัง** (ตัดบางส่วนเพื่อความกระชับ): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +หากรูปมีข้อความภาษาอังกฤษ ให้เปลี่ยนเป็น `OcrLanguage.English` แล้วคุณจะเห็นผลลัพธ์ที่สอดคล้อง + +--- + +## ขั้นตอนที่ 6 – การจัดการคำถาม “วิธี OCR รูปภาพ” ที่พบบ่อย + +### 6.1 ฉันสามารถ OCR PNG หรือ BMP ได้หรือไม่? + +ทำได้แน่นอน เมธอด `Image.FromFile` รองรับฟอร์แมตทั้งหมดที่ System.Drawing รับรู้ เพียงชี้พาธไปที่ไฟล์ `.png` หรือ `.bmp` แล้วโค้ดส่วนที่เหลือไม่ต้องเปลี่ยน + +### 6.2 ถ้ารูปภาพความละเอียดต่ำจะทำอย่างไร? + +ความแม่นยำของ OCR ลดลงอย่างมากเมื่อต่ำกว่า 300 dpi วิธีแก้เร็วคืออัปสเกลรูปด้วย `Graphics` ก่อนส่งให้ Engine: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 ฉันต้องมีลิขสิทธิ์สำหรับ Aspose.OCR หรือไม่? + +Aspose มีรุ่นทดลองฟรีพร้อมลายน้ำ สำหรับการใช้งานจริงต้องซื้อไลเซนส์และเพิ่ม: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## ตัวอย่างทำงานเต็มรูปแบบ + +ด้านล่างเป็นแอปคอนโซลที่พร้อมรันซึ่งสาธิต **วิธี OCR รูปภาพ**, **โหลดรูปภาพสำหรับ OCR**, และ **แปลง jpg เป็นข้อความ** ในแพคเกจเดียวที่เรียบร้อย + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**วิธีรัน** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +คุณควรเห็นข้อความที่ดึงออกมาปรากฏบนคอนโซล ยืนยันว่าคุณได้ **ดึงข้อความจากรูปภาพ** ด้วย C# สำเร็จแล้ว + +--- + +## ปัญหาที่พบบ่อย & เคล็ดลับระดับมืออาชีพ + +| ปัญหา | ทำไมถึงเกิด | วิธีแก้ | +|-------|------------|--------| +| ผลลัพธ์เป็นค่าว่าง | รูปภาพมืดหรือคอนทราสต์ต่ำ | ทำการพรี‑โปรเซสด้วย `Bitmap` เพื่อเพิ่มความสว่าง | +| ภาษาไม่ถูกต้อง | คุณสมบัติ `Language` ยังคงเป็นค่าเริ่มต้นอังกฤษ | ตั้งค่า `ocrEngine.Language = OcrLanguage.Ukrainian;` (หรือภาษาที่ต้องการ) | +| เกิด Out‑of‑memory | โหลดรูปภาพขนาดใหญ่มากโดยไม่ปล่อยทรัพยากร | ห่อ `Image.FromFile` ด้วยบล็อก `using` (ตามที่แสดง) | +| ลายน้ำไลเซนส์ | รันบนรุ่นทดลองโดยไม่มีไลเซนส์ | ใส่ไลเซนส์ที่ซื้อไว้ตั้งแต่ต้นใน `Main` | + +--- + +## สรุป + +เราได้ครอบคลุมทุกอย่างที่คุณต้องการเพื่อ **ดึงข้อความจากรูปภาพ** ด้วย C# — ตั้งแต่การติดตั้ง Aspose.OCR, **โหลดรูปภาพสำหรับ OCR**, ไปจนถึง **แปลง jpg เป็นข้อความ** และการจัดการสถานการณ์หลายภาษา ตัวอย่างโปรแกรมเต็มรูปแบบเชื่อมต่อทุกส่วนให้คุณมีพื้นฐานที่มั่นคงสำหรับโครงการ OCR ใด ๆ + +ต่อไปคุณอาจสำรวจ: + +* **วิธี OCR รูปภาพ** จากสตรีมแทนไฟล์ (ใช้ `MemoryStream`) +* เพิ่มการประมวลผลหลัง OCR เช่น **c# image to text** เพื่อตรวจสอบการสะกดคำ +* ผสานขั้นตอน OCR เข้ากับ pipeline ที่ใหญ่ขึ้น (เช่น เก็บผลลัพธ์ในฐานข้อมูล) + +ลองเล่นกับภาษา, ฟอร์แมตรูปภาพ, และเทคนิคพรี‑โปรเซสต่าง ๆ OCR เป็นศิลปะและวิทยาศาสตร์ร่วมกัน ยิ่งคุณทดลองมาก ผลลัพธ์ก็ยิ่งดี + +ขอให้เขียนโค้ดสนุกและรูปภาพของคุณอ่านออกได้เสมอ! + +## บทแนะนำที่เกี่ยวข้อง + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/thai/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..db0816ce7 --- /dev/null +++ b/ocr/thai/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,298 @@ +--- +category: general +date: 2026-05-25 +description: วิธีใช้ OCR ใน C# เพื่อดึงข้อความจากไฟล์รูปภาพ เรียนรู้การจดจำอักษรจีนจากไฟล์ + JPG ด้วย Aspose.OCR ในไม่กี่ขั้นตอนง่าย ๆ +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: th +og_description: วิธีใช้ OCR ใน C# เพื่อดึงข้อความจากไฟล์รูปภาพ คู่มือนี้จะแสดงวิธีการจดจำอักษรจีนจากไฟล์ + JPG ด้วย Aspose.OCR. +og_title: วิธีใช้ OCR ใน C# – แยกข้อความจีนจากไฟล์ JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: วิธีใช้ OCR ใน C# – แยกข้อความจีนจากไฟล์ JPG +url: /th/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# วิธีใช้ OCR ใน C# – จดจำข้อความจีนจาก JPG + +เคยสงสัย **วิธีใช้ OCR** เพื่อดึงคำจากรูปภาพที่คุณถ่ายด้วยโทรศัพท์หรือไม่? คุณไม่ได้เป็นคนเดียว ในหลายโครงการจริง—เช่น เครื่องสแกนใบเสร็จ, แอปแปลภาษา, หรือการบันทึกข้อมูลอัตโนมัติ—คุณจะต้อง **extract text from image** ไฟล์อย่างรวดเร็วและเชื่อถือได้ + +ในบทแนะนำนี้ เราจะพาคุณผ่านตัวอย่างที่สมบูรณ์และสามารถรันได้ ซึ่ง **recognizes text from JPG** ไฟล์และแม้กระทั่งจัดการกับกรณีที่ท้าทายของ **recognize Chinese characters** ด้วยแพ็คเกจภาษา **OCR Chinese Simplified**. เมื่อเสร็จคุณจะมีแอปคอนโซลที่ทำงานอิสระซึ่งพิมพ์สตริงที่ตรวจพบลงในคอนโซลโดยไม่ต้องดาวน์โหลดเพิ่มเติมใด ๆ + +> **หมายเหตุเร็ว:** โค้ดนี้ทำงานกับ Aspose.OCR ≥ 23.7 ซึ่งจะดึงทรัพยากรภาษาโดยอัตโนมัติในครั้งแรกที่ใช้ หากคุณใช้เวอร์ชันเก่ากว่า คุณจะต้องเพิ่มภาษาด้วยตนเอง + +## ข้อกำหนดเบื้องต้น + +- .NET 6.0 SDK หรือใหม่กว่า (ตัวอย่างใช้ .NET 6 แต่ .NET 5 ก็ทำงานได้เช่นกัน) +- Visual Studio 2022 รุ่นล่าสุดหรือ VS Code พร้อมส่วนขยาย C# +- การเชื่อมต่ออินเทอร์เน็ตสำหรับการดาวน์โหลดภาษาครั้งแรก +- รูปภาพ JPG ที่มีข้อความจีนแบบ Simplified (เราจะเรียกมันว่า `chinese_sign.jpg`) + +เท่านี้—ไม่มีเครื่อง OCR ขนาดใหญ่ ไม่มีการจัดการ DLL แบบเนทีฟ เพียงแค่คำสั่ง NuGet ไม่กี่คำและบรรทัดโค้ดไม่กี่บรรทัด + +## ขั้นตอนที่ 1: ติดตั้ง Aspose.OCR ผ่าน NuGet + +อันดับแรก เราต้องการไลบรารี OCR เปิดเทอร์มินัลในโฟลเดอร์โปรเจกต์ของคุณและรัน: + +```bash +dotnet add package Aspose.OCR +``` + +หรือหากคุณชอบใช้ UI ของ Visual Studio ให้คลิกขวาที่ **Dependencies → Manage NuGet Packages**, ค้นหา “Aspose.OCR” แล้วคลิก **Install**. + +> **เคล็ดลับ:** คอยอัปเดตแพคเกจของคุณให้เป็นเวอร์ชันล่าสุด แพ็คเกจภาษาใหม่และการปรับปรุงประสิทธิภาพจะมาพร้อมกับแต่ละเวอร์ชันย่อย + +## ขั้นตอนที่ 2: สร้างโปรเจกต์คอนโซลใหม่ (หากคุณยังไม่ได้ทำ) + +หากคุณเริ่มจากศูนย์ ให้สร้างแอปคอนโซลใหม่: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +ตอนนี้คุณมีไฟล์ `Program.cs` พร้อมสำหรับโค้ด OCR แล้ว + +## ขั้นตอนที่ 3: เขียนโค้ด OCR – จดจำ Chinese Simplified จาก JPG + +เปิด `Program.cs` แล้วแทนที่เนื้อหาด้วยโค้ดต่อไปนี้ ทุกบรรทัดมีคำอธิบายเพื่อให้คุณเห็น *ทำไม* เราถึงทำขั้นตอนนั้น ไม่ใช่แค่ *ทำอะไร*. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### สิ่งที่เกิดขึ้นเบื้องหลัง + +- **`OcrEngine.Language`** บอก Aspose ว่าจะใช้พจนานุกรมใด โดยเลือก `ChineseSimplified` เราจะสั่งให้เอ็นจิ้นค้นหาแพ็คเกจภาษาจีนแบบ Simplified +- **First‑time download**: เมื่อเรียก `Recognize` SDK จะติดต่อ CDN ของ Aspose ดึงไฟล์ภาษาขนาด ≈6 MB เก็บไว้ในแคชบนเครื่อง แล้วดำเนินการ OCR การเรียกครั้งต่อไปจะทำได้ทันที +- **`Image.FromFile`** ทำงานกับรูปแบบแรสเตอร์ใด ๆ ที่ .NET สามารถถอดรหัสได้—JPG, PNG, BMP—ดังนั้นคุณสามารถ **extract text from image** ไฟล์หลายประเภท ไม่ใช่แค่ JPG + +## ขั้นตอนที่ 4: รันแอปพลิเคชันและตรวจสอบผลลัพธ์ + +ทำการคอมไพล์และรัน: + +```bash +dotnet run +``` + +คุณควรเห็นผลลัพธ์ประมาณนี้: + +``` +=== Recognized Text === +欢迎光临 +``` + +หากคอนโซลพิมพ์ข้อความแปลก ๆ หรือสตริงว่าง ให้ตรวจสอบว่า: + +1. ภาพจริง ๆ มีอักขระจีนที่ชัดเจนและคอนทราสต์สูง +2. เส้นทางไฟล์ถูกต้อง (ไม่มีช่องว่างแปลก ๆ หรือขาดนามสกุล) +3. เครื่องของคุณสามารถเข้าถึง `https://download.aspose.com` เพื่อดาวน์โหลดแพ็คเกจภาษา + +## ขั้นตอนที่ 5: การจัดการกับกรณีขอบและข้อผิดพลาดทั่วไป + +### 5.1 การจัดการกับภาพคุณภาพต่ำ + +ความแม่นยำของ OCR ลดลงเมื่อภาพต้นฉบับเบลอ มีสัญญาณรบกวน หรือแสงไม่ดี วิธีแก้เร็วคือทำการประมวลผลล่วงหน้าภาพ: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 การรันในสภาพแวดล้อม Headless + +หากคุณกำลังปรับใช้ในคอนเทนเนอร์ Linux ที่ไม่มี GUI ให้ตรวจสอบว่าติดตั้งไลบรารี `libgdiplus` (ที่จำเป็นสำหรับ `System.Drawing`) แล้ว: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 แคชแพ็คเกจภาษาแบบแมนนวล + +คุณสามารถดาวน์โหลดไฟล์ภาษาเพียงครั้งเดียวและชี้ให้ Aspose ใช้ผ่าน API `License` ซึ่งจะขจัดการเรียกเครือข่ายครั้งเดียวนี้ เหมาะสำหรับสถานการณ์ออฟไลน์ + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## ตัวอย่างทำงานเต็มรูปแบบ (All‑In‑One) + +ด้านล่างเป็นโปรแกรม *ครบถ้วน* ที่คุณสามารถคัดลอกและวางลงใน `Program.cs` ไม่มีส่วนที่ซ่อนอยู่หรือสคริปต์ภายนอก + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### ผลลัพธ์ที่คาดหวัง + +หาก JPG มีวลี “欢迎光临” คอนโซลจะพิมพ์: + +``` +=== Recognized Text === +欢迎光临 +``` + +คุณสามารถเปลี่ยนภาพเป็นป้ายจีน Simplified ใด ๆ เช่น ชื่อถนน หรือป้ายสินค้า—เอ็นจิ้นจะทำอย่างดีที่สุด + +## สรุป + +เราเพิ่งอธิบาย **วิธีใช้ OCR** ใน C# เพื่อ **extract text from image** ไฟล์ โดยเฉพาะการจัดการกับความท้าทายของ **recognize Chinese characters** ใน **JPG** ด้วยการใช้การดาวน์โหลดภาษาของ Aspose.OCR แบบ on‑the‑fly คุณสามารถทำให้การปรับใช้ของคุณเบา ๆ แต่ยังรองรับ **OCR Chinese Simplified** ได้ทันที + +ต่อไปทำอะไรดี? ลองไอเดียเหล่านี้: + +- **Batch processing**: วนลูปผ่านโฟลเดอร์ของภาพและเขียนผลลัพธ์แต่ละรายการลงใน CSV +- **Combine with translation APIs**: ส่งสตริงที่จดจำได้ไปยัง Azure Translator เพื่อสร้างแอปหลายภาษาที่ทำงานแบบเรียลไทม์ +- **Explore other languages**: เปลี่ยน `OcrLanguage.ChineseSimplified` เป็น `Japanese` หรือ `Arabic` แล้วดูว่าโค้ดเดียวกันปรับตัวอย่างไร + +มีคำถามเกี่ยวกับการปรับประสิทธิภาพ, การลิขสิทธิ์, หรือการรวม OCR เข้ากับเว็บเซอร์วิสหรือไม่? แสดงความคิดเห็นด้านล่าง—ขอให้สนุกกับการเขียนโค้ด! + +--- + +![Screenshot of console output showing how to use OCR in C# to recognize Chinese text from a JPG image](ocr-chinese-demo.png "how to use OCR console output") + +## บทแนะนำที่เกี่ยวข้อง + +- [ดึงข้อความจากภาพ 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](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/thai/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/thai/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..c10d2d715 --- /dev/null +++ b/ocr/thai/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: เรียนรู้วิธีทำ OCR ข้อความภาษารัสเซียใน C# และดึงข้อความจากรูปภาพด้วย + Aspose OCR. โค้ดขั้นตอนต่อขั้นตอนเพื่อแปลงรูปภาพเป็นข้อความใน C# อย่างรวดเร็ว. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: th +og_description: ทำให้การ OCR ข้อความรัสเซียใน C# ง่ายขึ้น เรียนรู้วิธีดึงข้อความจากภาพ, + แปลงภาพเป็นข้อความใน C#, และโหลดภาพสำหรับ OCR ด้วย Aspose OCR. +og_title: OCR ข้อความรัสเซียใน C# – คู่มือ Aspose OCR ฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR ข้อความรัสเซียใน C# – คู่มือฉบับเต็มโดยใช้ Aspose OCR +url: /th/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Russian Text in C# – Complete Guide Using Aspose OCR + +เคยต้องการทำ OCR ข้อความรัสเซียใน C# แต่ไม่แน่ใจว่าจะใช้ไลบรารีใด? คุณไม่ได้อยู่คนเดียว การดึงอักขระที่อ่านได้จากภาพที่เป็น Cyrillic อาจรู้สึกเหมือนถอดรหัสข้อความลับ—โดยเฉพาะอย่างยิ่งหากคุณยังไม่ได้ตั้งค่าโมเดลภาษาที่ถูกต้อง + +ในบทแนะนำนี้เราจะพาคุณผ่านตัวอย่างเชิงปฏิบัติที่แสดงวิธี **extract text from image** files, แปลง *image to text C#* style, และจัดการกับความละเอียดของการรู้จำภาษารัสเซียด้วย Aspose OCR. เมื่อเสร็จสิ้นคุณจะมีแอปคอนโซลที่พร้อมรันซึ่งโหลดภาพสำหรับ OCR, พิมพ์สตริงที่รู้จำได้, และให้พื้นฐานที่มั่นคงสำหรับสถานการณ์ที่ซับซ้อนยิ่งขึ้น + +## What You’ll Learn + +- วิธีติดตั้งและกำหนดค่า **Aspose OCR C#** สำหรับการสนับสนุนภาษารัสเซีย +- ขั้นตอนที่แน่นอนเพื่อ **load image for OCR** และเรียกใช้เอนจิน +- เคล็ดลับในการจัดการกับปัญหาทั่วไป เช่น การขาดแหล่งข้อมูลภาษา หรือสแกนที่เบลอ +- วิธีขยายโซลูชัน เช่น การประมวลผลเป็นชุดหลายไฟล์หรือปรับค่า confidence threshold + +ไม่จำเป็นต้องมีประสบการณ์กับ Aspose มาก่อน; เพียงความคุ้นเคยพื้นฐานกับ C# และ .NET ก็พอที่จะเริ่มได้ + +## Prerequisites + +ก่อนที่เราจะเริ่ม, ตรวจสอบว่าคุณมีสิ่งต่อไปนี้: + +1. **.NET 6.0** (หรือใหม่กว่า) SDK ที่ติดตั้งแล้ว – โค้ดทำงานได้ทั้งบน .NET Core และ .NET Framework +2. **Visual Studio 2022** (หรือ IDE ที่คุณชอบ) +3. แพคเกจ **Aspose.OCR for .NET** จาก NuGet – คุณสามารถรับคีย์ทดลองฟรีจากเว็บไซต์ Aspose +4. ไฟล์ **Russian language model** (`rus.traineddata`) – ดาวน์โหลดจากหน้า resource ของ Aspose แล้ววางไว้ในโฟลเดอร์ที่คุณจะอ้างอิงต่อไป +5. ตัวอย่างภาพ (`russian_doc.png`) ที่มีข้อความ Cyrillic ชัดเจน + +พร้อมหรือยัง? ดีมาก—มาเริ่มกันเลย + +## Step 1: Set Up the Project and Install Aspose OCR + +แรกเริ่ม, สร้างโปรเจกต์คอนโซลใหม่: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +จากนั้นเพิ่มแพคเกจ Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** หากคุณใช้ไลเซนส์ทดลอง, เก็บไฟล์ `Aspose.Total.lic` ไว้ใกล้มือ; คุณจะโหลดไฟล์นี้ในโค้ดเพื่อหลีกเลี่ยง watermark + +เมื่อแพคเกจติดตั้งแล้ว, เปิด `Program.cs`. คุณจะเห็นเมธอด `Main` เริ่มต้น—ให้แทนที่เนื้อหาด้วยโครงสร้างที่เราจะสร้างต่อไป + +## Step 2: Configure the OCR Engine for Russian Language + +หัวใจของการทำงานคืออ็อบเจ็กต์ `OcrEngine`. เราต้องบอกสองอย่าง: ภาษาที่ต้องการรู้จำและตำแหน่งของไฟล์โมเดลภาษา + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Why this matters:** หากคุณละเว้นการตั้งค่า `Language = OcrLanguage.Russian`, เอนจินจะใช้ค่าเริ่มต้นเป็นภาษาอังกฤษ, และอักขระ Cyrillic จะปรากฏเป็นสัญลักษณ์ที่อ่านไม่ออก. `ResourceFolder` ชี้ไปยังไดเรกทอรีที่เก็บไฟล์ `rus.traineddata`; หากไม่มีไฟล์นี้ Aspose จะขว้างข้อยกเว้น *resource not found* + +## Step 3: Load the Image for OCR + +ต่อไปเราต้อง **load image for OCR**. Aspose OCR ทำงานกับ `System.Drawing.Image`, ดังนั้นคุณสามารถส่งไฟล์รูปแบบที่รองรับได้ (PNG, JPEG, BMP, ฯลฯ). ตรวจสอบให้แน่ใจว่าเส้นทางไฟล์ถูกต้อง; เส้นทางแบบ relative ก็ใช้ได้หากคุณเก็บภาพไว้ใกล้ไฟล์ executable + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Edge case:** หากภาพมีขนาดใหญ่ (เกิน 5 MB) คุณอาจต้องลดขนาดลงก่อน. ความแม่นยำของ OCR ลดลงเมื่อ DPI ต่ำเกินไป, แต่ไฟล์ขนาดใหญ่ก็อาจทำให้ใช้หน่วยความจำมาก. สามารถปรับขนาดอย่างรวดเร็วด้วย `Graphics` หากจำเป็น + +## Step 4: Recognize the Text – From Image to Text C# Style + +เมื่อเอนจินตั้งค่าและโหลดภาพแล้ว, การรู้จำจริงเป็นเพียงการเรียกครั้งเดียว: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +เมื่อคุณรันโปรแกรม (`dotnet run`), คุณควรเห็นผลลัพธ์ประมาณนี้: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +หากผลลัพธ์ดูเหมือนเป็นอักขระผสม, ตรวจสอบอีกครั้งว่า: + +- ไฟล์ `rus.traineddata` อยู่ใน `ResourceFolder` +- ภาพไม่เบลอเกินไป; พิจารณาใช้ฟิลเตอร์ binarization อย่างง่ายก่อน OCR +- การตั้งค่าภาษาเป็น `OcrLanguage.Russian` จริงหรือไม่ + +## Step 5: Fine‑Tuning and Common Pitfalls + +### Adjusting Confidence Threshold + +Aspose OCR คืนค่า confidence สำหรับแต่ละอักขระภายใน. แม้ API จะไม่เปิดเผยโดยตรง, คุณสามารถเปิด **detailed output** เพื่อดูคำที่มี confidence ต่ำ: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +หากพบการรับรู้ที่ผิดพลาดบ่อย, ลอง: + +- **Pre‑processing**: แปลงภาพเป็น grayscale, เพิ่มความคอนทราสต์, หรือใช้ median filter +- **DPI settings**: ตรวจสอบให้ภาพมี DPI อย่างน้อย 300 DPI สำหรับสคริปต์ Cyrillic + +### Batch Processing Multiple Images + +หากต้องการ **extract text from image** files เป็นจำนวนมาก, ให้วนลูปตรรกะการรู้จำ: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +ตอนนี้แต่ละ PNG จะได้ไฟล์ `.txt` ของมันเอง—สะดวกสำหรับการจัดเก็บเอกสาร + +### Handling Unicode Output + +อักขระ Cyrillic เป็น Unicode, ดังนั้นให้แน่ใจว่า encoding ของคอนโซลของคุณสามารถแสดงได้: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +วางบรรทัดนี้หลังจากเริ่มเมธอด `Main`. หากไม่มีคุณอาจเห็นเครื่องหมายคำถาม (`?`) แทนตัวอักษรรัสเซีย + +## Full Working Example + +ด้านล่างเป็นโค้ดเต็มที่พร้อมรัน. คัดลอก‑วางลงใน `Program.cs`, ปรับเส้นทางตามต้องการ, แล้วคุณก็พร้อมใช้งาน + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Expected output** (สมมติว่าภาพตัวอย่างมีข้อความ “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +หากคุณเห็นอย่างอื่น, ให้กลับไปตรวจสอบเคล็ดลับการแก้ปัญหาใน Step 5 อีกครั้ง + +## Conclusion + +คุณมีตัวอย่างครบวงจรจากต้นจนจบเกี่ยวกับการ **ocr russian text** ใน C# ด้วย Aspose OCR. ตั้งแต่การติดตั้งไลบรารี, กำหนดโมเดลภาษารัสเซีย, โหลดภาพและแปลงเป็นข้อความ Unicode ที่สะอาด, ทุกขั้นตอนถูกครอบคลุมแล้ว + +จำไว้ว่า กุญแจสำคัญของ OCR ที่เชื่อถือได้คือแหล่งข้อมูลต้นทางที่ดี: ฟอนต์ชัด, DPI เพียงพอ, และทรัพยากรภาษาอย่างถูกต้อง. เมื่อคุณเชี่ยวชาญพื้นฐานแล้ว, คุณสามารถขยายไปสู่การประมวลผลเป็นชุด, ผสานกับที่เก็บข้อมูลบนคลาวด์, หรือแม้แต่รวมกับ AI เพื่อทำ post‑processing ตรวจสอบการสะกด + +### What’s Next? + +- สำรวจตัวเลือก **aspose ocr c#** ขั้นสูง เช่น การวิเคราะห์เลย์เอาต์หรือการส่งออกเป็น PDF +- ผสานกับ workflow **extract text from image** ใน Azure Functions เพื่อการประมวลผลแบบ serverless +- ลองภาษาอื่น—แค่เปลี่ยน `OcrLanguage.Russian` เป็น `OcrLanguage.English` หรือโค้ดภาษาที่รองรับอื่น + +มีคำถามหรือภาพที่ยากต่อการทำ OCR? แสดงความคิดเห็นด้านล่าง, แล้วขอให้สนุกกับการเขียนโค้ด! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + +## Related Tutorials + +- [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 Using Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/thai/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..4c12c4ec9 --- /dev/null +++ b/ocr/thai/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-25 +description: แยกข้อความจากภาพโดยใช้ Aspose OCR ใน C#. เรียนรู้วิธีโหลดภาพสำหรับ OCR, + ตั้งค่าภาษา OCR, สร้างเอนจิน OCR และดึงข้อความจากไฟล์ TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: th +og_description: จดจำข้อความจากภาพโดยใช้ Aspose OCR ใน C# บทเรียนนี้แสดงวิธีสร้างเครื่องมือ + OCR, โหลดภาพสำหรับ OCR, ตั้งค่าภาษา OCR, และดึงข้อความจากไฟล์ TIFF. +og_title: แปลงข้อความจากภาพด้วย Aspose OCR – คู่มือ C# ฉบับสมบูรณ์ +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: แยกข้อความจากภาพด้วย Aspose OCR – คู่มือ C# ฉบับสมบูรณ์ +url: /th/net/text-recognition/recognize-text-from-image-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 – คู่มือ C# ฉบับสมบูรณ์ + +เคยต้อง **จดจำข้อความจากภาพ** แต่ไม่แน่ใจว่าควรใช้ไลบรารีใดที่ให้ความเร็วและความแม่นยำพร้อมกันหรือไม่? คุณไม่ได้อยู่คนเดียว ในหลายโครงการประมวลผลใบแจ้งหนี้หรือการจัดเก็บเอกสาร จุดเจ็บปวดที่ใหญ่ที่สุดคือการดึงข้อความที่สะอาดและค้นหาได้จากไฟล์ TIFF โดยไม่ต้องเขียนพาร์เซอร์เอง + +สิ่งที่ควรทราบคือ Aspose OCR สำหรับ .NET ทำให้กระบวนการทั้งหมดเป็นเรื่องง่าย ในคู่มือนี้เราจะพาคุณผ่านทุกขั้นตอนที่จำเป็น—การติดตั้งแพคเกจ, **การสร้าง OCR engine**, การโหลด TIFF, การตั้งค่าภาษา OCR, และสุดท้าย **การดึงข้อความจาก TIFF**. เมื่อเสร็จคุณจะมีแอปคอนโซลที่พร้อมรันและสามารถ **จดจำข้อความจากภาพ** ได้อย่างรวดเร็ว + +## Prerequisites + +- .NET 6.0 หรือใหม่กว่า (โค้ดนี้ทำงานได้กับ .NET Core และ .NET Framework ด้วย) +- Visual Studio 2022 (หรือ IDE ใดก็ได้ที่คุณชอบ) +- Aspose.OCR NuGet package (การสนับสนุน GPU ต้องใช้ add‑on `Aspose.OCR.Gpu`) +- GPU ที่รองรับ CUDA หากต้องการความเร็วเพิ่มขึ้น (ไม่บังคับแต่แนะนำ) + +> **Pro tip:** หากคุณไม่มี GPU เพียงแค่ลบบรรทัด `GpuDevice` แล้ว engine จะสลับไปใช้ CPU โดยอัตโนมัติ + +## Step 1: Install Aspose OCR and Create OCR Engine + +แรกเริ่มให้เพิ่มแพคเกจที่จำเป็นผ่าน NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +ตอนนี้เราสามารถ **สร้าง OCR engine** ได้แล้ว วัตถุนี้เป็นหัวใจของกระบวนการ; มันเก็บการตั้งค่าต่าง ๆ เช่น อุปกรณ์ที่ใช้ทำงานและขีดจำกัดหน่วยความจำ + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**ทำไมจึงสำคัญ:** การผูก engine กับ GPU จะทำให้เวลาที่ใช้ในการ **จดจำข้อความจากภาพ** ลดลงอย่างมาก โดยเฉพาะกับชุดข้อมูลขนาดใหญ่ของ TIFF ความละเอียดสูง + +## Step 2: Load Image for OCR + +ต่อไปเราต้อง **โหลดภาพสำหรับ OCR** Aspose.OCR ทำงานกับ `System.Drawing.Image` ดังนั้นฟอร์แมตใด ๆ ที่ GDI+ รองรับ (รวมถึง multi‑page TIFF) ก็ใช้ได้ + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +หากคุณทำงานกับ TIFF หลายหน้า สามารถวนลูปผ่านหน้าโดยใช้ `image.SelectActiveFrame` แต่ในกรณีส่วนใหญ่การเรียกครั้งเดียวก็เพียงพอ + +## Step 3: Set OCR Language + +Engine ไม่ได้รู้โดยอัตโนมัติว่าคุณกำลังสแกนภาษาอะไร **ตั้งค่าภาษา OCR** ก่อนเรียก recognizer; มิฉะนั้นคุณจะได้ผลลัพธ์ที่เป็นอักขระผสมกัน + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Did you know?** การสลับภาษาขณะทำงานทำได้อย่างรวดเร็ว—you can even process a mixed‑language document by changing this property between pages. + +## Step 4: Perform the Recognition – Recognize Text from Image + +ตอนนี้มาส่วนที่สนุก: **จดจำข้อความจากภาพ** จริง ๆ `Recognize` จะคืนค่าเป็นสตริงธรรมดาที่มีอักขระที่ตรวจพบทั้งหมด + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +หากต้องการคะแนนความเชื่อมั่นหรือ bounding box สามารถใช้ overload ที่คืนค่าเป็นอ็อบเจ็กต์ `OcrResult` ได้ แต่สำหรับงานดึงข้อความส่วนใหญ่สตริงธรรมดาก็เพียงพอ + +## Step 5: Extract Text from TIFF (and handle multi‑page files) + +เมื่อแหล่งข้อมูลเป็น TIFF ที่มีหลายหน้า คุณจะต้องทำซ้ำขั้นตอน 2‑4 สำหรับแต่ละเฟรม ตัวอย่างลูปสั้น ๆ ที่ **ดึงข้อความจาก TIFF** หน้าโดยหน้า: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +โค้ดด้านบนจะแสดงข้อความที่ดึงได้จากทุกหน้า ทำให้ง่ายต่อการส่งต่อผลลัพธ์ไปยังฐานข้อมูลหรือดัชนีการค้นหา + +## Step 6: Display or Persist the Extracted Text + +สุดท้ายให้ **แสดงข้อความที่ดึงได้** และอาจบันทึกลงไฟล์เพื่อใช้ต่อในภายหลัง + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +เมื่อรันโปรแกรมจะพิมพ์อักขระที่จดจำได้และสร้างไฟล์ `extracted_text.txt` อยู่ข้างไฟล์ TIFF ของคุณ + +--- + +## Common Questions & Edge Cases + +- **GPU ไม่ถูกตรวจพบจะทำอย่างไร?** + ลบบรรทัด `GpuDevice`; engine จะสลับไปใช้โหมด CPU โดยอัตโนมัติ ประสิทธิภาพอาจช้าลงแต่ผลลัพธ์ยังคงแม่นยำ + +- **สามารถประมวลผลไฟล์ PNG หรือ JPEG ได้หรือไม่?** + แน่นอน—`Image.FromFile` รองรับฟอร์แมตใดก็ได้ที่ System.Drawing รองรับ ดังนั้นคุณสามารถ **โหลดภาพสำหรับ OCR** ไม่ว่าขยายไฟล์จะเป็นอะไร + +- **จะจัดการกับสแกนความละเอียดต่ำอย่างไร?** + เพิ่มค่า `ocrEngine.PreprocessOptions.Dpi` ก่อนเรียก `Recognize` DPI ที่สูงขึ้นจะให้พิกเซลมากขึ้นกับ engine ช่วยเพิ่มความแม่นยำ + +- **มีขีดจำกัดขนาดของ TIFF หรือไม่?** + คุณสมบัติ `GpuMemoryLimit` จำกัดการใช้ GPU หากเกินขีดจำกัด engine จะสลับไปใช้ CPU สำหรับหน้าที่เหลือ + +--- + +## Conclusion + +คุณมีสคริปต์ที่สมบูรณ์และพร้อมใช้งานในระดับ production ที่ **จดจำข้อความจากภาพ** ด้วย Aspose OCR ใน C# แล้ว คู่มือได้อธิบายวิธี **สร้าง OCR engine**, **โหลดภาพสำหรับ OCR**, **ตั้งค่าภาษา OCR**, และ **ดึงข้อความจาก TIFF**—ทั้งหมดโดยใช้การเร่งความเร็วด้วย GPU + +ต่อจากนี้คุณอาจ: + +- ทดลองใช้ภาษาต่าง ๆ (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` เป็นต้น) +- ผสานผลลัพธ์เข้ากับดัชนี ElasticSearch ที่ค้นหาได้ +- เพิ่มกระบวนการหลังการประมวลผล (ตรวจสอบการสะกด, ทำความสะอาดด้วย regex) เพื่อปรับคุณภาพข้อมูล + +ลองใช้กับชุดใบแจ้งหนี้ของคุณเอง ปรับขีดจำกัดหน่วยความจำ แล้วดูประสิทธิภาพ OCR พุ่งสูงขึ้น ขอให้สนุกกับการเขียนโค้ด! + +## Related Tutorials + +- [ดึงข้อความจากภาพด้วย C# พร้อมเลือกภาษาโดยใช้ Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [วิธีดึงข้อความจากภาพโดยการเตรียมสี่เหลี่ยมใน OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [ดึงข้อความจากภาพ – จดจำบรรทัดด้วย Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..f909f2277 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 OCR Motoru Oluşturma – Tam Kılavuz](./create-ocr-engine-in-c-complete-guide/) +Aspose.OCR ile C# uygulamanızda tam OCR motoru oluşturmayı adım adım öğrenin. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/turkish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..e85abfdb1 --- /dev/null +++ b/ocr/turkish/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,267 @@ +--- +category: general +date: 2026-05-25 +description: C#'ta OCR motoru oluşturun ve birkaç satır kodla değerlendirme modunu + ve lisans durumunu nasıl kontrol edeceğinizi öğrenin. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: tr +og_description: C#'ta OCR motoru oluşturun ve değerlendirme modunu nasıl tespit edeceğinizi + ve lisans durumunu nasıl görüntüleyeceğinizi anında görün. +og_title: C#'ta OCR Motoru Oluşturma – Adım Adım Rehber +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: C#'ta OCR Motoru Oluşturma – Tam Rehber +url: /tr/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta OCR Motoru Oluşturma – Tam Kılavuz + +C#'ta **OCR motoru** nesnelerini sonsuz belgeler arasında dolaşmadan nasıl oluşturacağınızı hiç merak ettiniz mi? Tek başınıza değilsiniz. Birçok geliştirici, bir OCR motoru başlatmaları, deneme modunda çalışıp çalışmadığını doğrulamaları ve lisans durumunu kullanıcılara göstermeleri gerektiğinde bir duvara çarpar. + +Bu öğreticide, **OCR motoru** oluşturan, **OCR motoru değerlendirme modunu** kontrol eden ve lisans durumuyla ilgili dostane bir mesaj yazdıran özlü, uçtan uca bir örnek üzerinden ilerleyeceğiz. Sonunda, çalıştırmaya hazır bir konsol uygulamanız ve kendi projelerinizde OCR lisanslamasını yönetmek için net bir zihinsel modeliniz olacak. + +## Öğrenecekleriniz + +- `OcrEngine` (her OCR iş akışının çekirdeği) nasıl örneklenir. +- **Değerlendirme modunun** tespiti neden uyumluluk ve kullanıcı deneyimi açısından önemlidir. +- **OCR lisansını** kontrol etmenin en iyi yolu ve beklenmeyen durumlara nasıl yanıt verilir. +- Yaygın tuzaklar—null referanslar, istisna yönetimi ve sürüm uyumsuzlukları. + +Kurulu OCR SDK'nız dışındaki hiçbir dış araç gerekmiyor. Temel C# sözdizimini biliyorsanız, hazırsınız. + +## Önkoşullar + +- .NET 6.0 veya üzeri (kod .NET Core ve .NET Framework ile derlenir). +- `IsEvaluation` özelliğine sahip bir `OcrEngine` sınıfı sunan bir OCR SDK'sı (örneğin, hayali `MyOcrSdk`). +- Bir metin editörü veya IDE (Visual Studio, VS Code, Rider—hangisini tercih ederseniz). + +Hepsi bu. Hadi başlayalım. + +## Adım 1: Yeni Bir Konsol Projesi Oluşturun + +İlk olarak, kodu izole bir ortamda çalıştırabilmek için temiz bir konsol uygulaması başlatın. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Oluşturulan `Program.cs` dosyasını açın. İçeriğini **OCR motoru** örnekleri oluşturup lisanslamayı yöneten tam bir örnekle değiştireceğiz. + +## Adım 2: OCR SDK Ad Alanını İçe Aktarın + +SDK'ın NuGet üzerinden referanslandığını varsayarsak (`MyOcrSdk` bir yer tutucudur), dosyanın en üstüne using yönergesini ekleyin. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Paketi henüz eklemediyseniz, şu komutu çalıştırın: + +```bash +dotnet add package MyOcrSdk +``` + +> **Pro ipucu:** SDK sürümünüzü güncel tutun; yeni sürümler genellikle değerlendirme‑modu algılamasını iyileştirir. + +## Adım 3: OCR Motoru Örneğini Oluşturun + +Şimdi nihayet **OCR motoru** nesnelerini **oluşturuyoruz**. Bu, herhangi bir OCR iş akışının kalbidir—daha sonra görüntüleri okuyacak beyin gibi düşünebilirsiniz. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Bu adım neden kritik? `OcrEngine`, tüm yapılandırma, dil paketleri ve lisans verilerini kapsar. Motor olmadan görüntü işleyemez veya değerlendirme bayrağını sorgulayamazsınız. + +> **Not:** Bazı SDK'lar, yapıcıya bir yapılandırma nesnesi (ör. dil, DPI) geçirmenize izin verir. Özel ayarlar gerekiyorsa, ilgili satırı buna göre değiştirin. + +## Adım 4: OCR Motoru Değerlendirme Modunu Belirleyin + +Çoğu OCR sağlayıcısı, geçerli bir lisans anahtarı girilene kadar **değerlendirme modunda** çalışan bir deneme sürümü sunar. Deneme modunda olup olmadığınızı bilmek, uygun UI ipuçları göstermenize veya belirli özellikleri kısıtlamanıza olanak tanır. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +`IsEvaluation` özelliği, motor lisanssız veya zaman sınırlı bir deneme kullanıyorsa `true` döner. Premium özellikleri korumanın hızlı ve güvenilir bir yoludur. + +### Özellik Eksikse Ne Yapmalı? + +Eski SDK sürümleri, bunun yerine `GetLicenseInfo()` gibi bir metod sunabilir. Bu durumda, dönen nesnede bir `IsTrial` bayrağı ararsınız. Sürüm yükseltirken SDK değişiklik günlüğüne mutlaka bakın. + +## Adım 5: Mevcut Lisans Durumunu Görüntüleyin + +Son olarak, motorun lisanslı mı yoksa hâlâ deneme modunda mı olduğunu kullanıcıya gösterelim. Basit bir `Console.WriteLine` yeterli olur; GUI uygulamalarına da kolayca uyarlayabilirsiniz. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Üçlü (ternary) operatör kodu temiz tutar ve mesajlar, son kullanıcılar ya da logları okuyan geliştiriciler için yeterince açıktır. + +## Tam Çalışan Örnek + +Hepsini bir araya getirdiğimizde, `Program.cs` içine kopyalayıp `dotnet run` ile çalıştırabileceğiniz bağımsız bir program elde edersiniz. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Beklenen Çıktı + +- **Deneme sürümü:** + `Running in evaluation mode – limited functionality.` + +- **Lisanslı sürüm:** + `Licensed – full OCR capabilities enabled.` + +SDK bir istisna fırlatırsa (ör. eksik native DLL), catch bloğu uygulamanın çökmesi yerine yardımcı bir hata mesajı yazdırır. + +## Kenar Durumları ve Yaygın Tuzaklar + +### 1. Null Motor Örnekleri + +Yapıcı genellikle geçerli bir nesne döndürse de, bazı SDK'lar gerekli native bağımlılıklar eksik olduğunda `null` dönebilir. Buna karşı koruma ekleyin: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Çalışma Sırasında Lisans Süresinin Dolması + +Deneme lisansı oturum sırasında süresi dolabilir. Uygulamanız uzun süre çalışıyorsa periyodik olarak `IsEvaluation` yeniden sorgulayın. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Sürümler Arası Farklı Özellik İsimleri + +Eski sürümler `engine.EvaluationMode` ya da `engine.License.IsTrial` gibi isimler kullanabilir. Güncelleme yaptığınızda kırılma değişiklikleri için SDK sürüm notlarını arayın. + +### 4. Çoklu İş Parçacığı Senaryoları + +Birden fazla OCR çalışanı başlatıyorsanız, SDK açıkça çok iş parçacıklı kullanım desteklemiyorsa **her iş parçacığı için bir OCR motoru** oluşturun. Tek bir motoru paylaşmak yarış koşullarına ve yanlış lisans okumalara yol açabilir. + +## Üretim İçin Pro İpuçları + +- **Lisans durumunu** ilk kontrolden sonra önbelleğe alarak gereksiz özellik çağrılarından kaçının. +- **Lisans anahtarını** (maskelemiş şekilde) başlangıçta loglayın; denetim izleri destek ekiplerinin lisans sorunlarını teşhis etmesine yardımcı olur. +- **Kullanıcı arayüzünde** deneme modunda olduklarını belirten bir geçiş ekleyin ve “Lisans Satın Al” butonu sunun. +- SDK’nın aktivasyon API'si varsa, **lisans yenilemeyi otomatikleştirerek** kullanıcı deneyimini kesintisiz tutun. + +## Sonuç + +Birkaç satırda **OCR motoru** nesnelerini **oluşturduk**, **OCR motoru değerlendirme modunu** inceledik ve net bir **OCR lisans durumu** mesajı yazdırdık. Tam örnek kutudan çıkar çıkmaz çalışır, hataları zarifçe ele alır ve her adımın “nedenini” vurgular—böylece masaüstü, web ya da servis‑tarafı senaryolarına kolayca uyarlayabilirsiniz. + +Sonraki adımlarda şunları keşfedebilirsiniz: + +- Görüntüleri `engine.Recognize` ile beslemek ve çok‑dilli desteği yönetmek. +- **check OCR license** API'lerini kullanarak satın alınan bir anahtarı programatik olarak etkinleştirmek. +- UI framework'leri (WinForms, WPF, MAUI) ile lisans rozetleri göstermek. + +Bunları deneyin; her türlü uygulama için sağlam bir OCR temeli oluşturmuş olacaksınız. Kodlamanın tadını çıkarın! + + +## İlgili Öğreticiler + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/ocr-optimization/_index.md b/ocr/turkish/net/ocr-optimization/_index.md index 12ce2f053..9e013c811 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. +### [OCR için Görüntü Ön İşleme – Tam Aspose C# Kılavuzu](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Aspose OCR ile C# kullanarak görüntüleri ön işleyip OCR doğruluğunu artırın. ## Sıkça Sorulan Sorular diff --git a/ocr/turkish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/turkish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..b6e96f75e --- /dev/null +++ b/ocr/turkish/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,224 @@ +--- +category: general +date: 2026-05-25 +description: OCR doğruluğunu artırmak için Aspose ile görüntüyü ön işleme tabi tutun + ve JPEG dosyalarında OCR çalıştırın. Aspose kullanarak metin çıkarmayı net, adım + adım bir öğreticide öğrenin. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: tr +og_description: OCR doğruluğunu artırmak için Aspose ile görüntüyü ön işleme tabi + tutun. JPEG üzerinde OCR çalıştırmak ve Aspose kullanarak C# ile metin çıkarmak + için bu kılavuzu izleyin. +og_title: OCR için Görüntüyü Ön İşleme – Aspose C# Öğreticisi +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: OCR için Görüntüyü Ön İşleme – Tam Aspose C# Kılavuzu +url: /tr/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR için Görüntü Ön İşleme – Tam Aspose C# Kılavuzu + +Her zaman metnin temiz çıkması için **preprocess image for OCR**'ı merak ettiniz mi? Tek başınıza değilsiniz—geliştiriciler sürekli gürültülü taramalar, düşük kontrastlı JPEG'ler ve öngörülemeyen aydınlatma ile mücadele ediyor. İyi haber? Birkaç akıllı ayarlama ile **improve OCR accuracy**'ı büyük ölçüde artırabilirsiniz ve Aspose bunu zahmetsiz hale getiriyor. + +Bu öğreticide, **run OCR on JPEG** görüntüler üzerinde nasıl çalıştırılacağını, özel bir görüntü işleme hattı uygulamayı ve nihayet **extract text using Aspose**'ı gösterecek gerçek bir örnek üzerinden ilerleyeceğiz. Sonunda, herhangi bir .NET projesine ekleyebileceğiniz hazır bir C# kod parçacığına sahip olacaksınız. + +Aspose ile önceden bir deneyime sahip olmanız gerekmez; sadece temel bir C# altyapısı ve Visual Studio (veya favori IDE'niz) yeterlidir. Hadi başlayalım. + +![OCR için Görüntü Ön İşleme örneği](preprocess-ocr.png "OCR için Görüntü Ön İşleme") + +## Adım 1: Aspose.OCR Motorunu Kurun – OCR için Görüntü Ön İşleme + +İlk olarak, bir `OcrEngine` örneğine ihtiyacımız var ve ona hangi dili beklediğimizi söylemeliyiz. Çoğu durumda İngilizce varsayılan olarak gelir, ancak `OcrLanguage` enum'ını değiştirerek Fransızca, Almanca vb. dillerle değiştirebilirsiniz. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Neden önemli?** Motor, işlemin kalbidir; olmadan **preprocess image for OCR** yapan görüntü filtrelerini uygulayamazsınız. Bunu, tüm malzemelerin karıştırıldığı bir mutfak gibi düşünün. + +## Adım 2: Özel Bir Görüntü İşleme Hattı Oluşturun – OCR Doğruluğunu Artırın + +Şimdi en lezzetli kısma geliyoruz. Aspose, birden fazla filtreyi bir araya getirmenize izin verir. Aşağıda en etkili dört tanesini etkinleştiriyoruz: + +1. **Deskew** – eğik belgeleri düzleştirir (varsayılan olarak maksimum 5°). +2. **Denoise** – grenli arka planları yumuşatır. +3. **Binarize** – görüntüyü bir eşik kullanarak siyah‑beyaz'a dönüştürür. +4. **ContrastBoost** – soluk karakterleri belirginleştirir. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Pro ipucu:** Kaynak görüntüleriniz zaten netse, `Strength` değerini azaltabilir veya bir filtreyi tamamen kapatabilirsiniz. Aşırı işleme bazen soluk karakterleri silebilir, bu yüzden gerçek örneklerle deney yapın. + +## Adım 3: JPEG'i (veya Herhangi Bir Görüntüyü) Yükleyin ve OCR Çalıştırın – JPEG Üzerinde OCR Çalıştırma + +Aspose, .NET'in okuyabildiği herhangi bir görüntü formatıyle çalışır—JPEG, PNG, BMP, istediğiniz gibi. İşte bir JPEG dosyasını motorun içine nasıl besleyeceğiniz ve tanıma sürecini nasıl başlatacağınız. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Neden JPEG?** JPEG sıkıştırması genellikle OCR'ı şaşırtan artefaktlar oluşturur. Ön işleme hattımız, özellikle denoise ve binarize adımları, bu sorunları azaltır ve **run OCR on JPEG**'i güvenle yapmanızı sağlar. + +## Adım 4: Tanınan Metni Çıktı Alın – Aspose Kullanarak Metin Çıkarma + +Son olarak, metni sadece konsola, bir dosyaya veya herhangi bir sonraki servise yazarız. Demonstrasyon amacıyla, konsol yeterlidir. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Programı çalıştırdığınızda aşağıdakine benzer bir çıktı görmelisiniz: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Çıktı bozuk görünüyorsa, **Adım 2**'ye geri dönüp filtre ayarlarını değiştirin. Küçük ayarlamalar genellikle **improve OCR accuracy**'de büyük kazançlar sağlar. + +## Yaygın Kenar Durumları ve Nasıl Ele Alınır + +| Durum | Önerilen Ayar | +|-----------|----------------------| +| **Çok karanlık görüntüler** | Increase `ContrastBoost.Level` to 1.5 or higher. | +| **Eğim > 5°** | Raise `DeskewOptions.MaxAngle` (e.g., 10.0) or pre‑rotate the image manually. | +| **Renkli metin renkli arka planda** | Use `BinarizeOptions` with a custom threshold or switch to `AdaptiveBinarizeOptions`. | +| **Büyük dosyalar ( > 5 MB )** | Load the image into a `MemoryStream` first to avoid file‑lock issues. | + +Bu ayarlamalar, özellikle çeşitli kaynaklardan **extract text using Aspose** yapmanız gerektiğinde, hattınızı esnek ve geleceğe dayanıklı tutar. + +## Tam Çalışan Örnek – Tüm Adımlar Tek Bir Yerde + +Aşağıda, tamamen kopyala‑yapıştır‑hazır program bulunmaktadır. .NET 6+ ile derlenir ve sadece `Aspose.OCR` NuGet paketini gerektirir. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +`Program.cs` olarak kaydedin, Aspose.OCR paketini ekleyin (`dotnet add package Aspose.OCR`), ve `dotnet run` komutunu çalıştırın. Konsola temizlenmiş metnin yazdırıldığını göreceksiniz. + +## Özet – Neden Bu Yaklaşım Çalışır + +- **Preprocess image for OCR**: Hattı, hatanın en yaygın kaynaklarını (eğim, gürültü, düşük kontrast) ortadan kaldırır. +- **Improve OCR accuracy**: Her filtre, motorun gördüğü sinyal‑gürültü oranını artıracak şekilde ayarlanmıştır. +- **Run OCR on JPEG**: Sıkıştırılmış görüntüler bile deskew ve binarize sonrası okunabilir hâle gelir. +- **Extract text using Aspose**: `Recognize` metodu, herhangi bir sonraki mantık için hazır düz bir string döndürür. + +Birlikte, bu adımlar size sadece birkaç satırda güvenilir, üretim‑düzeyinde bir OCR çözümü sunar. + +## Sonraki Adımlar ve İlgili Konular + +- **Batch processing** – Bir klasördeki görüntüler üzerinde döngü yapın ve her sonucu bir `.txt` dosyasına yazın. +- **Language packs** – `OcrLanguage.English` yerine `OcrLanguage.Spanish` kullanın veya özel sözlükler ekleyin. +- **PDF extraction** – Tarama yapılan PDF'lerden doğrudan metin çekmek için Aspose.OCR'ı Aspose.PDF ile birleştirin. +- **Performance tuning** – Büyük iş yükleri için motoru `Parallel.ForEach` kullanarak paralel çalıştırın. + +Filtre değerleriyle denemeler yapmaktan, farklı görüntü formatlarını denemekten veya `SharpnessOptions` gibi ek Aspose filtreleri eklemekten çekinmeyin. Temelleri kavradıktan sonra sınır yok. + +--- + +*Kodlamanız keyifli olsun! Herhangi bir sorunla karşılaşırsanız, aşağıya yorum bırakın, birlikte çözüm bulalım.* + +## İlgili Öğreticiler + +- [Aspose.OCR Filtreleriyle .NET için Görüntü OCR Ön İşleme](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [.NET için Aspose.OCR ile Görüntüden Metin Çıkarma – OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) +- [Aspose.OCR kullanarak dil seçimiyle C# 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/text-recognition/_index.md b/ocr/turkish/net/text-recognition/_index.md index 5ddf0e83d..4757295ea 100644 --- a/ocr/turkish/net/text-recognition/_index.md +++ b/ocr/turkish/net/text-recognition/_index.md @@ -55,9 +55,23 @@ Etkili görüntü metni tanıma için .NET uygulamalarınızı Aspose.OCR ile ge 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. ### [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üden Metin Tanıma – Tam C# Kılavuzu](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Aspose OCR kullanarak C# ile görüntülerden metin çıkarmayı adım adım öğrenin ve projelerinize entegre edin. +### [C# OCR Eğitimi: Aspose ile PNG Makbuzlarından Metin Çıkarma](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Aspose kullanarak C# ile PNG formatındaki makbuzlardan metni nasıl çıkaracağınızı adım adım öğrenin. +### [C#'ta OCR Nasıl Kullanılır – JPG'den Çince Metin Tanıma](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +C# ve Aspose.OCR kullanarak JPG dosyalarındaki Çince metni nasıl tanıyacağınızı adım adım öğrenin. +### [C#'ta Rus Metin OCR – Aspose OCR Kullanarak Tam Kılavuz](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +### [C#'ta Görüntüden Metin Çıkarma – Tam Aspose OCR Kılavuzu](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Aspose OCR kullanarak C# ile görüntülerden metin çıkarmayı adım adım öğrenin ve projelerinize entegre edin. +### [ASP.NET Core Minimal API ile Görüntüden Metin Çıkarma – Tam Kılavuz](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +ASP.NET Core Minimal API kullanarak görüntülerden metin çıkarmayı adım adım öğrenin ve projelerinize entegre edin. +### [C# ile TIFF'i Metne Dönüştürme – Tam Toplu OCR Kılavuzu](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +C# kullanarak TIFF dosyalarını toplu olarak metne dönüştürmeyi adım adım öğrenin ve OCR sürecinizi otomatikleştirin. + {{< /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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/turkish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..272bc9ed1 --- /dev/null +++ b/ocr/turkish/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,221 @@ +--- +category: general +date: 2026-05-25 +description: c# OCR öğreticisi, c# ile görüntü dosyasını nasıl yükleyeceğinizi ve + Aspose OCR kullanarak bir makbuzdaki png metnini nasıl tanıyacağınızı adım adım + gösterir – adım adım rehber. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: tr +og_description: c# OCR öğreticisi, bir resim dosyasını c# ile yüklemenizi ve Aspose + OCR kullanarak bir makbuzdaki png metnini tanımanızı adım adım gösterir. +og_title: c# OCR öğreticisi – PNG makbuzlarından metin çıkarma +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'c# OCR öğreticisi: Aspose ile PNG makbuzlarından metin çıkarma' +url: /tr/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# c# OCR öğretici – PNG Makbuzlarından Metin Çıkarma Aspose ile + +Ever needed a **c# OCR tutorial** that actually gets the job done without endless Googling? You're in the right place. In this guide we'll **load image file c#**, **recognize png text**, and **read receipt OCR** results, all while showing you how to **perform OCR image** processing with Aspose OCR. + +We'll start by installing the required NuGet package, walk through each line of code, and finish with a tidy JSON dump you can pipe straight into your next data‑pipeline. No fluff, just a practical, ready‑to‑run solution. + +## Öğrenecekleriniz + +- How to set up Aspose OCR in a .NET 6 (or later) project. +- The exact steps to **load an image file c#** and hand it to the engine. +- How to **recognize png text** from a receipt image and capture the result. +- Ways to **read receipt OCR** output as nicely formatted JSON. +- Tips for **perform OCR image** operations on different file types and handling common pitfalls. + +**Prerequisites** +- Visual Studio 2022 (or any IDE you like). +- .NET 6 SDK or newer. +- A PNG receipt image handy (we’ll call it `receipt.png`). + +If you’ve got those, let’s dive in. + +![c# OCR öğretici ekran görüntüsü](ocr-demo.png "c# OCR öğretici sonucu JSON çıktısını gösteriyor") + +## c# OCR Öğretici – Aspose OCR Motorunu Kurma + +First off, we need the Aspose OCR library. Open your terminal in the solution folder and run: + +```bash +dotnet add package Aspose.OCR +``` + +That single command pulls in everything required, including native binaries for image decoding. Once installed, create a new console project or add the code to an existing one. + +### Neden Aspose? + +Aspose OCR supports over 30 languages, works offline, and returns a rich `OcrResult` object—perfect for **perform OCR image** tasks where you need more than just plain text. + +## Load image file c# ve Makbuzu Hazırlama + +Now that the library is ready, let’s **load image file c#**. The `System.Drawing.Image` class does the heavy lifting, but you could also use `SkiaSharp` if you prefer a cross‑platform alternative. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Pro ipucu:** `Image` nesnesini (gösterildiği gibi) bir `using` ifadesi içinde sararak yerel kaynakları hemen serbest bırakın—özellikle bir döngüde çok sayıda dosyada **perform OCR image** yaparken bu çok önemlidir. + +## Aspose ile PNG Metnini Tanıma + +With the image in memory, the engine can now **recognize png text**. Aspose returns an `OcrResult` that contains both the raw string and detailed data about each recognized word. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Why call `RecognizeWithResult` instead of the simpler `Recognize`? The former gives you access to confidence scores, bounding boxes, and line breaks—handy if you later need to **read receipt OCR** for line‑item extraction. + +## receipt OCR Sonucunu JSON Olarak Okuma + +Most downstream systems love JSON, so let’s serialize the `OcrResult`. The `System.Text.Json` serializer handles complex objects gracefully, and we’ll enable indentation for readability. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +The resulting JSON looks something like this (trimmed for brevity): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +You can now pipe `jsonResult` into a database, a message queue, or simply log it for debugging. + +## OCR Görüntü İşleme Yapma ve Çıktıyı Görüntüleme + +Finally, output the JSON to the console. In a real‑world app you’d probably write it to a file or send it over HTTP, but the console makes it easy to verify everything worked. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Run the program (`dotnet run`) and you should see the nicely formatted JSON printed. If the receipt image is clear, the text will be spot‑on; if not, consider increasing the image resolution or applying a preprocessing filter (e.g., grayscale, contrast boost) before feeding it to the engine. + +### Yaygın Kenar Durumlarını Ele Alma + +| Durum | Ne yapılmalı | +|-----------|------------| +| **Görüntü bulanık** | `System.Drawing` ile ön‑işleme yaparak keskinleştirin veya DPI'yi artırın. | +| **Makbuz birden fazla dil içeriyor** | `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` şeklinde ayarlayın. | +| **Büyük toplu işleme** | Tek bir `OcrEngine` örneğini yeniden kullanın; her yinelemede sadece `Image`'i değiştirin. | +| **Bellek baskısı** | `Image` nesnelerini hemen serbest bırakın ve async boru hatları için `await Task.Run` kullanmayı düşünün. | + +These tweaks keep your **perform OCR image** workflow robust even when the input isn’t perfect. + +## Özet + +Congratulations—you’ve just completed a **c# OCR tutorial** that loads an image, **recognizes png text**, and **reads receipt OCR** output as clean JSON. The core steps (engine setup, image loading, OCR execution, serialization, and display) form a solid foundation you can extend to invoices, passports, or any other scanned document. + +### Sıradaki Adımlar + +- `SkiaSharp` kullanarak **load image file c#** denemeleri yapın ve gerçek çapraz platform desteği elde edin. +- `OcrResult.Words` içine daha derine girerek satır öğeleri, fiyatlar ve tarihleri çıkarın—gider takibi uygulamaları için mükemmel. +- Bu öğreticiyi Azure Functions veya AWS Lambda ile birleştirerek sunucusuz bir makbuz‑işleme API'si oluşturun. + +Feel free to tweak the code, throw in more images, or even switch to a different language pack. The world of OCR is full of surprises, and now you have the tools to explore them. + +Happy coding, and may your receipts always be readable! + +## İlgili Öğreticiler + +- [Aspose.OCR kullanarak dil seçimiyle C# Görüntü Metni Çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Görüntüden Metin Çıkarma – .NET için Aspose.OCR ile OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) +- [OCR Nasıl Kullanılır - Metin Alanı Algılamadan Görüntü Tanıma](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/turkish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..21a127149 --- /dev/null +++ b/ocr/turkish/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,202 @@ +--- +category: general +date: 2026-05-25 +description: Aspose.OCR kullanarak C#'de TIFF'i metne dönüştürün. Toplu görüntüden + metne dönüşümünü öğrenin ve TIFF dosyalarından metni verimli bir şekilde çıkarın. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: tr +og_description: Aspose.OCR ile TIFF'i metne dönüştürün. Bu kılavuz, toplu görüntüden + metne dönüşümü ve C#'ta birkaç satırla TIFF dosyalarından metin çıkarmayı gösterir. +og_title: TIFF'i C# ile Metne Dönüştür – Tam Batch OCR Kılavuzu +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: C#'ta TIFF'i Metne Dönüştür – Tam Batch OCR Rehberi +url: /tr/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta TIFF'i Metne Dönüştür – Tam Batch OCR Kılavuzu + +Hiç **TIFF'i metne dönüştürmek** gerektiğinde nereden başlayacağınızı bilemediniz mi? Yalnız değilsiniz—birçok geliştirici taranmış belgelerle çalışırken batch OCR'da takılıp kalıyor. Bu öğreticide, Aspose.OCR kullanarak **TIFF dosyalarından metin çıkaran** uygulamalı bir çözümü adım adım inceleyeceğiz ve bunu paralel olarak yapacağız, böylece büyük klasörler saniyeler içinde tamamlanacak. + +Ayrıca **batch image to text conversion** en iyi uygulamalarına da değineceğiz, böylece sonunda taranmış görüntülerin tamamını düzenli *.txt* dosyalarına dönüştüren yeniden kullanılabilir bir kod parçasına sahip olacaksınız—indeksleme, arama veya sonraki analizlere beslemek için mükemmel. + +## İhtiyacınız Olanlar + +- **.NET 6.0** veya daha yenisi (kod .NET Framework'ta da derlenir) +- **Aspose.OCR for .NET** NuGet paketi (`Install-Package Aspose.OCR`) +- *.tif* dosyalarından bir veya daha fazlasını içeren bir klasör (klasik TIFF tarama formatı) +- Favori IDE'niz (Visual Studio, VS Code, Rider—ne isterseniz) + +Hepsi bu. Harici hizmet yok, API anahtarı yok, sadece saf C# ve Aspose. + +![İşlenen bir TIFF dosyasının ve ortaya çıkan metin dosyasının ekran görüntüsü](/images/ocr-result.png "TIFF'in metne dönüştürüldüğünü gösteren OCR sonucu") + +*(Alt metin: Ekranda dönüştürülmüş TIFF'ten metin çıktısını gösteren ekran görüntüsü)* + +## Adım 1: OCR Motorunu Kur – TIFF'i Metne Dönüştür + +İlk olarak, İngilizce karakterleri okuyacağını bilen bir `OcrEngine` örneğine ihtiyacımız var. Motor, dönüşümün kalbidir; doğru yapılandırılması güvenilir sonuçlar sağlar. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Neden önemli:* +Aspose.OCR onlarca dili destekler. Çok dilli taramalarla çalışıyorsanız, sadece `OcrLanguage.English` değerini uygun enum değeriyle değiştirin. Dili tanımlamamak, motoru otomatik algılama moduna zorlar; bu daha yavaş ve daha az doğru olabilir. + +## Adım 2: Tüm TIFF Dosyalarını Topla – TIFF'ten Metni Verimli Şekilde Çıkar + +Sonra belirttiğiniz klasörden tüm *.tif* dosyalarını alıyoruz. `Directory.GetFiles` kullanmak, batch işlemcisine besleyebileceğimiz temiz bir dizi sağlar. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Pro ipucu:* Taramalarınız alt klasörlerde iç içe ise `SearchOption.AllDirectories` bayrağını kullanabilirsiniz. Ancak daha derin bir yineleme, batch adımında bellek kullanımını artırabilir. + +## Adım 3: Paralel OCR Gerçekleştir – Batch Image to Text Conversion + +Şimdi eğlenceli kısım. Aspose.OCR, dosya yolu dizisi, bir motor ve bir `parallelism` ipucu alan statik bir yardımcı `BatchOcr.RecognizeAll` ile birlikte gelir. Modern bir quad‑core dizüstü bilgisayarda dört iş parçacığı başlatarak neredeyse doğrusal bir hız artışı elde ederiz. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Neden paralellik?* +Yüksek çözünürlüklü TIFF batch'ini taramak CPU yoğun olabilir. Çalışmayı birden fazla iş parçacığına dağıtarak tüm çekirdekleri meşgul tutar, toplam çalışma süresini büyük ölçüde kısar. Daha fazla çekirdeğe sahip bir sunucuda çalıştırıyorsanız, `parallelism` değerini buna göre artırın. + +## Adım 4: Çıktıyı Yaz – Taranmış Görüntüleri TXT Dosyalarına Dönüştür + +Son olarak sözlüğü döngüye alıp her metin parçasını orijinal temel adıyla aynı olan bir *.txt* dosyasına yazıyoruz. İşte **convert scanned images txt** ifadesinin gerçeğe dönüştüğü an. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Kodun yaptığı şey, sade İngilizce + +1. **Create** İngilizce için ayarlanmış bir OCR motoru oluştur. +2. **Collect** hedef klasörden tüm TIFF dosyalarını topla. +3. **Run** dört iş parçacığıyla `BatchOcr.RecognizeAll` çalıştır, her görüntüyü bir dizeye dönüştür. +4. **Loop** sonuçlar üzerinde dolaş, `.tif` uzantısını `.txt` ile değiştir ve dizeyi diske yaz. + +Bu, **convert TIFF to text** iş akışının tamamı, 50 satırdan az kodla. + +## Kenar Durumlarını Ele Alma – İşler Sorunsuz Gitmediğinde + +- **Missing or corrupted TIFFs** – `BatchOcr` bir `OcrException` fırlatır. Daha nazik bir bozulma istiyorsanız çağrıyı `try / catch` içinde sarın. +- **Non‑English documents** – `OcrLanguage.English` değerini `OcrLanguage.Spanish`, `OcrLanguage.French` vb. ile değiştirin veya `OcrLanguage.AutoDetect` kullanın. +- **Very large images** – OCR'dan önce DPI'yi düşürmeyi düşünün (`ocrEngine.ImagePreprocessing.Dpi = 200`) bellek tasarrufu için, ancak doğruluk kaybedebilirsiniz. +- **Output encoding** – belirli bir kod sayfasına (ör. Windows‑1252) ihtiyacınız varsa, bunu `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))` fonksiyonuna geçirin. + +## Sağlam Batch Dönüşümler İçin Pro İpuçları + +- **Log failures**: bir `List failedFiles` oluşturun ve hata veren dosyaları ekleyin; döngüden sonra listeyi bir log dosyasına yazın. +- **Reuse the engine**: aynı `OcrEngine` örneği birçok dosya için yeniden kullanılabilir; döngü içinde yeniden örnek oluşturmayın. +- **Validate the result**: hızlı bir `if (string.IsNullOrWhiteSpace(extractedText))` taramaların boş veya okunamaz olduğunu işaretleyebilir. +- **Combine with PDF**: kaynağınız çok sayfalı bir PDF ise, önce her sayfayı TIFF'e dönüştürün (Aspose.PDF bunu yapar) ve ardından bu batch'i çalıştırın. + +## Sonraki Adımlar – Basit Dönüşümün Ötesine Geçmek + +Şimdi toplu olarak **extract text from TIFF** dosyalarını çıkarabildiğinize göre, şunları yapmak isteyebilirsiniz: + +- *.txt* dosyalarını bir arama indeksine (Elasticsearch, Azure Cognitive Search) beslemek. +- Her sonuçta dil algılaması çalıştırarak belgeleri yerel‑spesifik boru hatlarına yönlendirmek. +- OCR metnini orijinal görüntülerin üzerine bindirerek aranabilir PDF'ler oluşturmak (Aspose.PDF tekrar). + +Bu senaryoların hepsi aynı temel fikri üzerine kuruludur: **batch image to text conversion**, daha büyük belge‑işleme sistemleri için bir yapı taşıdır. + +--- + +### Sonuç + +Az önce Aspose.OCR kullanarak **convert TIFF to text** nasıl yapılacağını, bir klasörü paralel olarak işleyip her sonucu temiz bir *.txt* dosyası olarak kaydetmeyi öğrendiniz. Çözüm hafif, tamamen yapılandırılabilir ve üretime hazır—ister eski faturaları dijitalleştiriyor, ister taranmış sözleşmeleri arşivliyor, ister bir metin‑arama motorunu çalıştırıyor olun. + +Bir deneyin, paralelliği ayarlayın ve yeni oluşturulan metin dosyalarını ihtiyacınız olan herhangi bir iş akışına beslemeye başlayın. İyi OCRlamalar! + +--- + +## İlgili Öğreticiler + +- [Klasörlerde OCR İşlemi Kullanarak Görüntülerden Metin Çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Görüntüden Metin Çıkarma – Aspose.OCR for .NET ile OCR Optimizasyonu](/ocr/english/net/ocr-optimization/) +- [Aspose.OCR Kullanarak Dil Seçimiyle Görüntü Metni Çıkarma C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/turkish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..8f44e6593 --- /dev/null +++ b/ocr/turkish/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,304 @@ +--- +category: general +date: 2026-05-25 +description: Minimal bir ASP.NET Core API ile görüntüden metin çıkarma yöntemini öğrenin. + Görüntüyü POST ile yükleyin, çok parçalı form verilerini okuyun ve görüntü üzerinde + OCR gerçekleştirin. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: tr +og_description: Minimal bir ASP.NET Core API kullanarak görüntüden metin çıkarın. + Bu kılavuz, görüntüyü POST ile nasıl yükleyeceğinizi, multipart form verilerini + nasıl okuyacağınızı ve görüntü üzerinde OCR nasıl yapılacağını gösterir. +og_title: ASP.NET Core'da Görüntüden Metin Çıkarma – Adım Adım +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: ASP.NET Core Minimal API'de Görüntüden Metin Çıkarma – Tam Kılavuz +url: /tr/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# ASP.NET Core Minimal API ile Görüntüden Metin Çıkarma – Tam Kılavuz + +Hiç **görüntüden metin çıkarma** işlemini ağır çerçevelerle uğraşmadan yapmayı düşündünüz mü? Yalnız değilsiniz. Birçok geliştirici, kullanıcıların bir fotoğraf bırakıp ham karakterleri alabilmesi için hızlı bir yol arıyor; ister fiş tarama, el yazısı notları dijitalleştirme, isterse bir arama indeksini besleme olsun. + +Bu eğitimde, **POST ile görüntü yükleme** yapan, *multipart/form‑data* yükünü ayrıştıran ve ardından tek bir `OcrEngine` örneği kullanarak **görüntüde OCR gerçekleştirme** yapan minik bir ASP.NET Core Minimal API oluşturacağız. Sonunda, herhangi bir .NET 8 projesine ekleyebileceğiniz ve hemen görüntüden metin çıkarabileceğiniz tamamen çalışır bir uygulamanız olacak. + +## Ne Yapacaksınız + +- `/ocr` yolunda dinleyen minimal bir web uygulaması. +- `multipart/form-data` POST isteğiyle gönderilen bir görüntü dosyasını kabul eden bir uç nokta. +- Yüklenen dosyayı okuyan, OCR motoruna besleyen ve düz metin sonuçlarını döndüren mantık. +- Uyumlu bir kartı olanlar için (yorum satırı olarak) GPU hızlandırma örneği. + +**Önkoşullar** +- .NET 8 SDK (veya daha yeni). +- C# ve komut satırı konusunda temel bilgi. +- `OcrEngine` sınıfını sunan bir OCR kütüphanesi (örnek, varsayımsal bir NuGet paketi varsayar). + +Bu koşullara sahipseniz, başlayalım. + +## Adım 1: Projeyi Kurun ve OCR Paketini Ekleyin + +İlk olarak yeni bir web projesi oluşturun ve OCR kütüphanesini ekleyin. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Pro ipucu:** Bağımlılıklarınızı güncel tutun. Yeni sürümler genellikle performans artışı getirir, özellikle GPU‑hızlandırmalı çıkarım için. + +## Adım 2: Tek Bir OCR Motoru (Singleton) Kaydedin + +Uygulama boyunca tek bir `OcrEngine` örneği istiyoruz—her istek için yeni bir motor başlatmaya gerek yok. Bunu builder’ın servis konteynerine kaydedin. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Neden singleton?** +Bir OCR motoru oluşturmak maliyetli olabilir—nöral ağ ağırlıklarını belleğe yüklemek gibi. Aynı örneği yeniden kullanarak CPU döngülerinden ve RAM’den tasarruf eder, bu da her `/ocr` çağrısında daha hızlı yanıt süreleri sağlar. + +## Adım 3: Uygulamayı Oluşturun + +Şimdi `WebApplication` nesnesini somutlaştırıyoruz. + +```csharp +var app = builder.Build(); +``` + +Bu satır neredeyse sihirli görünebilir, ancak altında yönlendirme, ara katman (middleware) ve az önce yapılandırdığımız DI konteyneri bağlanır. + +## Adım 4: POST Uç Noktasını Tanımlayın – “POST ile Görüntü Yükleme” + +İşte eğitimin kalbi: **POST ile görüntü yükleme**, multipart yükünü okuyan ve veriyi OCR motoruna veren bir uç nokta. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Mantığın Açıklaması + +| Adım | Ne Olur | Neden Önemli | +|------|----------|--------------| +| **ReadFormAsync** | Gelen *multipart/form-data* isteğini ayrıştırır. | Dosyalara erişim olmadan yüklenen görüntülere ulaşamazsınız. | +| **form.Files["image"]** | Form alanı adı `image` olan dosyayı alır. | Çağırıcılar için öngörülebilir bir sözleşme sağlar. | +| **Content‑type kontrolü** | Dosyanın bir görüntü olduğunu doğrular (örn. `image/png`). | OCR motorunun görüntü dışı verilerle takılmasını önler. | +| **Image.FromStream** | Ham akışı `System.Drawing.Image` nesnesine dönüştürür. | OCR kütüphanesi bir `Image` nesnesi bekler, ham bayt dizisi değil. | +| **ocr.Recognize(img)** | OCR motorunu **görüntüden metin tanıma** için çalıştırır. | Bu, **görüntüde OCR gerçekleştirme** adımının çekirdeğidir. | +| **Results.Text** | Düz metin yanıtını gönderir. | Sonraki hizmetler için basit, tüketilebilir bir format. | + +## Adım 5: API’yi Çalıştırın + +Son olarak web sunucusunu başlatın. + +```csharp +app.Run(); +``` + +`dotnet run` komutunu çalıştırdığınızda API, `http://localhost:5000` (veya seçtiğiniz bir port) üzerinden dinleyecek. `curl` ile test edebilirsiniz: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Beklenen çıktı:** Konsol, tanınan karakterleri yazdırır, örneğin: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Görüntü bulanıksa veya dil desteklenmiyorsa, OCR motoru boş bir dize ya da hata mesajı dönecektir—bu durumları üretim kodunda ele alın. + +## Köşe Durumları ve En İyi Uygulamalar + +### 1. Büyük Dosyalar + +Varsayılan istek gövdesi sınırı 30 MB’tir. Daha büyük taramalar için ayarlamanız gerekebilir: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. Asenkron OCR + +Bazı OCR kütüphaneleri async metodlar (`RecognizeAsync`) sunar. Eğer sizinkinde varsa, `ocr.Recognize(img)` yerine `await ocr.RecognizeAsync(img)` kullanın ve lambda’yı `async` olarak işaretleyin. + +### 3. Güvenlik Hususları + +- **Dosya boyutunu** belleğe yüklemeden önce doğrulayın. +- **Dosya adını** diske yazacaksanız temizleyin. +- **Rate‑limit** uygulayarak hizmet reddi saldırılarını önleyin. + +### 4. GPU Hızlandırma + +`engine.GpuDevice = new GpuDevice(0);` satırının yorumunu kaldırıp donanımınız CUDA ya da DirectML destekliyorsa, özellikle yüksek çözünürlüklü görüntülerde belirgin bir hız artışı göreceksiniz. + +## Tam Çalışan Örnek + +Aşağıda, yeni bir Minimal API projesine kopyalayıp yapıştırabileceğiniz tam `Program.cs` dosyası yer alıyor. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Kaydedin, `dotnet run` komutunu çalıştırın ve **görüntüden metin çıkarma** işlevine anında sahip olun. + +## Sonuç + +ASP.NET Core Minimal API kullanarak **görüntüden metin çıkarma** için **tam, uçtan uca bir çözüm** üzerinden geçtik. Proje iskeletini oluşturduktan, **singleton OCR motoru kaydettikten**, **POST ile görüntü yükleme** uç noktasını kurarak **multipart form verisini okuduk** ve sonunda **görüntüde OCR gerçekleştirme** yaparak temiz düz metin döndürdük. + +Bundan sonra şunları yapabilirsiniz: + +- Daha zengin yanıtlar için JSON sarmalayıcılar ekleyin. +- Çıkarılan metni saklamak için bir veritabanı bağlayın. +- Birden fazla dili desteklemek için (`OcrLanguage.Spanish` vb.) genişletin. + +Bu desen, aynı uç noktayı daha büyük bir mikroservise ekleyerek ya da bir API geçidi arkasına koyarak sorunsuzca ölçeklenebilir. + +PDF işleme, toplu işlem veya GPU ayarları hakkında sorularınız mı var? Yorum bırakın, iyi kodlamalar! + +## İlgili Eğitimler + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/turkish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..1f41fcc16 --- /dev/null +++ b/ocr/turkish/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: C# ve Aspose OCR kullanarak görüntüden metin çıkarın. JPG'yi metne dönüştürmeyi, + OCR için görüntüyü yüklemeyi ve hızlı bir şekilde güvenilir sonuçlar almayı öğrenin. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: tr +og_description: C# ile görüntüden metin çıkarın. Bu kılavuz, jpg'yi metne dönüştürmeyi, + OCR için görüntüyü yüklemeyi ve çok dilli içeriği yönetmeyi gösterir. +og_title: C#'ta Görüntüden Metin Çıkarma – Aspose OCR Öğreticisi +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: C# ile Görüntüden Metin Çıkarma – Tam Aspose OCR Rehberi +url: /tr/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Görüntüden Metin Çıkarma C# – Tam Aspose OCR Kılavuzu + +Hiç **görüntüden metin çıkarma** işlemini sade C# kodu ile yapmayı düşündünüz mü? Tek başınıza değilsiniz. Faturaları dijitalleştiriyor, tabela tarıyor ya da sadece OCR merak ediyorsanız, bir resimden karakterleri çekebilmek kullanışlı bir beceridir. Bu öğreticide, Aspose.OCR ile **görüntüden metin çıkarma** işlemini tam olarak gösteren çalıştırılabilir bir örnek üzerinden adım adım ilerleyecek ve ayrıca **jpg'yi metne dönüştürme**, **OCR için resmi yükleme** ve klasik “**görüntüyü nasıl OCR yaparım**” sorusunun yanıtını da ele alacağız. + +Bu rehberin sonunda, bir JPEG dosyasını okuyup Ukraynaca (veya desteklenen başka bir dil) tanıyan ve sonucu konsola yazdıran bağımsız bir konsol uygulamanız olacak. Belirsiz referanslar, eksik parçalar yok – sadece kopyalayıp yapıştırıp çalıştırabileceğiniz eksiksiz bir çözüm. + +--- + +## Öğrenecekleriniz + +* Aspose.OCR NuGet paketinin nasıl yükleneceği. +* C#’ta **OCR için resmi yükleme** için gereken tam kod. +* Dili ayarlayıp **görüntüden metin çıkarma** nasıl yapılır. +* **Jpg'yi metne dönüştürme** için pratik ipuçları. +* Yaygın tuzaklar ve nasıl önlenir. + +.NET geliştirme ortamınız zaten kuruluysa, hemen başlayabilirsiniz. Aksi takdirde, aşağıdaki önkoşullar bölümü sizi hazırlayacak. + +--- + +## Önkoşullar + +| Gereksinim | Neden önemli | +|-------------|----------------| +| .NET 6.0 SDK (veya daha yenisi) | Konsol uygulaması için çalışma zamanını sağlar. | +| Visual Studio 2022 veya VS Code | Düzenleme ve hata ayıklamayı kolaylaştırır. | +| İnternet bağlantısı (ilk çalıştırmada) | NuGet, Aspose.OCR’ı indirmelidir. | +| İşlemek istediğiniz bir JPEG resmi (ör. `ukrainian_sign.jpg`) | OCR motorunun kaynak dosyası. | + +> **Pro ipucu:** Linux veya macOS kullanıyorsanız, aynı kod .NET CLI (`dotnet new console`) ile çalışır; ağır IDE’yi atlayabilirsiniz. + +--- + +## Adım 1 – Aspose.OCR’ı NuGet ile Yükleyin + +Terminalinizi (veya Package Manager Console) açın ve şu komutu çalıştırın: + +```bash +dotnet add package Aspose.OCR +``` + +Bu tek satır, en yeni Aspose.OCR ikili dosyalarını ve tüm bağımlılıklarını indirir. Manuel DLL yönetimine gerek yok. + +--- + +## Adım 2 – OCR Motorunu Oluşturun (Çıkarma İşleminin Kalbi) + +Kütüphane yüklendikten sonra, bir `OcrEngine` örneği oluşturabiliriz. Bu nesne **görüntüden metin çıkarma** işlemlerinden sorumludur. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Neden önemli:** Motor, OCR algoritmalarını, dil modellerini ve yapılandırma seçeneklerini kapsar. Tek bir kez örnekleyip birden çok resimde yeniden kullanmak hem bellek açısından verimli hem de hızlıdır. + +--- + +## Adım 3 – OCR için Resmi Yükleyin (Ve Dili Ayarlayın) + +Sonraki adım, motorun hangi resmi okuyacağını belirtmektir. İşte **OCR için resmi yükleme** ifadesinin devreye girdiği yer. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Özel durum:** Dosya bulunamazsa, `Image.FromFile` bir `FileNotFoundException` fırlatır. Üretim kodunda bu çağrıyı try‑catch bloğuyla sarmalayın. + +--- + +## Adım 4 – OCR’u Gerçekleştirip Metni Çıkarın + +Resim yüklendikten sonra, motor artık **görüntüden metin çıkarma** yapabilir. `Recognize` metodu ağır işi üstlenir. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Her şey yolunda giderse, `recognizedText` OCR motorunun okuyabildiği her şeyin düz metin temsili olacaktır. + +--- + +## Adım 5 – JPG'yi Metne Dönüştürün (Hepsini Bir Araya Getirin) + +Şimdiye kadar oluşturduğumuz kod zaten **jpg'yi metne dönüştürme** işlevini sağlıyor, ancak bunu tekrar tekrar çağırabileceğiniz şık bir metoda alalım. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Artık şu şekilde kullanabilirsiniz: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Beklenen çıktı** (kısaltılmış): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Resimde İngilizce metin varsa, `OcrLanguage.English` olarak değiştirin ve ilgili çıktıyı göreceksiniz. + +--- + +## Adım 6 – Yaygın “Görüntüyü Nasıl OCR Yapılır?” Sorularını Ele Alın + +### 6.1 PNG veya BMP OCR yapılabilir mi? + +Kesinlikle. `Image.FromFile` metodu, System.Drawing’in tanıdığı tüm formatları destekler; sadece yolu `.png` ya da `.bmp` dosyasına yönlendirin, kod aynı kalır. + +### 6.2 Resim düşük çözünürlükteyse ne olur? + +300 dpi’nin altındaki görüntülerde OCR doğruluğu büyük ölçüde düşer. Hızlı bir çözüm, resmi motorun önüne `Graphics` ile yükseltmektir: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Aspose.OCR için lisansa ihtiyacım var mı? + +Aspose, su işaretiyle ücretsiz bir deneme sunar. Üretim ortamı için lisans satın alın ve şu satırı ekleyin: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Tam Çalışan Örnek + +Aşağıda, **görüntüyü OCR yapma**, **OCR için resmi yükleme** ve **jpg'yi metne dönüştürme** işlemlerini tek bir paket içinde gösteren, hazır‑çalıştırılabilir bir konsol uygulaması yer alıyor. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Nasıl çalıştırılır** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Konsola çıkarılan metni göreceksiniz; bu, C# ile **görüntüden metin çıkarma** işlemini başarıyla tamamladığınız anlamına gelir. + +--- + +## Yaygın Tuzaklar ve Pro İpuçları + +| Sorun | Neden oluşur | Çözüm | +|-------|----------------|-----| +| Boş çıktı | Resim çok karanlık veya düşük kontrastlı. | Parlaklığı artırmak için `Bitmap` ile ön‑işleme yapın. | +| Yanlış dil | `Language` özelliği varsayılan İngilizce olarak kalmış. | `ocrEngine.Language = OcrLanguage.Ukrainian;` gibi hedef dili açıkça ayarlayın. | +| Bellek hatası | Çok büyük resimler serbest bırakılmadan yükleniyor. | `Image.FromFile`ı `using` bloğu içinde kullanın (gösterildiği gibi). | +| Lisans su işareti | Lisans olmadan deneme sürümü çalışıyor. | `Main` içinde satın alınan lisansı erken uygulayın. | + +--- + +## Sonuç + +C#’ta **görüntüden metin çıkarma** için ihtiyacınız olan her şeyi kapsadık – Aspose.OCR kurulumu, **OCR için resmi yükleme**, **jpg'yi metne dönüştürme** ve çok‑dilli senaryolar. Tam örnek program, tüm parçaları bir araya getirerek OCR‑ile ilgili herhangi bir projeye sağlam bir temel sunar. + +İleride keşfedebilecekleriniz: + +* **Görüntüyü OCR yapma** akışını dosyalar yerine akışlar (`MemoryStream`) üzerinden gerçekleştirmek. +* **c# image to text** sonrası işlem olarak yazım denetimi eklemek. +* OCR adımını daha büyük bir veri hattına entegre etmek (ör. sonuçları bir veritabanına kaydetmek). + +Farklı diller, resim formatları ve ön‑işleme teknikleriyle denemeler yapmaktan çekinmeyin. OCR, bir sanat olduğu kadar bir bilimdir; ne kadar çok oynarsanız sonuçlar o kadar iyi olur. + +İyi kodlamalar, ve resimleriniz her zaman okunabilir olsun! + +## İlgili Eğitimler + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/turkish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..5941c1856 --- /dev/null +++ b/ocr/turkish/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-05-25 +description: C#'ta OCR kullanarak görüntü dosyalarından metin nasıl çıkarılır. Aspose.OCR + ile bir JPG'den Çince karakterleri tanımayı birkaç basit adımda öğrenin. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: tr +og_description: C#'ta OCR kullanarak görüntü dosyalarından metin nasıl çıkarılır. + Bu kılavuz, Aspose.OCR kullanarak bir JPG'den Çince karakterleri nasıl tanıyacağınızı + gösterir. +og_title: C#'de OCR Nasıl Kullanılır – JPG'den Çince Metni Tanıma +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: C#'ta OCR Nasıl Kullanılır – JPG'den Çince Metni Tanıma +url: /tr/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta OCR Nasıl Kullanılır – JPG'den Çince Metin Tanıma + +Ever wondered **how to use OCR** to pull words out of a picture you snapped on your phone? You’re not alone. In many real‑world projects—think receipt scanners, translation apps, or automated data entry—you’ll need to **extract text from image** files quickly and reliably. + +In this tutorial we’ll walk through a complete, runnable example that **recognizes text from JPG** files and even handles the tricky case of **recognize Chinese characters** using the **OCR Chinese Simplified** language pack. By the end, you’ll have a self‑contained console app that prints the detected string to the console, no extra manual downloads required. + +> **Quick note:** Kod, ilk kullanımda dil kaynaklarını otomatik olarak indiren Aspose.OCR ≥ 23.7 ile çalışır. Daha eski bir sürüm kullanıyorsanız, dili manuel olarak eklemeniz gerekir. + +## Önkoşullar + +- .NET 6.0 SDK veya daha yeni bir sürüm (örnek .NET 6 hedefli, ancak .NET 5 de çalışır) +- Visual Studio 2022 veya C# uzantılı VS Code'un güncel bir sürümü +- İlk dil indirmesi için bir internet bağlantısı +- Basitleştirilmiş Çince metin içeren bir JPG görüntüsü (`chinese_sign.jpg` olarak adlandıralım) + +Hepsi bu—ağır OCR motorları yok, yerel DLL karışıklığı yok. Sadece birkaç NuGet komutu ve birkaç satır kod. + +## Adım 1: Aspose.OCR'yi NuGet üzerinden kurun + +İlk olarak, OCR kütüphanesine ihtiyacımız var. Proje klasörünüzde bir terminal açın ve şu komutu çalıştırın: + +```bash +dotnet add package Aspose.OCR +``` + +Ya da Visual Studio arayüzünü tercih ediyorsanız, **Dependencies → Manage NuGet Packages** üzerine sağ‑tıklayın, “Aspose.OCR” için arama yapın ve **Install** düğmesine tıklayın. + +> **Pro tip:** Paketlerinizi güncel tutun. Yeni dil paketleri ve performans iyileştirmeleri her küçük sürümde eklenir. + +## Adım 2: Yeni Bir Konsol Projesi Oluşturun (Henüz Oluşturmadıysanız) + +Sıfırdan başlıyorsanız, yeni bir konsol uygulaması oluşturun: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Artık OCR kodu için hazır bir `Program.cs` dosyanız var. + +## Adım 3: OCR Kodunu Yazın – JPG'den Basitleştirilmiş Çince Tanıma + +`Program.cs` dosyasını açın ve içeriğini aşağıdakilerle değiştirin. Her satır açıklamalı, böylece sadece *ne* yaptığımızı değil, *neden* yaptığımızı da görebilirsiniz. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Arkada Ne Oluyor? + +- **`OcrEngine.Language`** Aspose'a hangi sözlüğün kullanılacağını söyler. `ChineseSimplified` seçilerek motor, Basitleştirilmiş Çince dil paketini aramaya yönlendirilir. +- **First‑time download**: `Recognize` çalıştığında, SDK Aspose'un CDN'ine bağlanır, ≈6 MB'lık dil dosyasını çeker, yerel olarak önbelleğe alır ve ardından OCR işlemini gerçekleştirir. Sonraki çağrılar anında gerçekleşir. +- **`Image.FromFile`** .NET'in çözebildiği herhangi bir raster formatıyla çalışır—JPG, PNG, BMP—bu sayede **extract text from image** dosyalarını sadece JPG değil, birçok tipten çıkarabilirsiniz. + +## Adım 4: Uygulamayı Çalıştırın ve Çıktıyı Doğrulayın + +Derleyin ve çalıştırın: + +```bash +dotnet run +``` + +Şuna benzer bir şey görmelisiniz: + +``` +=== Recognized Text === +欢迎光临 +``` + +Eğer konsol anlamsız karakterler ya da boş bir dize yazdırıyorsa, şunları kontrol edin: + +1. Görüntünün gerçekten net, yüksek kontrastlı Çince karakterler içerdiğinden emin olun. +2. Dosya yolunun doğru olduğundan (gereksiz boşluklar veya eksik uzantılar olmadığından) emin olun. +3. Makinenizin dil paketi için `https://download.aspose.com` adresine erişebildiğini kontrol edin. + +## Adım 5: Kenar Durumlarını ve Yaygın Tuzakları Ele Alma + +### 5.1 Düşük Kaliteli Görüntülerle Baş Etme + +Kaynak görüntü bulanık, gürültülü veya kötü aydınlatmalı olduğunda OCR doğruluğu düşer. Hızlı bir çözüm, görüntüyü ön‑işlemektir: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Başsız (Headless) Ortamda Çalıştırma + +GUI'siz bir Linux konteynerine dağıtım yapıyorsanız, `System.Drawing` için gerekli olan `libgdiplus` kütüphanesinin kurulu olduğundan emin olun: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Dil Paketini Manuel Olarak Önbelleğe Alma + +Dil dosyasını bir kez indirip, Aspose'yi `License` API'si aracılığıyla ona yönlendirebilirsiniz; bu, tek seferlik ağ çağrısını ortadan kaldırır. Çevrim dışı senaryolar için kullanışlıdır. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Tam Çalışan Örnek (Hepsi Bir Arada) + +Aşağıda, `Program.cs` içine kopyalayıp yapıştırabileceğiniz *tam* program yer alıyor. Gizli parçalar yok, dış script yok. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Beklenen Çıktı + +JPG, “欢迎光临” ifadesini içeriyorsa, konsol şu çıktıyı verir: + +``` +=== Recognized Text === +欢迎光临 +``` + +Görüntüyü başka bir Basitleştirilmiş Çince işaret, sokak adı veya ürün etiketiyle değiştirmekten çekinmeyin—motor elinden geleni yapacaktır. + +## Sonuç + +C#'ta **how to use OCR**'ı, **extract text from image** dosyalarından **recognize Chinese characters**'ı **JPG** içinde ele alarak nasıl yapacağımızı yeni gördük. Aspose.OCR'nin anında dil indirme özelliğini kullanarak dağıtımınızı hafif tutabilir ve **OCR Chinese Simplified**'ı kutudan çıkar çıkmaz destekleyebilirsiniz. + +Sırada ne var? Şu fikirleri deneyin: + +- **Batch processing**: Bir klasördeki görüntüleri döngüye alıp her sonucu bir CSV'ye yazın. +- **Combine with translation APIs**: Tanınan dizeyi gerçek zamanlı çok dilli uygulamalar için Azure Translator'a gönderin. +- **Explore other languages**: `OcrLanguage.ChineseSimplified`'ı `Japanese` veya `Arabic` ile değiştirin ve aynı kodun nasıl uyduğunu görün. + +Performans ayarı, lisanslama veya OCR'yi bir web servisine entegre etme hakkında sorularınız mı var? Aşağıya yorum bırakın—iyi kodlamalar! + +--- + +![C#'ta OCR kullanarak JPG görüntüsünden Çince metin tanıma gösteren konsol çıktısının ekran görüntüsü](ocr-chinese-demo.png "OCR konsol çıktısını nasıl kullanılır") + +## İlgili Öğreticiler + +- [Aspose.OCR kullanarak dil seçimiyle Görüntü Metni Çıkarma C#](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Aspose OCR ile çoklu dillerde metin görüntüsü tanıma](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [OCR'de Dikdörtgen Hazırlayarak Görüntüden Metin Çıkarma](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/turkish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/turkish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..b44f22164 --- /dev/null +++ b/ocr/turkish/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: C#'ta Rusça metni OCR ile nasıl tanıyacağınızı ve Aspose OCR ile görüntüden + metin çıkartacağınızı öğrenin. Görüntüyü hızlıca metne dönüştüren adım adım C# kodu. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: tr +og_description: C#'ta Rusça metin OCR'u artık kolay. Görüntüden metin çıkarmayı, görüntüyü + C#'ta metne dönüştürmeyi ve Aspose OCR ile OCR için görüntü yüklemeyi öğrenin. +og_title: C#'ta Rus Metin OCR – Tam Aspose OCR Rehberi +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: C#'da Rus Metin OCR – Aspose OCR Kullanarak Tam Kılavuz +url: /tr/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# C#'ta Rus Metin OCR – Aspose OCR Kullanarak Tam Kılavuz + +C#'ta Rus metni OCR'lamak gerektiğinde, hangi kütüphaneye güveneceğinizi bilemediniz mi? Yalnız değilsiniz. Kiril alfabesinden temiz, okunabilir karakterler elde etmek, doğru dil modelini ayarlamadıysanız, gizli mesajları çözmek gibi hissettirebilir. + +Bu öğreticide, **extract text from image** dosyalarından metin çıkarmayı, *image to text C#* tarzında dönüştürmeyi ve Aspose OCR ile Rus dili tanımanın inceliklerini gösteren uygulamalı bir örnek üzerinden ilerleyeceğiz. Sonunda, OCR için bir görüntüyü yükleyen, tanınan dizeyi yazdıran ve daha gelişmiş senaryolar için sağlam bir temel sağlayan, çalıştırmaya hazır bir konsol uygulamanız olacak. + +## Öğrenecekleriniz + +- Rus dili desteği için **Aspose OCR C#** nasıl kurulur ve yapılandırılır. +- **load image for OCR** nasıl yapılır ve motor nasıl çağrılır. +- Eksik dil kaynakları veya bulanık taramalar gibi yaygın tuzaklarla başa çıkma ipuçları. +- Çözümü genişletme yolları, örneğin birden fazla dosyanın toplu işlenmesi veya güven eşiği ayarları. + +Aspose ile önceden deneyiminiz olmasına gerek yok; sadece C# ve .NET hakkında temel bir bilgi sizi harekete geçirecek. + +## Önkoşullar + +İlerlemeye başlamadan önce aşağıdakilere sahip olduğunuzdan emin olun: + +1. **.NET 6.0** (veya daha yeni) SDK yüklü – kod .NET Core ve .NET Framework'te aynı şekilde çalışır. +2. **Visual Studio 2022** (veya tercih ettiğiniz herhangi bir IDE). +3. **Aspose.OCR for .NET** NuGet paketi – Aspose web sitesinden ücretsiz deneme anahtarını alabilirsiniz. +4. **Russian language model** dosyası (`rus.traineddata`) – bunu Aspose kaynak sayfasından indirip daha sonra referans göstereceğiniz bir klasöre yerleştirin. +5. Açık Kiril metni içeren bir örnek görüntü (`russian_doc.png`). + +Hepsi hazır mı? Harika—haydi başlayalım. + +## Adım 1: Projeyi Kurun ve Aspose OCR'yi Yükleyin + +İlk olarak, yeni bir konsol projesi oluşturun: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Şimdi Aspose OCR paketini ekleyin: + +```bash +dotnet add package Aspose.OCR +``` + +> **Pro tip:** Deneme lisansı kullanıyorsanız, `Aspose.Total.lic` dosyasını elinizin altında bulundurun; kod içinde yükleyerek filigranları önleyeceksiniz. + +Paket yüklendikten sonra `Program.cs` dosyasını açın. Varsayılan `Main` metodunu göreceksiniz—içeriğini, oluşturacağımız iskeletle değiştirin. + +## Adım 2: OCR Motorunu Rus Dili İçin Yapılandırın + +İşlemin kalbi `OcrEngine` nesnesidir. Ona iki şeyi söylememiz gerekir: hangi dili tanıyacağı ve dil modeli dosyalarının nerede olduğu. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Neden önemli:** `Language = OcrLanguage.Russian` ayarını atlamanız durumunda motor varsayılan olarak İngilizceyi kullanır ve Kiril karakterleri bozuk semboller olarak görünür. `ResourceFolder`, `rus.traineddata` dosyasını içeren dizini gösterir; bu olmadan Aspose *resource not found* hatası verir. + +## Adım 3: OCR İçin Görüntüyü Yükleyin + +Şimdi **load image for OCR** yapmamız gerekiyor. Aspose OCR, `System.Drawing.Image` ile çalışır, bu yüzden desteklenen herhangi bir formatı (PNG, JPEG, BMP vb.) geçirebilirsiniz. Dosya yolunun doğru olduğundan emin olun; görüntüyü çalıştırılabilir dosyanın yanına koyarsanız göreceli yollar da uygundur. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Köşe durumu:** Görüntü büyükse (5 MB'den fazla) önce ölçeklendirmek isteyebilirsiniz. DPI çok düşük olduğunda OCR doğruluğu düşer, ancak çok büyük dosyalar bellek baskısına neden olabilir. Gerekirse `Graphics` ile hızlı bir yeniden boyutlandırma yapılabilir. + +## Adım 4: Metni Tanıma – Görüntüden Metne C# Stili + +Motor yapılandırıldı ve görüntü yüklendiğinde, gerçek tanıma tek bir çağrı ile gerçekleşir: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Programı (`dotnet run`) çalıştırdığınızda aşağıdakine benzer bir çıktı görmelisiniz: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Eğer çıktı anlamsız görünüyorsa, şunları iki kez kontrol edin: + +- `rus.traineddata` dosyasının `ResourceFolder` içinde bulunduğundan emin olun. +- Görüntü çok bulanık değil; OCR'den önce basit bir ikilileştirme filtresi uygulamayı düşünün. +- Dil ayarının gerçekten `OcrLanguage.Russian` olduğundan emin olun. + +## Adım 5: İnce Ayar ve Yaygın Tuzaklar + +### Güven Eşiğini Ayarlama + +Aspose OCR, dahili olarak karakter başına bir güven değeri döndürür. API bunu doğrudan sunmasa da, düşük güvenli kelimeleri görmek için **detailed output**'ı etkinleştirebilirsiniz: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Eğer sık sık hatalı tanıma görürseniz, şunları deneyin: + +- **Pre‑processing**: Görüntüyü gri tonlamaya çevirin, kontrastı artırın veya bir medyan filtre uygulayın. +- **DPI settings**: Kiril scriptleri için görüntünün en az 300 DPI olduğundan emin olun. + +### Birden Fazla Görüntüyü Toplu İşleme + +Eğer toplu olarak **extract text from image** dosyalarından metin çıkarmanız gerekiyorsa, tanıma mantığını bir döngüye sarın: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Artık her PNG kendi `.txt` karşılığına sahip—belge arşivleme için kullanışlı. + +### Unicode Çıktısını İşleme + +Kiril karakterleri Unicode'dur, bu yüzden konsol kodlamanızın bunları gösterebildiğinden emin olun: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Bu satırı `Main` metodunun hemen başında yerleştirin. Olmazsa, Rus harfleri yerine soru işaretleri (`?`) görebilirsiniz. + +## Tam Çalışan Örnek + +Aşağıda eksiksiz, çalıştırmaya hazır kod bulunuyor. `Program.cs` içine kopyalayıp yapıştırın, yolları ayarlayın ve hazırsınız. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Beklenen çıktı** (örnek görüntü “Пример текста на русском языке.” diyor varsayarsak): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Eğer başka bir şey görürseniz, Adım 5'teki sorun giderme ipuçlarına tekrar bakın. + +## Sonuç + +Artık Aspose OCR kullanarak C#'ta **ocr russian text** nasıl yapılır konusunda sağlam, uçtan uca bir örneğe sahipsiniz. Kütüphaneyi kurmaktan, Rus dili modelini yapılandırmaya, görüntüyü yükleyip temiz Unicode metne dönüştürmeye kadar her adım ele alındı. + +Unutmayın, güvenilir OCR'ın anahtarı iyi kaynak materyaldir: net yazı tipleri, yeterli DPI ve doğru dil kaynakları. Temelleri kavradıktan sonra toplu işleme, bulut depolama entegrasyonu veya hatta yazım denetimi için AI sonrası işleme gibi konulara genişletebilirsiniz. + +### Sıradaki Adımlar? + +- **aspose ocr c#**'nin düzen analizi veya PDF çıktısı gibi gelişmiş seçeneklerini keşfedin. +- Bunu, Azure Functions'ta **extract text from image** iş akışlarıyla birleştirerek sunucusuz işleme uygulayın. +- Farklı dilleri deneyin—sadece `OcrLanguage.Russian` yerine `OcrLanguage.English` ya da başka desteklenen bir kodu kullanın. + +Sorularınız veya işbirliği yapmayan zor bir görüntünüz var mı? Aşağıya yorum bırakın, iyi kodlamalar! + +![ocr russian text example](ocr-russian-example.png){alt="ocr russian text example"} + +## İlgili Öğreticiler + +- [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 ile çoklu dillerde metin görüntüsü tanıma](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Aspose.OCR .NET kullanarak Görüntüden Metin Çıkarma](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/turkish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..b444d5357 --- /dev/null +++ b/ocr/turkish/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,209 @@ +--- +category: general +date: 2026-05-25 +description: C#'ta Aspose OCR kullanarak görüntüden metin tanıma. OCR için görüntünün + nasıl yükleneceğini, OCR dilinin nasıl ayarlanacağını, OCR motorunun nasıl oluşturulacağını + ve TIFF'ten metnin nasıl çıkarılacağını öğrenin. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: tr +og_description: Aspose OCR kullanarak C#'de görüntüden metin tanıma. Bu öğreticide + OCR motoru oluşturma, OCR için görüntü yükleme, OCR dilini ayarlama ve TIFF'ten + metin çıkarma gösterilmektedir. +og_title: Aspose OCR ile Görüntüden Metin Tanıma – Tam C# Rehberi +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Aspose OCR ile görüntüden metin tanıma – Tam C# Kılavuzu +url: /tr/net/text-recognition/recognize-text-from-image-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 Görüntüden Metin Tanıma – Tam C# Kılavuzu + +Görüntüden **görüntüden metin tanıma** ihtiyacı hiç duydunuz mu, ancak hangi kütüphanenin hem hız hem de doğruluk sağlayacağını bilemediniz mi? Yalnız değilsiniz. Birçok fatura‑işleme veya arşivleme projesinde en büyük sorun, TIFF dosyalarından temiz, aranabilir metin elde etmek ve özel bir ayrıştırıcı yazmadan bunu başarmaktır. + +Şöyle ki: Aspose OCR for .NET bu tüm süreci çocuk oyuncağı haline getiriyor. Bu kılavuzda ihtiyacınız olan her şeyi adım adım göstereceğiz—paketi kurma, **OCR motoru oluşturma**, bir TIFF yükleme, OCR dilini ayarlama ve sonunda **TIFF'ten metin çıkarma**. Sonunda, **görüntüden metin tanıma** dosyalarını anında işleyebilen hazır bir konsol uygulamanız olacak. + +## Gereksinimler + +- .NET 6.0 veya üzeri (kod .NET Core ve .NET Framework ile de çalışır) +- Visual Studio 2022 (veya tercih ettiğiniz herhangi bir IDE) +- Aspose.OCR NuGet paketi (GPU desteği `Aspose.OCR.Gpu` eklentisini gerektirir) +- Ekstra hız istiyorsanız CUDA destekli bir GPU (isteğe bağlı ama önerilir) + +> **Pro tip:** GPU'nuz yoksa, sadece `GpuDevice` satırını kaldırın ve motor otomatik olarak CPU'ya geçecektir. + +## Adım 1: Aspose OCR'yi Kurun ve OCR Motoru Oluşturun + +İlk olarak, gerekli paketleri NuGet üzerinden ekleyin: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Şimdi **OCR motoru oluşturabiliriz**. Bu nesne sürecin kalbidir; çalışacağı cihaz ve bellek limitleri gibi yapılandırmaları tutar. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Neden önemli?** Motoru bir GPU'ya bağlayarak, özellikle yüksek çözünürlüklü TIFF'lerin büyük partileri için **görüntüden metin tanıma** süresini büyük ölçüde azaltırsınız. + +## Adım 2: OCR için Görüntüyü Yükle + +Sonra, **OCR için görüntüyü yüklememiz** gerekiyor. Aspose.OCR, `System.Drawing.Image` ile çalışır, bu yüzden GDI+ tarafından desteklenen herhangi bir format (çok sayfalı TIFF dahil) uygundur. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Eğer çok sayfalı bir TIFF ile çalışıyorsanız, `image.SelectActiveFrame` kullanarak sayfalar arasında döngü yapabilirsiniz, ancak çoğu senaryoda tek bir çağrı yeterlidir. + +## Adım 3: OCR Dilini Ayarla + +Motor, taradığınız dili sihirli bir şekilde bilmez. Tanıyıcıyı çalıştırmadan önce **OCR dilini ayarlayın**; aksi takdirde çok fazla bozuk çıktı alırsınız. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Biliyor muydunuz?** Çalışma zamanında dilleri değiştirmek maliyetli değildir—sayfalar arasında bu özelliği değiştirerek karışık dilli bir belge bile işleyebilirsiniz. + +## Adım 4: Tanıma İşlemini Gerçekleştir – Görüntüden Metin Tanıma + +Şimdi eğlenceli kısım: aslında **görüntüden metin tanıma**. `Recognize` yöntemi, tespit edilen tüm karakterleri içeren düz bir string döndürür. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Eğer güven puanları veya sınırlama kutuları (bounding boxes) gerekiyorsa, `OcrResult` nesnesi döndüren aşırı yüklemeyi (overload) kullanabilirsiniz, ancak çoğu çıkarma görevinde düz string yeterlidir. + +## Adım 5: TIFF'ten Metin Çıkarma (ve çok sayfalı dosyaları işleme) + +Kaynak, birden fazla sayfa içeren bir TIFF ise, her çerçeve için adım 2‑4'ü tekrarlamak isteyeceksiniz. İşte **TIFF'ten metin çıkarma** işlemini sayfa sayfa yapan hızlı bir döngü: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Yukarıdaki kod, her sayfa için çıkarılan metni yazdırır ve sonuçları bir veritabanına ya da arama indeksine yönlendirmeyi çok basit hâle getirir. + +## Adım 6: Çıkarılan Metni Görüntüle veya Sakla + +Son olarak, **çıkarılan metni görüntüleyelim** ve isteğe bağlı olarak daha sonraki işlem için bir dosyaya yazalım. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Programı çalıştırdığınızda tanınan karakterler çıktılanacak ve kaynak TIFF'inizin yanına `extracted_text.txt` dosyası oluşturulacaktır. + +--- + +## Yaygın Sorular & Özel Durumlar + +- **GPU'm algılanmazsa ne olur?** + `GpuDevice` satırını kaldırın; motor otomatik olarak CPU moduna geçecektir. Performans daha yavaş olur ancak sonuçlar doğru kalır. + +- **PNG veya JPEG dosyalarını işleyebilir miyim?** + Kesinlikle—`Image.FromFile` System.Drawing tarafından desteklenen herhangi bir formatta çalışır, bu yüzden uzantı ne olursa olsun **OCR için görüntüyü yükleyebilirsiniz**. + +- **Düşük çözünürlüklü taramaları nasıl ele alırım?** + `Recognize` çağrısından önce `ocrEngine.PreprocessOptions.Dpi` değerini artırın. Daha yüksek DPI, motorun çalışacağı daha fazla piksel sağlar ve doğruluğu artırır. + +- **TIFF'in boyutu için bir limit var mı?** + `GpuMemoryLimit` özelliği GPU kullanımını sınırlar. Limit aşılırsa, motor kalan sayfalar için CPU'ya geçecektir. + +## Sonuç + +Artık Aspose OCR kullanarak C# içinde **görüntüden metin tanıma** dosyaları için tam, üretime hazır bir kod parçacığınız var. Eğitim, **OCR motoru oluşturma**, **OCR için görüntüyü yükleme**, **OCR dilini ayarlama** ve **TIFF'ten metin çıkarma** konularını kapsadı—hepsi hız için GPU hızlandırmasından yararlanarak. + +Bundan sonra şunları yapabilirsiniz: + +- Farklı dillerle deney yapın (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified` vb.). +- Çıktıyı aranabilir bir ElasticSearch indeksine entegre edin. +- Veri kalitesini artırmak için son‑işleme (imla kontrolü, regex temizliği) ekleyin. + +Kendi fatura topluluğunuzda bir deneme yapın, bellek limitlerini ayarlayın ve OCR performansının nasıl yükseldiğini izleyin. İyi kodlamalar! + +## İlgili Eğitimler + +- [Aspose.OCR kullanarak dil seçimiyle C# görüntü metni çıkarma](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [OCR'da Dikdörtgen Hazırlayarak Görüntüden Metin Çıkarma](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Görüntüden Metin Çıkarma – Aspose.OCR ile Satır Tanıma](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..9f3f56428 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. +### [Tạo Engine OCR trong C# – Hướng Dẫn Đầy Đủ](./create-ocr-engine-in-c-complete-guide/) +Hướng dẫn chi tiết cách tạo engine OCR trong C# sử dụng Aspose.OCR, bao gồm cấu hình và ví dụ thực tế. ### 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/create-ocr-engine-in-c-complete-guide/_index.md b/ocr/vietnamese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md new file mode 100644 index 000000000..dafac74d9 --- /dev/null +++ b/ocr/vietnamese/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/_index.md @@ -0,0 +1,266 @@ +--- +category: general +date: 2026-05-25 +description: Tạo công cụ OCR bằng C# và tìm hiểu cách kiểm tra chế độ dùng thử và + trạng thái cấp phép trong vài dòng mã. +draft: false +keywords: +- create OCR engine +- OCR engine evaluation mode +- check OCR license +- OcrEngine usage +- OCR licensing status +language: vi +og_description: Tạo công cụ OCR bằng C# và ngay lập tức xem cách phát hiện chế độ + dùng thử và hiển thị trạng thái cấp phép. +og_title: Tạo Engine OCR bằng C# – Hướng dẫn từng bước +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + headline: Create OCR Engine in C# – Complete Guide + type: TechArticle +- description: Create OCR engine in C# and learn how to check its evaluation mode + and licensing status in a few lines of code. + name: Create OCR Engine in C# – Complete Guide + steps: + - name: What If the Property Is Missing? + text: Older SDK versions might expose a method like `GetLicenseInfo()` instead. + In that case, you’d inspect the returned object for a `IsTrial` flag. Always + consult the SDK changelog when upgrading. + - name: Expected Output + text: '- **Trial build:** `Running in evaluation mode – limited functionality.`' + - name: 1. Null Engine Instances + text: 'Although the constructor usually returns a valid object, some SDKs may + return `null` if required native dependencies are missing. Guard against it:' + - name: 2. License Expiration While Running + text: A trial license can expire mid‑session. Periodically re‑query `IsEvaluation` + if your app stays alive for a long time. + - name: 3. Different Property Names Across Versions + text: Older releases might expose `engine.EvaluationMode` or `engine.License.IsTrial`. + When you upgrade, search the SDK release notes for breaking changes. + - name: 4. Multi‑Threaded Scenarios + text: If you spin up several OCR workers, instantiate **one OCR engine per thread** + unless the SDK explicitly supports thread‑safe sharing. Sharing a single engine + can lead to race conditions and false licensing reads. + type: HowTo +tags: +- OCR +- C# +- Licensing +title: Tạo Engine OCR trong C# – Hướng dẫn toàn diện +url: /vi/net/ocr-configuration/create-ocr-engine-in-c-complete-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tạo Engine OCR trong C# – Hướng Dẫn Toàn Diện + +Bạn đã bao giờ tự hỏi làm sao **tạo đối tượng engine OCR** trong C# mà không phải lục lọi vô số tài liệu? Bạn không phải là người duy nhất. Nhiều nhà phát triển gặp khó khăn khi cần khởi tạo một engine OCR, kiểm tra xem nó có đang chạy ở chế độ dùng thử hay không, và hiển thị trạng thái cấp phép cho người dùng. + +Trong tutorial này, chúng ta sẽ đi qua một ví dụ ngắn gọn, từ đầu tới cuối, **tạo một OCR engine**, kiểm tra **chế độ đánh giá của OCR engine**, và in ra một thông báo thân thiện về trạng thái cấp phép. Khi kết thúc, bạn sẽ có một ứng dụng console sẵn sàng chạy và một mô hình tư duy rõ ràng để xử lý việc cấp phép OCR trong các dự án của mình. + +## Những gì bạn sẽ học + +- Cách khởi tạo một `OcrEngine` (cốt lõi của bất kỳ quy trình OCR nào). +- Tại sao việc phát hiện **chế độ đánh giá** lại quan trọng đối với tuân thủ và trải nghiệm người dùng. +- Cách **kiểm tra trạng thái giấy phép OCR** và phản hồi khi gặp các trạng thái bất ngờ. +- Những bẫy thường gặp—tham chiếu null, xử lý ngoại lệ, và sự không khớp phiên bản. + +Không cần công cụ bên ngoài nào ngoài SDK OCR mà bạn đã cài đặt. Nếu bạn đã quen với cú pháp C# cơ bản, bạn đã sẵn sàng. + +## Yêu cầu trước + +- .NET 6.0 trở lên (mã có thể biên dịch với .NET Core và .NET Framework). +- Một OCR SDK cung cấp lớp `OcrEngine` với thuộc tính `IsEvaluation` (ví dụ, SDK giả định `MyOcrSdk`). +- Trình soạn thảo văn bản hoặc IDE (Visual Studio, VS Code, Rider—chọn bất kỳ cái nào bạn thích). + +Đó là tất cả. Hãy bắt đầu. + +## Bước 1: Tạo Dự Án Console Mới + +Đầu tiên, tạo một ứng dụng console mới để bạn có thể chạy mã một cách độc lập. + +```bash +dotnet new console -n OcrEngineDemo +cd OcrEngineDemo +``` + +Mở file `Program.cs` được tạo ra. Chúng ta sẽ thay thế nội dung của nó bằng một ví dụ hoàn chỉnh **tạo các đối tượng OCR engine** và xử lý cấp phép. + +## Bước 2: Nhập Namespace của OCR SDK + +Giả sử SDK đã được tham chiếu qua NuGet (`MyOcrSdk` chỉ là tên placeholder), thêm chỉ thị `using` ở đầu file. + +```csharp +using MyOcrSdk; // Replace with the actual namespace of your OCR library +``` + +Nếu bạn chưa thêm gói này, chạy: + +```bash +dotnet add package MyOcrSdk +``` + +> **Mẹo:** Giữ phiên bản SDK luôn cập nhật; các bản phát hành mới thường cải thiện việc phát hiện chế độ dùng thử. + +## Bước 3: Tạo Instance của OCR Engine + +Bây giờ chúng ta cuối cùng **tạo đối tượng OCR engine**. Đây là trái tim của bất kỳ quy trình OCR nào—nghĩ như bộ não sẽ đọc các hình ảnh sau này. + +```csharp +// Step 3: Instantiate the OCR engine +OcrEngine engine = new OcrEngine(); +``` + +Tại sao bước này lại quan trọng? `OcrEngine` bao hàm tất cả cấu hình, gói ngôn ngữ, và dữ liệu cấp phép. Không có nó, bạn không thể xử lý ảnh hoặc truy vấn cờ đánh giá. + +> **Lưu ý phụ:** Một số SDK cho phép bạn truyền một đối tượng cấu hình vào constructor (ví dụ: ngôn ngữ, DPI). Nếu cần cài đặt tùy chỉnh, hãy sửa dòng tương ứng. + +## Bước 4: Xác Định Chế Độ Đánh Giá của OCR Engine + +Hầu hết các nhà cung cấp OCR cung cấp phiên bản dùng thử chạy ở **chế độ đánh giá** cho đến khi có khóa giấy phép hợp lệ. Biết bạn đang ở chế độ trial giúp bạn hiển thị các gợi ý UI phù hợp hoặc hạn chế một số tính năng. + +```csharp +// Step 4: Check if the engine is running in evaluation (trial) mode +bool isEvaluation = engine.IsEvaluation; +``` + +Thuộc tính `IsEvaluation` trả về `true` khi engine chưa được cấp phép hoặc đang sử dụng bản dùng thử có thời hạn. Đây là cách nhanh, đáng tin cậy để bảo vệ các tính năng cao cấp. + +### Nếu Thuộc Tính Này Không Tồn Tại? + +Các phiên bản SDK cũ hơn có thể cung cấp một phương thức như `GetLicenseInfo()` thay thế. Khi đó, bạn sẽ kiểm tra đối tượng trả về để tìm cờ `IsTrial`. Luôn tham khảo changelog của SDK khi nâng cấp. + +## Bước 5: Hiển Thị Trạng Thái Cấp Phép Hiện Tại + +Cuối cùng, hãy cho người dùng biết engine đã được cấp phép hay vẫn ở chế độ trial. Một dòng `Console.WriteLine` đơn giản đã đủ, nhưng bạn có thể tùy biến cho các ứng dụng GUI. + +```csharp +// Step 5: Output the licensing status +Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); +``` + +Toán tử ba ngôi giúp mã gọn gàng, và các thông báo đủ rõ ràng cho người dùng cuối hoặc các nhà phát triển khi đọc log. + +## Ví Dụ Hoàn Chỉnh + +Kết hợp tất cả lại, đây là một chương trình tự chứa bạn có thể sao chép‑dán vào `Program.cs` và chạy bằng `dotnet run`. + +```csharp +using System; +using MyOcrSdk; // Replace with your actual OCR SDK namespace + +namespace OcrEngineDemo +{ + class Program + { + static void Main(string[] args) + { + try + { + // Step 1: Create OCR engine instance + OcrEngine engine = new OcrEngine(); + + // Step 2: Determine whether the engine is in evaluation mode + bool isEvaluation = engine.IsEvaluation; + + // Step 3: Display the current licensing status + Console.WriteLine(isEvaluation + ? "Running in evaluation mode – limited functionality." + : "Licensed – full OCR capabilities enabled."); + + // Optional: Show how you might handle a licensed engine + if (!isEvaluation) + { + // Example: Load an image and perform OCR (pseudo‑code) + // var image = Image.Load("sample.png"); + // var result = engine.Recognize(image); + // Console.WriteLine($"OCR Result: {result.Text}"); + } + } + catch (Exception ex) + { + // Graceful error handling – useful when checking license fails + Console.Error.WriteLine($"Error initializing OCR engine: {ex.Message}"); + // In a real app, you might log the stack trace or prompt for a license key + } + } + } +} +``` + +### Kết Quả Dự Kiến + +- **Bản dùng thử:** + `Running in evaluation mode – limited functionality.` + +- **Bản có giấy phép:** + `Licensed – full OCR capabilities enabled.` + +Nếu SDK ném ra ngoại lệ (ví dụ: thiếu DLL gốc), khối `catch` sẽ in ra thông báo lỗi hữu ích thay vì làm ứng dụng bị sập. + +## Xử Lý Các Trường Hợp Cạnh và Những Cạm Bẫy Thường Gặp + +### 1. Instance Engine Null + +Mặc dù constructor thường trả về một đối tượng hợp lệ, một số SDK có thể trả về `null` nếu thiếu phụ thuộc native. Hãy bảo vệ lại: + +```csharp +if (engine == null) +{ + Console.Error.WriteLine("Failed to create OCR engine – check SDK installation."); + return; +} +``` + +### 2. Hết Hạn Giấy Phép Khi Đang Chạy + +Giấy phép dùng thử có thể hết hạn giữa chừng. Thường xuyên gọi lại `IsEvaluation` nếu ứng dụng của bạn chạy lâu. + +```csharp +// Example: Re‑check every 5 minutes in a background timer +``` + +### 3. Tên Thuộc Tính Khác Nhau Giữa Các Phiên Bản + +Các bản phát hành cũ hơn có thể có `engine.EvaluationMode` hoặc `engine.License.IsTrial`. Khi nâng cấp, hãy tìm kiếm trong notes của SDK để biết các thay đổi phá vỡ. + +### 4. Kịch Bản Đa Luồng + +Nếu bạn khởi tạo nhiều worker OCR, tạo **một OCR engine cho mỗi luồng** trừ khi SDK hỗ trợ chia sẻ an toàn đa luồng. Chia sẻ một engine duy nhất có thể gây race condition và đọc sai trạng thái cấp phép. + +## Mẹo Chuyên Gia cho Sản Xuất + +- **Lưu trữ trạng thái cấp phép** sau lần kiểm tra đầu tiên để tránh gọi thuộc tính không cần thiết. +- **Ghi log khóa giấy phép** (được mask) khi khởi động để phục vụ kiểm tra audit—giúp đội hỗ trợ chẩn đoán vấn đề cấp phép. +- **Cung cấp một công tắc UI** thông báo cho người dùng họ đang ở chế độ trial và đưa ra nút “Mua Giấy Phép”. +- **Tự động gia hạn giấy phép** bằng API kích hoạt của SDK, nếu có, để trải nghiệm người dùng liền mạch. + +## Kết Luận + +Chúng ta vừa **tạo các đối tượng OCR engine** trong vài dòng mã, kiểm tra **chế độ đánh giá của OCR engine**, và in ra một thông báo **trạng thái cấp phép OCR** rõ ràng. Ví dụ đầy đủ chạy ngay, xử lý lỗi một cách nhẹ nhàng, và giải thích “tại sao” mỗi bước—giúp bạn dễ dàng áp dụng cho desktop, web, hoặc các kịch bản phía server. + +Tiếp theo, bạn có thể khám phá: + +- Đưa ảnh vào `engine.Recognize` và xử lý hỗ trợ đa ngôn ngữ. +- Sử dụng API **kiểm tra giấy phép OCR** để kích hoạt khóa đã mua một cách lập trình. +- Tích hợp với các framework UI (WinForms, WPF, MAUI) để hiển thị biểu tượng cấp phép. + +Hãy thử những điều trên, và bạn sẽ có một nền tảng OCR vững chắc cho bất kỳ ứng dụng nào. Chúc lập trình vui vẻ! + +## Các Tutorial Liên Quan + +- [How to Extract OCR – OCR Configuration](/ocr/english/net/ocr-configuration/) +- [How to Get OCR Results with Aspose.OCR for .NET](/ocr/english/net/text-recognition/get-recognition-result/) +- [How to OCR PDF in .NET with Aspose.OCR](/ocr/english/net/text-recognition/recognize-pdf/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/ocr-optimization/_index.md b/ocr/vietnamese/net/ocr-optimization/_index.md index e65f42655..5fbf38996 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. +### [Tiền xử lý hình ảnh cho OCR – Hướng dẫn đầy đủ Aspose C#](./preprocess-image-for-ocr-complete-aspose-c-guide/) +Khám phá cách tiền xử lý hình ảnh để cải thiện độ chính xác OCR với Aspose trong C#. ## Câu hỏi thường gặp diff --git a/ocr/vietnamese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md b/ocr/vietnamese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md new file mode 100644 index 000000000..477f0ed3b --- /dev/null +++ b/ocr/vietnamese/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/_index.md @@ -0,0 +1,232 @@ +--- +category: general +date: 2026-05-25 +description: Tiền xử lý hình ảnh cho OCR bằng Aspose để cải thiện độ chính xác của + OCR và thực hiện OCR trên các tệp JPEG. Tìm hiểu cách trích xuất văn bản bằng Aspose + trong một hướng dẫn rõ ràng, từng bước. +draft: false +keywords: +- preprocess image for OCR +- improve OCR accuracy +- run OCR on JPEG +- extract text using Aspose +language: vi +og_description: Tiền xử lý hình ảnh cho OCR với Aspose để nâng cao độ chính xác của + OCR. Thực hiện theo hướng dẫn này để chạy OCR trên JPEG và trích xuất văn bản bằng + Aspose trong C#. +og_title: Tiền xử lý hình ảnh cho OCR – Hướng dẫn Aspose C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + headline: Preprocess Image for OCR – Complete Aspose C# Guide + type: TechArticle +- description: Preprocess image for OCR with Aspose to improve OCR accuracy and run + OCR on JPEG files. Learn how to extract text using Aspose in a clear, step‑by‑step + tutorial. + name: Preprocess Image for OCR – Complete Aspose C# Guide + steps: + - name: '**Deskew** – straightens tilted documents (max 5° by default).' + text: '**Deskew** – straightens tilted documents (max 5° by default).' + - name: '**Denoise** – smooths out grainy backgrounds.' + text: '**Denoise** – smooths out grainy backgrounds.' + - name: '**Binarize** – converts the image to black‑and‑white using a threshold.' + text: '**Binarize** – converts the image to black‑and‑white using a threshold.' + - name: '**ContrastBoost** – makes faint characters pop.' + text: '**ContrastBoost** – makes faint characters pop.' + type: HowTo +tags: +- OCR +- Aspose +- C# +- Image Processing +title: Tiền xử lý hình ảnh cho OCR – Hướng dẫn đầy đủ Aspose C# +url: /vi/net/ocr-optimization/preprocess-image-for-ocr-complete-aspose-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Tiền xử lý hình ảnh cho OCR – Hướng dẫn đầy đủ Aspose C# + +Bạn đã bao giờ tự hỏi làm thế nào để **tiền xử lý hình ảnh cho OCR** sao cho văn bản luôn sạch sẽ? Bạn không phải là người duy nhất—các nhà phát triển luôn phải đấu tranh với các bản scan nhiễu, JPEG độ tương phản thấp và ánh sáng không ổn định. Tin tốt là gì? Với một vài điều chỉnh thông minh, bạn có thể **cải thiện độ chính xác của OCR** một cách đáng kể, và Aspose giúp việc này trở nên dễ dàng. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ thực tế cho thấy cách **chạy OCR trên ảnh JPEG**, áp dụng một quy trình xử lý ảnh tùy chỉnh, và cuối cùng **trích xuất văn bản bằng Aspose**. Khi kết thúc, bạn sẽ có một đoạn mã C# sẵn sàng sao chép và dán vào bất kỳ dự án .NET nào. + +## Những gì bạn sẽ học + +- Tại sao tiền xử lý lại quan trọng và các bộ lọc nào mang lại lợi ích lớn nhất. +- Cách cấu hình `ImageProcessingOptions` của Aspose.OCR cho việc chỉnh nghiêng, giảm nhiễu, nhị phân hoá và tăng độ tương phản. +- Mã chính xác để **chạy OCR trên file JPEG** và lấy văn bản sạch. +- Các mẹo và lưu ý giúp quy trình OCR của bạn ổn định trong môi trường sản xuất. + +Không cần kinh nghiệm trước với Aspose; chỉ cần kiến thức cơ bản về C# và Visual Studio (hoặc IDE yêu thích). Hãy bắt đầu. + +![Ví dụ tiền xử lý hình ảnh cho OCR](preprocess-ocr.png "Tiền xử lý hình ảnh cho OCR") + +## Bước 1: Thiết lập Aspose.OCR Engine – Tiền xử lý hình ảnh cho OCR + +Đầu tiên, chúng ta cần một thể hiện `OcrEngine` và phải chỉ định ngôn ngữ mong muốn. Trong hầu hết các trường hợp, tiếng Anh là mặc định, nhưng bạn có thể thay đổi sang tiếng Pháp, tiếng Đức, v.v., bằng cách thay đổi enum `OcrLanguage`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; + +// Initialize the OCR engine – this is where we’ll later plug in our preprocessing pipeline +var ocrEngine = new OcrEngine +{ + Language = OcrLanguage.English +}; +``` + +**Tại sao điều này quan trọng:** Engine là trái tim của quá trình; nếu không có nó, bạn không thể áp dụng bất kỳ bộ lọc ảnh nào thực sự **tiền xử lý hình ảnh cho OCR**. Hãy nghĩ nó như một căn bếp nơi tất cả các nguyên liệu được trộn lẫn. + +## Bước 2: Xây dựng Quy trình Xử lý Ảnh Tùy chỉnh – Cải thiện độ chính xác OCR + +Bây giờ là phần hấp dẫn. Aspose cho phép bạn nối chuỗi nhiều bộ lọc lại với nhau. Dưới đây chúng tôi kích hoạt bốn bộ lọc hiệu quả nhất: + +1. **Deskew** – làm thẳng tài liệu bị nghiêng (mặc định tối đa 5°). +2. **Denoise** – làm mịn nền nhiễu. +3. **Binarize** – chuyển ảnh sang đen‑trắng bằng một ngưỡng. +4. **ContrastBoost** – làm nổi bật các ký tự mờ. + +```csharp +// Attach a preprocessing pipeline to the engine +ocrEngine.ImageProcessingOptions = new ImageProcessingOptions +{ + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } +}; +``` + +**Mẹo chuyên nghiệp:** Nếu ảnh nguồn của bạn đã đủ sắc nét, bạn có thể giảm `Strength` hoặc tắt hoàn toàn một bộ lọc. Xử lý quá mức đôi khi có thể xóa bỏ các ký tự mờ, vì vậy hãy thử nghiệm với các mẫu thực tế. + +## Bước 3: Tải JPEG (hoặc bất kỳ ảnh nào) và chạy OCR – Chạy OCR trên JPEG + +Aspose hỗ trợ mọi định dạng ảnh mà .NET có thể đọc—JPEG, PNG, BMP, bất kỳ gì. Dưới đây là cách đưa một file JPEG vào engine và khởi động quá trình nhận dạng. + +```csharp +// Load the source image (replace the path with your actual file) +string imagePath = @"C:\Images\noisy_form.jpg"; +var sourceImage = Image.FromFile(imagePath); + +// Perform OCR – the heavy lifting happens after our preprocessing pipeline runs +string extractedText = ocrEngine.Recognize(sourceImage); +``` + +**Tại sao lại là JPEG?** Nén JPEG thường tạo ra các artefact gây rối cho OCR. Quy trình tiền xử lý của chúng tôi, đặc biệt là các bước giảm nhiễu và nhị phân hoá, giảm thiểu những vấn đề này, cho phép bạn **chạy OCR trên JPEG** một cách tự tin. + +## Bước 4: Xuất Văn bản Đã Nhận dạng – Trích xuất Văn bản bằng Aspose + +Cuối cùng, chúng ta chỉ cần ghi văn bản ra console, file, hoặc bất kỳ dịch vụ downstream nào. Đối với mục đích minh họa, console là đủ. + +```csharp +// Show the result – you can also write to a file or database +Console.WriteLine("=== Extracted Text ==="); +Console.WriteLine(extractedText); +``` + +Khi bạn chạy chương trình, bạn sẽ thấy kết quả giống như: + +``` +=== Extracted Text === +John Doe +Invoice #12345 +Total: $1,250.00 +... +``` + +Nếu đầu ra bị rối, quay lại **Bước 2** và điều chỉnh các thiết lập bộ lọc. Những thay đổi nhỏ thường mang lại cải thiện lớn trong **cải thiện độ chính xác OCR**. + +## Các Trường hợp Cạnh và Cách Xử lý + +| Tình huống | Điều chỉnh đề xuất | +|-----------|----------------------| +| **Ảnh rất tối** | Tăng `ContrastBoost.Level` lên 1.5 hoặc cao hơn. | +| **Nghiêng > 5°** | Tăng `DeskewOptions.MaxAngle` (ví dụ, 10.0) hoặc xoay ảnh thủ công trước. | +| **Văn bản màu trên nền màu** | Sử dụng `BinarizeOptions` với ngưỡng tùy chỉnh hoặc chuyển sang `AdaptiveBinarizeOptions`. | +| **File lớn ( > 5 MB )** | Đầu tiên tải ảnh vào `MemoryStream` để tránh vấn đề khóa file. | + +Những điều chỉnh này giúp quy trình của bạn linh hoạt và chuẩn bị cho tương lai, đặc biệt khi bạn cần **trích xuất văn bản bằng Aspose** từ nhiều nguồn khác nhau. + +## Ví dụ Hoàn chỉnh – Tất cả các Bước trong Một File + +Dưới đây là chương trình hoàn chỉnh, sẵn sàng sao chép‑dán. Nó biên dịch với .NET 6+ và chỉ yêu cầu gói NuGet `Aspose.OCR`. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Filters; +using System; +using System.Drawing; // For Image + +class Program +{ + static void Main() + { + // 1️⃣ Initialize OCR engine + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English, + ImageProcessingOptions = new ImageProcessingOptions + { + // 2️⃣ Preprocess image for OCR + Deskew = new DeskewOptions { Enabled = true, MaxAngle = 5.0 }, + Denoise = new DenoiseOptions { Enabled = true, Strength = 0.7 }, + Binarize = new BinarizeOptions { Enabled = true, Threshold = 120 }, + ContrastBoost = new ContrastBoostOptions { Enabled = true, Level = 1.3 } + } + }; + + // 3️⃣ Load JPEG and run OCR + string path = @"YOUR_DIRECTORY/noisy_form.jpg"; // ← change this + using var img = Image.FromFile(path); + string text = ocrEngine.Recognize(img); + + // 4️⃣ Output – extract text using Aspose + Console.WriteLine("=== Extracted Text ==="); + Console.WriteLine(text); + } +} +``` + +Lưu file này dưới tên `Program.cs`, thêm gói Aspose.OCR (`dotnet add package Aspose.OCR`), và chạy `dotnet run`. Bạn sẽ thấy văn bản đã được làm sạch được in ra console. + +## Tóm tắt – Tại sao Cách Tiếp Cận Này Hiệu Quả + +- **Tiền xử lý hình ảnh cho OCR**: Quy trình loại bỏ các nguồn lỗi phổ biến nhất (nghiêng, nhiễu, độ tương phản thấp). +- **Cải thiện độ chính xác OCR**: Mỗi bộ lọc được tinh chỉnh để tăng tỉ lệ tín hiệu‑nhiễu mà engine nhận được. +- **Chạy OCR trên JPEG**: Ngay cả các ảnh đã nén cũng trở nên dễ đọc sau khi chỉnh nghiêng và nhị phân hoá. +- **Trích xuất văn bản bằng Aspose**: Phương thức `Recognize` trả về một chuỗi thuần, sẵn sàng cho bất kỳ logic downstream nào. + +Kết hợp các bước này, bạn sẽ có một giải pháp OCR đáng tin cậy, chuẩn sản xuất chỉ trong vài dòng mã. + +## Các Bước Tiếp Theo và Chủ Đề Liên Quan + +- **Xử lý hàng loạt** – Lặp qua một thư mục ảnh và ghi mỗi kết quả vào file `.txt`. +- **Gói ngôn ngữ** – Thay `OcrLanguage.English` bằng `OcrLanguage.Spanish` hoặc thêm từ điển tùy chỉnh. +- **Trích xuất PDF** – Kết hợp Aspose.OCR với Aspose.PDF để lấy văn bản trực tiếp từ PDF đã scan. +- **Tối ưu hiệu năng** – Chạy engine song song bằng `Parallel.ForEach` cho khối lượng công việc lớn. + +Hãy tự do thử nghiệm các giá trị bộ lọc, thử các định dạng ảnh khác, hoặc nối thêm các bộ lọc Aspose như `SharpnessOptions`. Khi đã nắm vững nền tảng, khả năng của bạn sẽ không có giới hạn. + +--- + +*Chúc lập trình vui! Nếu gặp khó khăn, hãy để lại bình luận bên dưới và chúng tôi sẽ cùng bạn khắc phục.* + + +## Các Hướng Dẫn Liên Quan + +- [Tiền xử lý Image OCR với Aspose.OCR Filters cho .NET](/ocr/english/net/ocr-optimization/preprocessing-filters-for-image/) +- [Trích xuất Văn bản từ Image – Tối ưu OCR với Aspose.OCR cho .NET](/ocr/english/net/ocr-optimization/) +- [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/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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..74a9f130a 100644 --- a/ocr/vietnamese/net/text-recognition/_index.md +++ b/ocr/vietnamese/net/text-recognition/_index.md @@ -55,9 +55,24 @@ Nâng cao các ứng dụng .NET của bạn với Aspose.OCR để nhận dạn 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. ### [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. +### [Nhận dạng văn bản từ hình ảnh với Aspose OCR – Hướng dẫn C# đầy đủ](./recognize-text-from-image-with-aspose-ocr-complete-c-guide/) +Hướng dẫn chi tiết từng bước để nhận dạng văn bản từ hình ảnh bằng Aspose OCR trong C#, bao gồm cài đặt và ví dụ thực tế. +### [Trích xuất văn bản từ hình ảnh trong C# – Hướng dẫn đầy đủ Aspose OCR](./extract-text-from-image-in-c-complete-aspose-ocr-guide/) +Hướng dẫn chi tiết từng bước để trích xuất văn bản từ hình ảnh bằng Aspose OCR trong C#, bao gồm cài đặt và ví dụ thực tế. +### [Cách sử dụng OCR trong C# – Nhận dạng văn bản tiếng Trung từ JPG](./how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/) +Hướng dẫn chi tiết cách dùng Aspose.OCR trong C# để nhận dạng văn bản tiếng Trung từ hình ảnh JPG một cách chính xác. +### [OCR Văn bản tiếng Nga trong C# – Hướng dẫn đầy đủ sử dụng Aspose OCR](./ocr-russian-text-in-c-complete-guide-using-aspose-ocr/) +Hướng dẫn chi tiết từng bước để nhận dạng văn bản tiếng Nga từ hình ảnh bằng Aspose OCR trong C#, bao gồm cài đặt và ví dụ thực tế. +### [Trích xuất văn bản từ hình ảnh trong ASP.NET Core Minimal API – Hướng dẫn đầy đủ](./extract-text-from-image-in-asp-net-core-minimal-api-complete/) +Hướng dẫn chi tiết từng bước để trích xuất văn bản từ hình ảnh bằng ASP.NET Core Minimal API, bao gồm cài đặt và ví dụ thực tế. +### [Hướng dẫn OCR C#: Trích xuất văn bản từ biên lai PNG với Aspose](./c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/) +Hướng dẫn chi tiết từng bước để trích xuất văn bản từ biên lai PNG bằng Aspose OCR trong C#, bao gồm cài đặt và ví dụ thực tế. +### [Chuyển đổi TIFF sang Văn bản trong C# – Hướng dẫn OCR hàng loạt đầy đủ](./convert-tiff-to-text-in-c-complete-batch-ocr-guide/) +Hướng dẫn chi tiết cách chuyển đổi tệp TIFF thành văn bản bằng Aspose.OCR trong C#, hỗ trợ xử lý hàng loạt 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/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md b/ocr/vietnamese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md new file mode 100644 index 000000000..da2112459 --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/_index.md @@ -0,0 +1,220 @@ +--- +category: general +date: 2026-05-25 +description: Hướng dẫn OCR bằng C# cho thấy cách tải tệp hình ảnh trong C# và nhận + dạng văn bản PNG từ biên lai bằng Aspose OCR – hướng dẫn từng bước. +draft: false +keywords: +- c# OCR tutorial +- load image file c# +- recognize png text +- read receipt OCR +- perform OCR image +language: vi +og_description: Hướng dẫn OCR C# đưa bạn qua quá trình tải tệp hình ảnh C# và nhận + dạng văn bản PNG từ biên lai bằng Aspose OCR. +og_title: Hướng dẫn OCR C# – Trích xuất văn bản từ biên lai PNG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + headline: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + type: TechArticle +- description: c# OCR tutorial that shows how to load image file c# and recognize + png text from a receipt using Aspose OCR – step‑by‑step guide. + name: 'c# OCR tutorial: Extract Text from PNG Receipts with Aspose' + steps: + - name: Why Aspose? + text: Aspose OCR supports over 30 languages, works offline, and returns a rich + `OcrResult` object—perfect for **perform OCR image** tasks where you need more + than just plain text. + - name: Handling Common Edge Cases + text: '| Situation | What to do | |-----------|------------| | **Image is blurry** + | Pre‑process with `System.Drawing` to sharpen or increase DPI. | | **Receipt + contains multiple languages** | Set `ocrEngine.Language = OcrLanguage.English + | OcrLanguage.Spanish;` | | **Large batch processing** | Reuse a sin' + - name: What’s Next? + text: '- Experiment with **load image file c#** using `SkiaSharp` for true cross‑platform + support. - Dive deeper into `OcrResult.Words` to extract line items, prices, + and dates—perfect for expense‑tracking apps. - Combine this tutorial with Azure + Functions or AWS Lambda to build a serverless receipt‑proces' + type: HowTo +tags: +- OCR +- C# +- Aspose +title: 'Hướng dẫn OCR bằng C#: Trích xuất văn bản từ hoá đơn PNG bằng Aspose' +url: /vi/net/text-recognition/c-ocr-tutorial-extract-text-from-png-receipts-with-aspose/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Hướng dẫn OCR c# – Trích xuất văn bản từ biên lai PNG với Aspose + +Bạn đã bao giờ cần một **c# OCR tutorial** thực sự hoàn thành công việc mà không phải tìm kiếm vô tận trên Google chưa? Bạn đang ở đúng nơi. Trong hướng dẫn này, chúng tôi sẽ **load image file c#**, **recognize png text**, và **read receipt OCR** kết quả, đồng thời chỉ cho bạn cách **perform OCR image** xử lý với Aspose OCR. + +Chúng tôi sẽ bắt đầu bằng cách cài đặt gói NuGet cần thiết, đi qua từng dòng mã, và kết thúc với một bản JSON gọn gàng mà bạn có thể truyền thẳng vào pipeline dữ liệu tiếp theo. Không có phần thừa, chỉ có giải pháp thực tế, sẵn sàng chạy. + +## Những gì bạn sẽ học + +- Cách thiết lập Aspose OCR trong dự án .NET 6 (hoặc mới hơn). +- Các bước chính xác để **load an image file c#** và chuyển nó cho engine. +- Cách **recognize png text** từ hình ảnh biên lai và nắm bắt kết quả. +- Các cách **read receipt OCR** đầu ra dưới dạng JSON được định dạng đẹp mắt. +- Mẹo cho các thao tác **perform OCR image** trên các loại tệp khác nhau và xử lý các vấn đề thường gặp. + +**Yêu cầu trước** +- Visual Studio 2022 (hoặc bất kỳ IDE nào bạn thích). +- .NET 6 SDK hoặc mới hơn. +- Một hình ảnh biên lai PNG sẵn có (chúng tôi sẽ gọi nó là `receipt.png`). + +Nếu bạn đã có những thứ này, hãy bắt đầu. + +![ảnh chụp màn hình hướng dẫn OCR c#](ocr-demo.png "kết quả hướng dẫn OCR c# hiển thị đầu ra JSON") + +## Hướng dẫn OCR c# – Cài đặt Aspose OCR Engine + +Trước hết, chúng ta cần thư viện Aspose OCR. Mở terminal trong thư mục solution và chạy: + +```bash +dotnet add package Aspose.OCR +``` + +Lệnh duy nhất này sẽ tải về mọi thứ cần thiết, bao gồm các binary gốc để giải mã hình ảnh. Sau khi cài đặt, tạo một dự án console mới hoặc thêm mã vào dự án hiện có. + +### Tại sao lại chọn Aspose? + +Aspose OCR hỗ trợ hơn 30 ngôn ngữ, hoạt động offline, và trả về một đối tượng `OcrResult` phong phú—hoàn hảo cho các nhiệm vụ **perform OCR image** khi bạn cần nhiều hơn chỉ văn bản thuần. + +## Tải tệp hình ảnh c# và chuẩn bị biên lai + +Bây giờ thư viện đã sẵn sàng, hãy **load image file c#**. Lớp `System.Drawing.Image` thực hiện phần lớn công việc, nhưng bạn cũng có thể dùng `SkiaSharp` nếu muốn một giải pháp đa nền tảng. + +```csharp +using System; +using System.Drawing; // For Image loading +using Aspose.OCR; // OCR engine +using System.Text.Json; // JSON serialization + +// Step 1: Create and configure the OCR engine +var ocrEngine = new OcrEngine +{ + // English works for most receipts; change as needed + Language = OcrLanguage.English +}; + +// Step 2: Load the image to be processed +// Replace the path with the actual location of your receipt PNG +string imagePath = @"C:\Receipts\receipt.png"; +if (!File.Exists(imagePath)) +{ + Console.WriteLine($"File not found: {imagePath}"); + return; +} +using Image receiptImage = Image.FromFile(imagePath); +``` + +> **Mẹo chuyên nghiệp:** Đặt `Image` trong một câu lệnh `using` (như đã minh họa) để giải phóng tài nguyên gốc kịp thời—đặc biệt quan trọng khi bạn **perform OCR image** trên nhiều tệp trong một vòng lặp. + +## Nhận dạng văn bản PNG với Aspose + +Với hình ảnh trong bộ nhớ, engine bây giờ có thể **recognize png text**. Aspose trả về một `OcrResult` chứa cả chuỗi thô và dữ liệu chi tiết về mỗi từ đã nhận dạng. + +```csharp +// Step 3: Perform OCR and obtain the result object +OcrResult ocrResult = ocrEngine.RecognizeWithResult(receiptImage); + +// Quick sanity check – was anything recognized? +if (string.IsNullOrWhiteSpace(ocrResult.Text)) +{ + Console.WriteLine("No text detected. Verify image quality or language settings."); + return; +} +``` + +Tại sao gọi `RecognizeWithResult` thay vì `Recognize` đơn giản hơn? Phiên bản trước cung cấp cho bạn quyền truy cập vào điểm tin cậy, hộp bao và ngắt dòng—rất hữu ích nếu sau này bạn cần **read receipt OCR** để trích xuất các mục dòng. + +## Đọc kết quả OCR biên lai dưới dạng JSON + +Hầu hết các hệ thống downstream yêu thích JSON, vì vậy hãy serialize `OcrResult`. Bộ serializer `System.Text.Json` xử lý các đối tượng phức tạp một cách nhẹ nhàng, và chúng ta sẽ bật thụt lề để dễ đọc. + +```csharp +// Step 4: Convert the OCR result to a readable JSON string (indented) +string jsonResult = JsonSerializer.Serialize( + ocrResult, + new JsonSerializerOptions { WriteIndented = true } +); +``` + +JSON kết quả trông giống như sau (được rút gọn để ngắn gọn): + +```json +{ + "Text": "Walmart\n123 Main St\nTotal $12.34", + "Words": [ + { + "Text": "Walmart", + "Confidence": 0.98, + "Rectangle": { "X": 10, "Y": 20, "Width": 150, "Height": 30 } + }, + { + "Text": "Total", + "Confidence": 0.95, + "Rectangle": { "X": 10, "Y": 150, "Width": 80, "Height": 25 } + } + ] +} +``` + +Bây giờ bạn có thể truyền `jsonResult` vào cơ sở dữ liệu, hàng đợi tin nhắn, hoặc chỉ đơn giản là ghi log để gỡ lỗi. + +## Thực hiện xử lý OCR Image và hiển thị đầu ra + +Cuối cùng, xuất JSON ra console. Trong một ứng dụng thực tế, bạn có thể ghi nó vào tệp hoặc gửi qua HTTP, nhưng console giúp dễ dàng kiểm tra mọi thứ đã hoạt động. + +```csharp +// Step 5: Output the JSON to the console +Console.WriteLine("=== OCR Result (JSON) ==="); +Console.WriteLine(jsonResult); +``` + +Chạy chương trình (`dotnet run`) và bạn sẽ thấy JSON được định dạng đẹp mắt được in ra. Nếu hình ảnh biên lai rõ ràng, văn bản sẽ chính xác; nếu không, hãy cân nhắc tăng độ phân giải hình ảnh hoặc áp dụng bộ lọc tiền xử lý (ví dụ: grayscale, tăng độ tương phản) trước khi đưa vào engine. + +### Xử lý các trường hợp góc cạnh thường gặp + +| Situation | What to do | +|-----------|------------| +| **Hình ảnh bị mờ** | Tiền xử lý bằng `System.Drawing` để làm nét hoặc tăng DPI. | +| **Biên lai chứa nhiều ngôn ngữ** | Đặt `ocrEngine.Language = OcrLanguage.English | OcrLanguage.Spanish;` | +| **Xử lý hàng loạt lớn** | Tái sử dụng một thể hiện `OcrEngine` duy nhất; chỉ thay đổi `Image` ở mỗi vòng lặp. | +| **Áp lực bộ nhớ** | Giải phóng các đối tượng `Image` kịp thời và cân nhắc `await Task.Run` cho các pipeline bất đồng bộ. | + +Những điều chỉnh này giữ cho quy trình **perform OCR image** của bạn mạnh mẽ ngay cả khi đầu vào không hoàn hảo. + +## Tổng kết + +Chúc mừng—bạn vừa hoàn thành một **c# OCR tutorial** tải một hình ảnh, **recognizes png text**, và **reads receipt OCR** đầu ra dưới dạng JSON sạch sẽ. Các bước cốt lõi (cài đặt engine, tải hình ảnh, thực thi OCR, serialize, và hiển thị) tạo nên nền tảng vững chắc mà bạn có thể mở rộng cho hoá đơn, hộ chiếu, hoặc bất kỳ tài liệu quét nào khác. + +### Tiếp theo là gì? + +- Thử nghiệm **load image file c#** bằng `SkiaSharp` để hỗ trợ đa nền tảng thực sự. +- Đi sâu hơn vào `OcrResult.Words` để trích xuất các mục dòng, giá và ngày—hoàn hảo cho các ứng dụng theo dõi chi phí. +- Kết hợp hướng dẫn này với Azure Functions hoặc AWS Lambda để xây dựng API xử lý biên lai không máy chủ. + +Bạn có thể thoải mái chỉnh sửa mã, thêm nhiều hình ảnh hơn, hoặc thậm chí chuyển sang một gói ngôn ngữ khác. Thế giới OCR đầy bất ngờ, và giờ bạn đã có công cụ để khám phá chúng. + +Chúc lập trình vui vẻ, và hy vọng biên lai của bạn luôn dễ đọc! + +## Các hướng dẫn liên quan + +- [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/) +- [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/) +- [Cách sử dụng OCR - Nhận dạng hình ảnh mà không cần phát hiện vùng văn bản](/ocr/english/net/image-and-drawing-recognition/recognize-image-without-text-area-detection/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md b/ocr/vietnamese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md new file mode 100644 index 000000000..d8d96c7e7 --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/_index.md @@ -0,0 +1,205 @@ +--- +category: general +date: 2026-05-25 +description: Chuyển đổi TIFF sang văn bản bằng Aspose.OCR trong C#. Tìm hiểu cách + chuyển đổi hàng loạt hình ảnh sang văn bản và trích xuất văn bản từ các tệp TIFF + một cách hiệu quả. +draft: false +keywords: +- convert tiff to text +- extract text from tiff +- batch image to text conversion +- convert scanned images txt +language: vi +og_description: Chuyển đổi TIFF sang văn bản với Aspose.OCR. Hướng dẫn này trình bày + cách chuyển đổi hàng loạt hình ảnh sang văn bản và cách trích xuất văn bản từ các + tệp TIFF chỉ trong vài dòng C#. +og_title: Chuyển đổi TIFF sang Văn bản trong C# – Hướng dẫn OCR Batch toàn diện +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + headline: Convert TIFF to Text in C# – Complete Batch OCR Guide + type: TechArticle +- description: Convert TIFF to text using Aspose.OCR in C#. Learn batch image to text + conversion and extract text from TIFF files efficiently. + name: Convert TIFF to Text in C# – Complete Batch OCR Guide + steps: + - name: '**Create** an OCR engine set for English.' + text: '**Create** an OCR engine set for English.' + - name: '**Collect** every TIFF file from the target folder.' + text: '**Collect** every TIFF file from the target folder.' + - name: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + text: '**Run** `BatchOcr.RecognizeAll` with four threads, turning each image into + a string.' + - name: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + text: '**Loop** over the results, swapping the `.tif` extension for `.txt` and + writing the string to disk.' + type: HowTo +tags: +- C# +- OCR +- Aspose +- TIFF +title: Chuyển đổi TIFF sang Văn bản trong C# – Hướng dẫn OCR Batch toàn diện +url: /vi/net/text-recognition/convert-tiff-to-text-in-c-complete-batch-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Chuyển đổi TIFF sang Văn bản trong C# – Hướng dẫn OCR Batch hoàn chỉnh + +Bạn đã bao giờ cần **chuyển đổi TIFF sang văn bản** nhưng không biết bắt đầu từ đâu? Bạn không cô độc—nhiều nhà phát triển gặp khó khăn với OCR batch khi làm việc với tài liệu đã quét. Trong tutorial này, chúng ta sẽ thực hành một giải pháp **trích xuất văn bản từ các tệp TIFF** bằng Aspose.OCR, và thực hiện song song để các thư mục lớn hoàn thành trong vài giây. + +Chúng ta cũng sẽ đề cập đến các **thực hành tốt nhất cho chuyển đổi ảnh sang văn bản batch**, vì vậy vào cuối bạn sẽ có một đoạn mã có thể tái sử dụng để biến toàn bộ thư mục ảnh quét thành các tệp *.txt* gọn gàng—hoàn hảo cho việc lập chỉ mục, tìm kiếm, hoặc đưa vào các phân tích downstream. + +## Những gì bạn cần + +- **.NET 6.0** trở lên (mã cũng biên dịch trên .NET Framework) +- Gói NuGet **Aspose.OCR for .NET** (`Install-Package Aspose.OCR`) +- Một thư mục chứa một hoặc nhiều tệp *.tif* (định dạng quét TIFF cổ điển) +- IDE yêu thích của bạn (Visual Studio, VS Code, Rider—bất kỳ gì bạn thích) + +Đó là tất cả. Không có dịch vụ bên ngoài, không có khóa API, chỉ cần C# thuần và Aspose. + +![Ảnh chụp màn hình của một tệp TIFF đang được xử lý và tệp văn bản kết quả](/images/ocr-result.png "Kết quả OCR hiển thị đầu ra chuyển đổi TIFF sang văn bản") + +*(Văn bản thay thế: Ảnh chụp màn hình hiển thị đầu ra chuyển đổi TIFF sang văn bản trên màn hình)* + +## Bước 1: Thiết lập Engine OCR – Chuyển đổi TIFF sang Văn bản + +Đầu tiên, chúng ta cần một thể hiện `OcrEngine` biết rằng nó sẽ đọc các ký tự tiếng Anh. Engine là trái tim của quá trình chuyển đổi; cấu hình đúng sẽ đảm bảo kết quả ổn định. + +```csharp +using Aspose.OCR; +using System.IO; +using System.Collections.Generic; + +class Program +{ + static void Main() + { + // Create an OCR engine configured for English – this is the core of convert TIFF to text + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.English + }; +``` + +*Tại sao điều này quan trọng:* +Aspose.OCR hỗ trợ hàng chục ngôn ngữ. Nếu bạn đang xử lý các bản quét đa ngôn ngữ, chỉ cần thay `OcrLanguage.English` bằng giá trị enum phù hợp. Để ngôn ngữ không xác định sẽ buộc engine vào chế độ tự động phát hiện, có thể chậm hơn và kém chính xác. + +## Bước 2: Thu thập Tất cả các Tệp TIFF – Trích xuất Văn bản từ TIFF Một cách Hiệu quả + +Tiếp theo chúng ta lấy mọi tệp *.tif* từ thư mục bạn chỉ định. Sử dụng `Directory.GetFiles` cho chúng ta một mảng sạch sẽ để đưa vào bộ xử lý batch. + +```csharp + // Locate every TIFF in the input folder – adjust the path to your own directory + string inputFolder = @"C:\Scans\Batch"; + string[] tiffFiles = Directory.GetFiles(inputFolder, "*.tif", SearchOption.TopDirectoryOnly); + + if (tiffFiles.Length == 0) + { + System.Console.WriteLine("No TIFF files found. Check the folder path."); + return; + } +``` + +*Mẹo chuyên nghiệp:* Cờ `SearchOption.AllDirectories` có thể được dùng nếu các bản quét của bạn nằm trong các thư mục con. Chỉ cần nhớ rằng đệ quy sâu hơn có thể tăng mức sử dụng bộ nhớ trong bước batch. + +## Bước 3: Thực hiện OCR Song Song – Chuyển Đổi Ảnh Sang Văn Bản Batch + +Bây giờ là phần thú vị. Aspose.OCR cung cấp một helper tĩnh `BatchOcr.RecognizeAll` nhận một mảng đường dẫn tệp, một engine, và một gợi ý `parallelism`. Chúng ta sẽ khởi tạo bốn luồng, trên một laptop quad‑core hiện đại sẽ mang lại tốc độ gần như tuyến tính. + +```csharp + // Run OCR on all files in parallel (4 threads by default) + // The result is a dictionary where Key = file path, Value = extracted text + Dictionary ocrResults = BatchOcr.RecognizeAll(tiffFiles, ocrEngine, parallelism: 4); +``` + +*Tại sao cần song song?* +Quét một batch các TIFF độ phân giải cao có thể tốn nhiều CPU. Bằng cách phân chia công việc qua nhiều luồng, chúng ta giữ cho tất cả các lõi bận rộn, giảm đáng kể thời gian chạy tổng thể. Nếu bạn chạy trên server có nhiều lõi hơn, hãy tăng giá trị `parallelism` cho phù hợp. + +## Bước 4: Ghi Kết Quả – Chuyển Đổi Ảnh Quét thành Tệp TXT + +Cuối cùng chúng ta duyệt qua dictionary và ghi mỗi đoạn văn bản vào một tệp *.txt* có cùng tên cơ sở với tệp gốc. Đây là khoảnh khắc **convert scanned images txt** trở thành hiện thực. + +```csharp + // Save each recognized text to a .txt file with the same base name as the source TIFF + foreach (var kvp in ocrResults) + { + string sourcePath = kvp.Key; + string extractedText = kvp.Value; + + // Change extension from .tif to .txt + string txtPath = Path.ChangeExtension(sourcePath, ".txt"); + + // Write the text – UTF‑8 ensures all characters are preserved + File.WriteAllText(txtPath, extractedText); + System.Console.WriteLine($"Saved: {txtPath}"); + } + + System.Console.WriteLine("Batch conversion complete!"); + } +} +``` + +### Giải thích mã bằng tiếng Việt đơn giản + +1. **Tạo** một engine OCR được cài đặt cho tiếng Anh. +2. **Thu thập** mọi tệp TIFF từ thư mục mục tiêu. +3. **Chạy** `BatchOcr.RecognizeAll` với bốn luồng, chuyển mỗi ảnh thành một chuỗi. +4. **Lặp** qua các kết quả, thay đổi phần mở rộng `.tif` thành `.txt` và ghi chuỗi ra đĩa. + +Đó là toàn bộ quy trình **convert TIFF to text** trong chưa tới 50 dòng mã. + +## Xử lý Các Trường Hợp Ngoại Lệ – Khi Mọi Thứ Không Trơn Tru + +- **TIFF bị thiếu hoặc hỏng** – `BatchOcr` sẽ ném ra `OcrException`. Bao quanh lời gọi bằng `try / catch` nếu bạn cần giảm nhẹ lỗi một cách duyên dáng. +- **Tài liệu không phải tiếng Anh** – thay `OcrLanguage.English` bằng `OcrLanguage.Spanish`, `OcrLanguage.French`, v.v., hoặc dùng `OcrLanguage.AutoDetect`. +- **Ảnh rất lớn** – cân nhắc giảm DPI trước khi OCR (`ocrEngine.ImagePreprocessing.Dpi = 200`) để tiết kiệm bộ nhớ, dù có thể mất một chút độ chính xác. +- **Mã hoá đầu ra** – nếu bạn cần một trang mã cụ thể (ví dụ Windows‑1252), truyền nó vào `File.WriteAllText(txtPath, extractedText, Encoding.GetEncoding(1252))`. + +## Mẹo Chuyên Nghiệp cho Việc Chuyển Đổi Batch Ổn Định + +- **Ghi lại lỗi**: tạo một `List failedFiles` và thêm bất kỳ tệp nào gây lỗi; ghi danh sách này vào log sau vòng lặp. +- **Tái sử dụng engine**: cùng một thể hiện `OcrEngine` có thể được dùng lại cho nhiều tệp; đừng khởi tạo bên trong vòng lặp. +- **Xác thực kết quả**: một kiểm tra nhanh `if (string.IsNullOrWhiteSpace(extractedText))` có thể đánh dấu các bản quét trống hoặc không đọc được. +- **Kết hợp với PDF**: nếu nguồn của bạn là PDF đa trang, hãy chuyển mỗi trang sang TIFF trước (Aspose.PDF làm việc này) rồi chạy batch này. + +## Các Bước Tiếp Theo – Vượt Qua Chuyển Đổi Đơn Giản + +Bây giờ bạn đã có thể **extract text from TIFF** hàng loạt, bạn có thể muốn: + +- Đưa các tệp *.txt* vào một chỉ mục tìm kiếm (Elasticsearch, Azure Cognitive Search). +- Chạy phát hiện ngôn ngữ trên mỗi kết quả để định hướng tài liệu tới các pipeline theo vùng. +- Tạo PDF có thể tìm kiếm bằng cách chồng văn bản OCR lên lại ảnh gốc (lại dùng Aspose.PDF). + +Tất cả các kịch bản này dựa trên cùng một ý tưởng cốt lõi: **batch image to text conversion** là khối xây dựng cho các hệ thống xử lý tài liệu lớn hơn. + +--- + +### Kết luận + +Bạn vừa học cách **convert TIFF to text** bằng Aspose.OCR, xử lý toàn bộ thư mục một cách song song, và lưu mỗi kết quả dưới dạng tệp *.txt* sạch sẽ. Giải pháp nhẹ, hoàn toàn có thể cấu hình và sẵn sàng cho môi trường production—dù bạn đang số hoá hoá đơn cũ, lưu trữ hợp đồng đã quét, hay cung cấp dữ liệu cho một công cụ tìm kiếm văn bản. + +Hãy thử nghiệm, điều chỉnh mức song song, và bắt đầu đưa những tệp văn bản mới tạo này vào bất kỳ quy trình nào bạn cần. Chúc bạn OCR vui vẻ! + +--- + + +## Các Tutorial Liên Quan + +- [Extract Text from Images Using OCR Operation on Folders](/ocr/english/net/ocr-configuration/ocr-operation-with-folder/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [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/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md b/ocr/vietnamese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md new file mode 100644 index 000000000..130f38f5a --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/_index.md @@ -0,0 +1,305 @@ +--- +category: general +date: 2026-05-25 +description: Tìm hiểu cách trích xuất văn bản từ hình ảnh bằng một API ASP.NET Core + tối thiểu. Tải lên hình ảnh qua POST, đọc dữ liệu multipart form và thực hiện OCR + trên hình ảnh. +draft: false +keywords: +- extract text from image +- upload image via post +- read multipart form data +- how to recognize text from image +- perform OCR on image +language: vi +og_description: Trích xuất văn bản từ hình ảnh bằng API ASP.NET Core tối giản. Hướng + dẫn này cho thấy cách tải lên hình ảnh qua POST, đọc dữ liệu multipart form, và + thực hiện OCR trên hình ảnh. +og_title: Trích xuất văn bản từ hình ảnh trong ASP.NET Core – Từng bước +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + headline: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + type: TechArticle +- description: Learn how to extract text from image with a minimal ASP.NET Core API. + Upload image via POST, read multipart form data and perform OCR on image. + name: Extract Text from Image in ASP.NET Core Minimal API – Complete Guide + steps: + - name: Breaking Down the Logic + text: '| Step | What Happens | Why It Matters | |------|--------------|----------------| + | **ReadFormAsync** | Parses the incoming *multipart/form-data* request. | Without + this, you can’t access the uploaded files. | | **form.Files["image"]** | Retrieves + the file whose form‑field name is `image`. | Guarant' + - name: 1. Large Files + text: 'The default request body limit is 30 MB. For larger scans you might need + to adjust:' + - name: 2. Asynchronous OCR + text: Some OCR libraries expose async methods (`RecognizeAsync`). If yours does, + replace `ocr.Recognize(img)` with `await ocr.RecognizeAsync(img)` and mark the + lambda as `async`. + - name: 3. Security Considerations + text: '- **Validate file size** before loading it into memory. - **Sanitize the + filename** if you ever write it to disk. - **Rate‑limit** the endpoint to avoid + denial‑of‑service attacks.' + - name: 4. GPU Acceleration + text: If you uncomment the `engine.GpuDevice = new GpuDevice(0);` line and your + hardware supports CUDA or DirectML, you’ll see a noticeable speed boost, especially + on high‑resolution images. + type: HowTo +tags: +- ASP.NET Core +- OCR +- Minimal API +title: Trích xuất văn bản từ hình ảnh trong ASP.NET Core Minimal API – Hướng dẫn đầy + đủ +url: /vi/net/text-recognition/extract-text-from-image-in-asp-net-core-minimal-api-complete/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Trích xuất Văn bản từ Hình ảnh trong ASP.NET Core Minimal API – Hướng dẫn đầy đủ + +Bạn đã bao giờ tự hỏi làm thế nào để **trích xuất văn bản từ hình ảnh** mà không phải đấu tranh với các framework nặng? Bạn không phải là người duy nhất. Nhiều nhà phát triển cần một cách nhanh chóng để cho phép người dùng tải lên một bức ảnh và nhận lại các ký tự thô, cho dù đó là quét biên lai, số hoá ghi chú viết tay, hay cung cấp dữ liệu cho chỉ mục tìm kiếm. + +Trong hướng dẫn này, chúng ta sẽ tạo một ASP.NET Core Minimal API nhỏ gọn cho phép **tải lên hình ảnh qua POST**, phân tích payload *multipart/form‑data*, và sau đó **thực hiện OCR trên hình ảnh** bằng một singleton `OcrEngine`. Khi hoàn thành, bạn sẽ có một ứng dụng có thể chạy đầy đủ mà bạn có thể đưa vào bất kỳ dự án .NET 8 nào và bắt đầu trích xuất văn bản từ hình ảnh ngay lập tức. + +## Những gì bạn sẽ xây dựng + +- Một ứng dụng web tối thiểu lắng nghe tại `/ocr`. +- Một endpoint chấp nhận tệp hình ảnh được gửi bằng yêu cầu POST `multipart/form-data`. +- Logic đọc tệp đã tải lên, đưa nó vào OCR engine và trả về kết quả dạng văn bản thuần. +- Đoạn mã tăng tốc GPU (được chú thích) cho những người có card tương thích. + +**Prerequisites** +- .NET 8 SDK (hoặc phiên bản mới hơn). +- Kiến thức cơ bản về C# và dòng lệnh. +- Thư viện OCR cung cấp lớp `OcrEngine` (ví dụ giả định một gói NuGet). + +Nếu bạn đã có những điều trên, hãy bắt đầu. + +## Bước 1: Thiết lập dự án và thêm gói OCR + +Đầu tiên, tạo một dự án web mới và thêm thư viện OCR. + +```bash +dotnet new web -n ImageOcrApi +cd ImageOcrApi +dotnet add package Awesome.Ocr --version 1.3.0 # replace with your actual OCR package +``` + +> **Mẹo:** Giữ các phụ thuộc của bạn luôn cập nhật. Các phiên bản mới thường mang lại cải thiện hiệu năng, đặc biệt đối với suy luận tăng tốc GPU. + +## Bước 2: Đăng ký Singleton OCR Engine (Dịch vụ chính) + +Chúng ta muốn một thể hiện `OcrEngine` duy nhất cho toàn bộ ứng dụng—không cần khởi tạo engine mới cho mỗi yêu cầu. Đăng ký nó trong container dịch vụ của builder. + +```csharp +using Awesome.Ocr; // <-- the OCR library namespace +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System.Drawing; // System.Drawing.Common for Image handling + +var builder = WebApplication.CreateBuilder(args); + +// Register a singleton OCR engine (English language) +// Uncomment the GPU line if you have a compatible GPU and the library supports it. +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU acceleration + return engine; +}); +``` + +**Tại sao lại là singleton?** +Việc tạo một OCR engine có thể tốn kém—nghĩ đến việc tải trọng lượng mạng nơ-ron vào bộ nhớ. Bằng cách tái sử dụng cùng một thể hiện, chúng ta tiết kiệm cả chu kỳ CPU và RAM, giúp thời gian phản hồi nhanh hơn cho mỗi lời gọi `/ocr`. + +## Bước 3: Xây dựng Ứng dụng + +Bây giờ chúng ta khởi tạo đối tượng `WebApplication`. + +```csharp +var app = builder.Build(); +``` + +Dòng này trông gần như ma thuật, nhưng bên trong nó thiết lập routing, middleware và container DI mà chúng ta vừa cấu hình. + +## Bước 4: Định nghĩa Endpoint POST – “Tải lên Hình ảnh qua POST” + +Đây là phần cốt lõi của hướng dẫn: một endpoint cho phép **tải lên hình ảnh qua POST**, đọc payload multipart và chuyển dữ liệu cho OCR engine. + +```csharp +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + // Step 5: Read multipart form data and extract the uploaded image + var form = await request.ReadFormAsync(); // <-- read multipart/form-data + var file = form.Files["image"]; // expects a field named "image" + + if (file is null || file.Length == 0) + { + return Results.BadRequest("No image file provided."); + } + + // Guard against unsupported content types + if (!file.ContentType.StartsWith("image/")) + { + return Results.BadRequest("Uploaded file is not an image."); + } + + // Load the image into a System.Drawing.Image + using var img = Image.FromStream(file.OpenReadStream()); + + // Step 6: Perform OCR on the image + string text = ocr.Recognize(img); // <-- perform OCR on image + + // Step 7: Return the extracted text as plain‑text + return Results.Text(text); +}); +``` + +### Phân tích Logic + +| Bước | Điều gì xảy ra | Tại sao quan trọng | +|------|----------------|--------------------| +| **ReadFormAsync** | Phân tích yêu cầu *multipart/form-data* đến. | Nếu không có bước này, bạn không thể truy cập các tệp đã tải lên. | +| **form.Files["image"]** | Lấy tệp có tên trường form là `image`. | Đảm bảo một hợp đồng dự đoán được cho người gọi. | +| **Content‑type check** | Kiểm tra tệp có phải là hình ảnh (ví dụ `image/png`). | Ngăn OCR engine bị lỗi khi nhận dữ liệu không phải hình ảnh. | +| **Image.FromStream** | Chuyển luồng raw thành một `System.Drawing.Image`. | Thư viện OCR yêu cầu một đối tượng `Image`, không phải mảng byte thô. | +| **ocr.Recognize(img)** | Gọi OCR engine để **nhận dạng văn bản từ hình ảnh**. | Đây là bước **thực hiện OCR trên hình ảnh** cốt lõi. | +| **Results.Text** | Trả về phản hồi dạng văn bản thuần. | Định dạng đơn giản, dễ tiêu thụ cho các dịch vụ downstream. | + +## Bước 5: Chạy API + +Cuối cùng, khởi động máy chủ web. + +```csharp +app.Run(); +``` + +Khi bạn chạy `dotnet run`, API sẽ lắng nghe tại `http://localhost:5000` (hoặc cổng bạn chọn). Bạn có thể kiểm tra bằng `curl`: + +```bash +curl -X POST http://localhost:5000/ocr \ + -F "image=@/path/to/receipt.png" \ + -H "Accept: text/plain" +``` + +**Kết quả mong đợi:** Console sẽ in ra các ký tự đã nhận dạng, ví dụ: + +``` +Total: $23.45 +Date: 2026-05-20 +Item A $12.00 +Item B $11.45 +``` + +Nếu hình ảnh mờ hoặc ngôn ngữ không được hỗ trợ, OCR engine sẽ trả về chuỗi rỗng hoặc thông báo lỗi—hãy xử lý các trường hợp này trong mã production. + +## Các Trường hợp Cạnh & Thực hành Tốt + +### 1. Tệp lớn + +Giới hạn mặc định cho body yêu cầu là 30 MB. Đối với các bản quét lớn hơn, bạn có thể cần điều chỉnh: + +```csharp +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 100 * 1024 * 1024; // 100 MB +}); +``` + +### 2. OCR bất đồng bộ + +Một số thư viện OCR cung cấp các phương thức async (`RecognizeAsync`). Nếu thư viện của bạn có, thay thế `ocr.Recognize(img)` bằng `await ocr.RecognizeAsync(img)` và đánh dấu lambda là `async`. + +### 3. Các lưu ý bảo mật + +- **Xác thực kích thước tệp** trước khi tải vào bộ nhớ. +- **Làm sạch tên tệp** nếu bạn ghi nó ra đĩa. +- **Giới hạn tốc độ** endpoint để tránh tấn công từ chối dịch vụ. + +### 4. Tăng tốc GPU + +Nếu bạn bỏ comment dòng `engine.GpuDevice = new GpuDevice(0);` và phần cứng của bạn hỗ trợ CUDA hoặc DirectML, bạn sẽ thấy tốc độ tăng đáng kể, đặc biệt với các hình ảnh độ phân giải cao. + +## Ví dụ Hoạt động Đầy đủ + +Dưới đây là file `Program.cs` hoàn chỉnh mà bạn có thể sao chép‑dán vào một dự án Minimal API mới. + +```csharp +using Awesome.Ocr; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using System.Drawing; + +var builder = WebApplication.CreateBuilder(args); + +// Optional: increase multipart limit for big images +builder.Services.Configure(options => +{ + options.MultipartBodyLengthLimit = 50 * 1024 * 1024; // 50 MB +}); + +// Register the OCR engine as a singleton +builder.Services.AddSingleton(sp => +{ + var engine = new OcrEngine { Language = OcrLanguage.English }; + // engine.GpuDevice = new GpuDevice(0); // enable GPU if available + return engine; +}); + +var app = builder.Build(); + +app.MapPost("/ocr", async (HttpRequest request, OcrEngine ocr) => +{ + var form = await request.ReadFormAsync(); + var file = form.Files["image"]; + + if (file is null || file.Length == 0) + return Results.BadRequest("No image file provided."); + + if (!file.ContentType.StartsWith("image/")) + return Results.BadRequest("Uploaded file is not an image."); + + using var img = Image.FromStream(file.OpenReadStream()); + + // Core OCR operation + string text = ocr.Recognize(img); + + return Results.Text(text); +}); + +app.Run(); +``` + +Lưu lại, chạy `dotnet run`, và bạn đã sẵn sàng **trích xuất văn bản từ hình ảnh** theo yêu cầu. + +## Kết luận + +Chúng ta đã đi qua một **giải pháp hoàn chỉnh, đầu‑tới‑cuối** để trích xuất văn bản từ hình ảnh bằng ASP.NET Core Minimal API. Bắt đầu từ việc tạo khung dự án, chúng ta **đã đăng ký một singleton OCR engine**, xây dựng một endpoint cho phép **tải lên hình ảnh qua POST**, **đọc dữ liệu multipart**, và cuối cùng **thực hiện OCR trên hình ảnh** để trả về văn bản thuần sạch sẽ. + +Từ đây bạn có thể: + +- Thêm lớp bọc JSON để có phản hồi phong phú hơn. +- Kết nối cơ sở dữ liệu để lưu trữ văn bản đã trích xuất. +- Mở rộng hỗ trợ nhiều ngôn ngữ (`OcrLanguage.Spanish`, v.v.). + +Mẫu này mở rộng tốt—chỉ cần đưa cùng một endpoint vào một microservice lớn hơn hoặc expose nó phía sau một API gateway. + +Bạn có câu hỏi về xử lý PDF, xử lý batch, hay tối ưu GPU? Hãy để lại bình luận, chúc lập trình vui! + +## Các Hướng dẫn Liên quan + +- [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/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md b/ocr/vietnamese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md new file mode 100644 index 000000000..e1ba55810 --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/_index.md @@ -0,0 +1,312 @@ +--- +category: general +date: 2026-05-25 +description: Trích xuất văn bản từ hình ảnh bằng C# và Aspose OCR. Tìm hiểu cách chuyển + đổi jpg sang văn bản, tải hình ảnh cho OCR và nhận kết quả đáng tin cậy nhanh chóng. +draft: false +keywords: +- extract text from image +- convert jpg to text +- how to ocr image +- c# image to text +- load image for ocr +language: vi +og_description: Trích xuất văn bản từ hình ảnh bằng C#. Hướng dẫn này chỉ cách chuyển + đổi jpg thành văn bản, tải hình ảnh cho OCR và xử lý nội dung đa ngôn ngữ. +og_title: Trích xuất văn bản từ hình ảnh trong C# – Hướng dẫn OCR Aspose +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + headline: Extract Text from Image in C# – Complete Aspose OCR Guide + type: TechArticle +- description: Extract text from image using C# and Aspose OCR. Learn how to convert + jpg to text, load image for OCR, and get reliable results fast. + name: Extract Text from Image in C# – Complete Aspose OCR Guide + steps: + - name: 6.1 Can I OCR a PNG or BMP? + text: Absolutely. The `Image.FromFile` method supports all formats that System.Drawing + recognizes, so just point the path to a `.png` or `.bmp` file and the rest of + the code stays identical. + - name: 6.2 What if the image is low‑resolution? + text: 'OCR accuracy drops dramatically below 300 dpi. A quick fix is to upscale + the image with `Graphics` before feeding it to the engine:' + - name: 6.3 Do I need a license for Aspose.OCR? + text: 'Aspose offers a free trial with a watermark. For production use, purchase + a license and add:' + type: HowTo +tags: +- C# +- OCR +- Aspose +title: Trích xuất văn bản từ hình ảnh trong C# – Hướng dẫn đầy đủ về Aspose OCR +url: /vi/net/text-recognition/extract-text-from-image-in-c-complete-aspose-ocr-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Trích xuất văn bản từ hình ảnh trong C# – Hướng dẫn đầy đủ Aspose OCR + +Bạn có bao giờ tự hỏi làm thế nào để **extract text from image** bằng mã C# thuần? Bạn không phải là người duy nhất. Dù bạn đang số hoá hoá đơn, quét biển hiệu, hay chỉ đơn giản tò mò về OCR, khả năng lấy ký tự từ một bức ảnh là một kỹ năng hữu ích. Trong hướng dẫn này chúng tôi sẽ đi qua một ví dụ đầy đủ, có thể chạy được, cho thấy chính xác cách **extract text from image** với Aspose.OCR, và chúng tôi cũng sẽ đề cập đến cách **convert jpg to text**, **load image for OCR**, và trả lời câu hỏi cổ điển “**how to ocr image**” một lần và mãi mãi. + +Khi kết thúc hướng dẫn này, bạn sẽ có một ứng dụng console tự chứa, đọc một tệp JPEG, nhận dạng tiếng Ukraina (hoặc bất kỳ ngôn ngữ nào được hỗ trợ), và in kết quả ra console. Không có tham chiếu mơ hồ, không thiếu bất kỳ phần nào—chỉ một giải pháp hoàn chỉnh bạn có thể sao chép‑dán và chạy. + +--- + +## Những gì bạn sẽ học + +* Cách cài đặt gói NuGet Aspose.OCR. +* Mã chính xác cần thiết để **load image for OCR** trong C#. +* Cách đặt ngôn ngữ và thực sự **extract text from image**. +* Mẹo để **convert jpg to text** một cách hiệu quả. +* Các lỗi thường gặp và cách tránh chúng. + +Nếu bạn đã có môi trường phát triển .NET được thiết lập, bạn đã sẵn sàng để bắt đầu. Nếu không, phần yêu cầu trước đây dưới đây sẽ giúp bạn nhanh chóng chuẩn bị. + +--- + +## Yêu cầu trước + +| Yêu cầu | Lý do quan trọng | +|-------------|----------------| +| .NET 6.0 SDK (hoặc mới hơn) | Cung cấp môi trường chạy cho ứng dụng console. | +| Visual Studio 2022 hoặc VS Code | Giúp việc chỉnh sửa và gỡ lỗi dễ dàng hơn. | +| Kết nối Internet (lần chạy đầu) | NuGet cần tải Aspose.OCR. | +| Một ảnh JPEG bạn muốn xử lý (ví dụ, `ukrainian_sign.jpg`) | Tệp nguồn cho engine OCR. | + +> **Mẹo:** Nếu bạn đang dùng Linux hoặc macOS, cùng một đoạn mã hoạt động với .NET CLI (`dotnet new console`), vì vậy bạn có thể bỏ qua IDE nặng. + +--- + +## Bước 1 – Cài đặt Aspose.OCR qua NuGet + +Mở terminal của bạn (hoặc Package Manager Console) và chạy: + +```bash +dotnet add package Aspose.OCR +``` + +Dòng lệnh duy nhất này sẽ tải các binary mới nhất của Aspose.OCR và tất cả các phụ thuộc truyền thống. Không cần thao tác thủ công với DLL. + +--- + +## Bước 2 – Tạo OCR Engine (Trái tim của việc trích xuất) + +Bây giờ thư viện đã sẵn sàng, chúng ta có thể tạo một thể hiện của `OcrEngine`. Đối tượng này chịu trách nhiệm **extracting text from image** dữ liệu. + +```csharp +using Aspose.OCR; +using System.Drawing; // For Image class +using System; + +// Initialize the OCR engine +var ocrEngine = new OcrEngine(); +``` + +> **Tại sao điều này quan trọng:** Engine bao gồm các thuật toán OCR, mô hình ngôn ngữ và các tùy chọn cấu hình. Tạo một lần và tái sử dụng nó cho nhiều ảnh sẽ tiết kiệm bộ nhớ và nhanh hơn. + +--- + +## Bước 3 – Tải ảnh cho OCR (Và đặt ngôn ngữ) + +Bước tiếp theo là cho engine biết ảnh nào sẽ được đọc. Đây là nơi cụm từ **load image for OCR** xuất hiện. + +```csharp +// Path to the JPEG you want to process +string imagePath = @"YOUR_DIRECTORY/ukrainian_sign.jpg"; + +// Load the image into a System.Drawing.Image object +Image inputImage = Image.FromFile(imagePath); + +// Optional: If you’re dealing with a different language, set it here +ocrEngine.Language = OcrLanguage.Ukrainian; // Change as needed +``` + +> **Trường hợp đặc biệt:** Nếu tệp không tồn tại, `Image.FromFile` sẽ ném ra `FileNotFoundException`. Hãy bao bọc lời gọi trong khối try‑catch cho mã sản xuất. + +--- + +## Bước 4 – Thực hiện OCR và Trích xuất Văn bản + +Với ảnh đã được tải, engine bây giờ có thể **extract text from image**. Phương thức `Recognize` thực hiện phần công việc nặng. + +```csharp +// Perform OCR – this returns the recognized string +string recognizedText = ocrEngine.Recognize(inputImage); +``` + +Nếu mọi thứ diễn ra tốt, `recognizedText` sẽ chứa dạng văn bản thuần của mọi thứ mà engine OCR có thể đọc. + +--- + +## Bước 5 – Chuyển đổi JPG sang Văn bản (Kết hợp mọi thứ lại) + +Mã chúng ta đã xây dựng cho tới nay đã **convert jpg to text**, nhưng hãy gói nó trong một phương thức gọn gàng mà bạn có thể gọi nhiều lần. + +```csharp +static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) +{ + var engine = new OcrEngine { Language = language }; + using var img = Image.FromFile(filePath); + return engine.Recognize(img); +} +``` + +Bây giờ bạn có thể đơn giản làm: + +```csharp +string result = ConvertJpgToText(@"YOUR_DIRECTORY/ukrainian_sign.jpg", OcrLanguage.Ukrainian); +Console.WriteLine(result); +``` + +**Kết quả mong đợi** (rút gọn để ngắn gọn): + +``` +Вітаємо! Це приклад тексту з українською мовою. +``` + +Nếu ảnh chứa văn bản tiếng Anh, thay đổi `OcrLanguage.English` và bạn sẽ thấy kết quả tương ứng. + +--- + +## Bước 6 – Xử lý các câu hỏi “How to OCR Image” thường gặp + +### 6.1 Tôi có thể OCR một PNG hoặc BMP không? + +Chắc chắn. Phương thức `Image.FromFile` hỗ trợ tất cả các định dạng mà System.Drawing nhận diện, vì vậy chỉ cần chỉ đường dẫn tới tệp `.png` hoặc `.bmp` và phần còn lại của mã vẫn giống nhau. + +### 6.2 Nếu ảnh có độ phân giải thấp thì sao? + +Độ chính xác OCR giảm đáng kể dưới 300 dpi. Một cách khắc phục nhanh là tăng kích thước ảnh bằng `Graphics` trước khi đưa vào engine: + +```csharp +using var original = Image.FromFile(imagePath); +var upscale = new Bitmap(original, new Size(original.Width * 2, original.Height * 2)); +string text = ocrEngine.Recognize(upscale); +``` + +### 6.3 Tôi có cần giấy phép cho Aspose.OCR không? + +Aspose cung cấp bản dùng thử miễn phí có watermark. Đối với môi trường sản xuất, mua giấy phép và thêm: + +```csharp +License lic = new License(); +lic.SetLicense("Aspose.Total.lic"); +``` + +--- + +## Ví dụ Hoạt động Đầy đủ + +Dưới đây là một ứng dụng console hoàn chỉnh, sẵn sàng chạy, minh họa **how to OCR image**, **load image for OCR**, và **convert jpg to text** trong một gói gọn gàng. + +```csharp +// Program.cs +using Aspose.OCR; +using System; +using System.Drawing; + +namespace ImageToTextDemo +{ + class Program + { + static void Main(string[] args) + { + // ------------------------------------------------- + // 1️⃣ Verify arguments + // ------------------------------------------------- + if (args.Length == 0) + { + Console.WriteLine("Usage: dotnet run "); + return; + } + + string filePath = args[0]; + + // ------------------------------------------------- + // 2️⃣ Perform OCR (extract text from image) + // ------------------------------------------------- + try + { + string text = ConvertJpgToText(filePath, OcrLanguage.Ukrainian); + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(text); + } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + } + } + + /// + /// Converts a JPG (or any supported image) to plain text. + /// + /// Full path to the image file. + /// OCR language – defaults to English. + /// Recognized text. + static string ConvertJpgToText(string filePath, OcrLanguage language = OcrLanguage.English) + { + // Create and configure the OCR engine + var engine = new OcrEngine + { + Language = language + }; + + // Load the image – this is the "load image for OCR" step + using var img = Image.FromFile(filePath); + + // Run recognition and return the result + return engine.Recognize(img); + } + } +} +``` + +**Cách chạy nó** + +```bash +dotnet run -- "C:\Images\ukrainian_sign.jpg" +``` + +Bạn sẽ thấy văn bản đã trích xuất được in ra console, xác nhận rằng bạn đã thành công **extract text from image** bằng C#. + +--- + +## Những Cạm Bẫy Thường Gặp & Mẹo Chuyên Gia + +| Vấn đề | Tại sao xảy ra | Cách khắc phục | +|-------|----------------|----------------| +| Kết quả trống | Ảnh quá tối hoặc độ tương phản thấp. | Tiền xử lý bằng `Bitmap` để tăng độ sáng. | +| Ngôn ngữ sai | Thuộc tính `Language` để mặc định tiếng Anh. | Đặt rõ `ocrEngine.Language = OcrLanguage.Ukrainian;` (hoặc ngôn ngữ mục tiêu). | +| Lỗi hết bộ nhớ | Ảnh rất lớn được tải mà không giải phóng. | Bao bọc `Image.FromFile` trong khối `using` (như đã minh họa). | +| Watermark giấy phép | Chạy bản dùng thử không có giấy phép. | Áp dụng giấy phép đã mua ngay trong `Main`. | + +--- + +## Kết luận + +Chúng tôi vừa trình bày mọi thứ bạn cần để **extract text from image** trong C#—từ việc cài đặt Aspose.OCR, **loading image for OCR**, đến **convert jpg to text** và xử lý các kịch bản đa ngôn ngữ. Chương trình mẫu hoàn chỉnh kết nối tất cả các phần lại với nhau, cung cấp cho bạn nền tảng đáng tin cậy cho bất kỳ dự án liên quan đến OCR nào. + +Tiếp theo, bạn có thể khám phá: + +* **How to OCR image** streams thay vì tệp (sử dụng `MemoryStream`). +* Thêm **c# image to text** xử lý hậu kỳ như kiểm tra chính tả. +* Tích hợp bước OCR vào pipeline lớn hơn (ví dụ, lưu kết quả vào cơ sở dữ liệu). + +Hãy thoải mái thử nghiệm với các ngôn ngữ, định dạng ảnh và các kỹ thuật tiền xử lý khác nhau. OCR vừa là nghệ thuật vừa là khoa học, và càng thực hành, kết quả sẽ càng tốt. + +Chúc lập trình vui vẻ, và hy vọng ảnh của bạn luôn có thể đọc được! + +## Các hướng dẫn liên quan + +- [Extract image text C# with language selection using Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Extract Text from Image – OCR Optimization with Aspose.OCR for .NET](/ocr/english/net/ocr-optimization/) +- [How to Extract Text from Image by Preparing Rectangles in OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md b/ocr/vietnamese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md new file mode 100644 index 000000000..94258e6a0 --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/_index.md @@ -0,0 +1,299 @@ +--- +category: general +date: 2026-05-25 +description: Cách sử dụng OCR trong C# để trích xuất văn bản từ các tệp hình ảnh. + Học cách nhận dạng ký tự Trung Quốc từ file JPG bằng Aspose.OCR trong vài bước đơn + giản. +draft: false +keywords: +- how to use OCR +- extract text from image +- recognize text from jpg +- recognize chinese characters +- ocr chinese simplified +language: vi +og_description: Cách sử dụng OCR trong C# để trích xuất văn bản từ các tệp hình ảnh. + Hướng dẫn này chỉ cho bạn cách nhận dạng ký tự tiếng Trung từ một tệp JPG bằng Aspose.OCR. +og_title: Cách sử dụng OCR trong C# – Nhận dạng văn bản tiếng Trung từ JPG +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + headline: How to Use OCR in C# – Recognize Chinese Text from JPG + type: TechArticle +- description: How to use OCR in C# to extract text from image files. Learn to recognize + Chinese characters from a JPG using Aspose.OCR in a few simple steps. + name: How to Use OCR in C# – Recognize Chinese Text from JPG + steps: + - name: What’s happening under the hood? + text: '- **`OcrEngine.Language`** tells Aspose which dictionary to use. By picking + `ChineseSimplified`, we instruct the engine to look for the Simplified Chinese + language pack. - **First‑time download**: When `Recognize` runs, the SDK reaches + out to Aspose’s CDN, pulls the ≈6 MB language file, caches it lo' + - name: 5.1 Dealing with Low‑Quality Images + text: 'OCR accuracy drops when the source image is blurry, noisy, or has poor + lighting. A quick fix is to pre‑process the image:' + - name: 5.2 Running in a Headless Environment + text: 'If you’re deploying to a Linux container without a GUI, make sure the `libgdiplus` + library (required for `System.Drawing`) is installed:' + - name: 5.3 Caching the Language Pack Manually + text: You can download the language file once and point Aspose to it via the `License` + API, which eliminates the one‑time network call. This is handy for offline scenarios. + - name: Expected Output + text: 'If the JPG contains the phrase “欢迎光临”, the console will print:' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Image Processing +title: Cách sử dụng OCR trong C# – Nhận dạng văn bản tiếng Trung từ JPG +url: /vi/net/text-recognition/how-to-use-ocr-in-c-recognize-chinese-text-from-jpg/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Cách sử dụng OCR trong C# – Nhận dạng văn bản tiếng Trung từ JPG + +Bạn đã bao giờ tự hỏi **cách sử dụng OCR** để lấy các từ ra khỏi một bức ảnh bạn chụp bằng điện thoại chưa? Bạn không phải là người duy nhất. Trong nhiều dự án thực tế—như máy quét biên lai, ứng dụng dịch thuật, hoặc nhập dữ liệu tự động—bạn sẽ cần **trích xuất văn bản từ hình ảnh** một cách nhanh chóng và đáng tin cậy. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ đầy đủ, có thể chạy được mà **nhận dạng văn bản từ các tệp JPG** và thậm chí xử lý trường hợp khó khăn của **nhận dạng ký tự tiếng Trung** bằng cách sử dụng gói ngôn ngữ **OCR Chinese Simplified**. Khi kết thúc, bạn sẽ có một ứng dụng console tự chứa, in chuỗi đã phát hiện ra trên console, mà không cần tải xuống thủ công nào thêm. + +> **Lưu ý nhanh:** Mã này hoạt động với Aspose.OCR ≥ 23.7, tự động tải về tài nguyên ngôn ngữ khi sử dụng lần đầu. Nếu bạn đang dùng phiên bản cũ hơn, bạn sẽ cần thêm ngôn ngữ một cách thủ công. + +## Yêu cầu trước + +- .NET 6.0 SDK hoặc phiên bản mới hơn (ví dụ này nhắm tới .NET 6, nhưng .NET 5 cũng hoạt động được) +- Phiên bản mới nhất của Visual Studio 2022 hoặc VS Code với phần mở rộng C# +- Kết nối internet để tải ngôn ngữ lần đầu +- Một hình ảnh JPG chứa văn bản tiếng Trung giản thể (chúng tôi sẽ gọi nó là `chinese_sign.jpg`) + +Chỉ vậy thôi—không cần các engine OCR nặng, không cần xử lý DLL gốc. Chỉ cần một vài lệnh NuGet và một vài dòng mã. + +## Bước 1: Cài đặt Aspose.OCR qua NuGet + +Đầu tiên, chúng ta cần thư viện OCR. Mở terminal trong thư mục dự án và chạy: + +```bash +dotnet add package Aspose.OCR +``` + +Hoặc, nếu bạn thích giao diện Visual Studio, nhấp chuột phải vào **Dependencies → Manage NuGet Packages**, tìm “Aspose.OCR”, và nhấn **Install**. + +> **Mẹo chuyên nghiệp:** Giữ các gói của bạn luôn cập nhật. Các gói ngôn ngữ mới và cải tiến hiệu năng luôn xuất hiện trong mỗi bản phát hành phụ. + +## Bước 2: Tạo dự án Console mới (Nếu bạn chưa có) + +Nếu bạn bắt đầu từ đầu, tạo một ứng dụng console mới: + +```bash +dotnet new console -n OcrChineseDemo +cd OcrChineseDemo +``` + +Bây giờ bạn đã có tệp `Program.cs` sẵn sàng cho mã OCR. + +## Bước 3: Viết mã OCR – Nhận dạng tiếng Trung giản thể từ JPG + +Mở `Program.cs` và thay thế nội dung của nó bằng đoạn sau. Mỗi dòng đều có chú thích để bạn thấy *tại sao* chúng ta thực hiện từng bước, không chỉ *cái gì* chúng ta đang làm. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // Required for Image.FromFile + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // -------------------------------------------------------------- + // 1️⃣ Initialise the OCR engine and request the Simplified Chinese + // language. This language isn’t bundled in the core package, + // so Aspose.OCR will download it the first time you call + // Recognize(). + // -------------------------------------------------------------- + var ocrEngine = new OcrEngine + { + // The enum value maps to the language pack name. + Language = OcrLanguage.ChineseSimplified + }; + + // -------------------------------------------------------------- + // 2️⃣ Load the image you want to process. Replace the path with + // the actual location of your JPG file. + // -------------------------------------------------------------- + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + using var image = Image.FromFile(imagePath); + + // -------------------------------------------------------------- + // 3️⃣ Perform the recognition. The first call may take a few + // seconds because the language resources are being fetched. + // -------------------------------------------------------------- + string recognizedText = ocrEngine.Recognize(image); + + // -------------------------------------------------------------- + // 4️⃣ Output the result to the console. + // -------------------------------------------------------------- + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Điều gì đang diễn ra phía sau? + +- **`OcrEngine.Language`** cho Aspose biết từ điển nào sẽ được sử dụng. Bằng cách chọn `ChineseSimplified`, chúng ta chỉ định engine tìm gói ngôn ngữ tiếng Trung giản thể. +- **Tải xuống lần đầu**: Khi `Recognize` chạy, SDK sẽ liên hệ tới CDN của Aspose, tải về tệp ngôn ngữ ≈6 MB, lưu vào bộ nhớ cache cục bộ, và sau đó thực hiện OCR. Các lần gọi sau đều tức thì. +- **`Image.FromFile`** hoạt động với bất kỳ định dạng raster nào mà .NET có thể giải mã—JPG, PNG, BMP—do đó bạn có thể **trích xuất văn bản từ hình ảnh** của nhiều loại, không chỉ JPG. + +## Bước 4: Chạy ứng dụng và kiểm tra đầu ra + +Biên dịch và chạy: + +```bash +dotnet run +``` + +Bạn sẽ thấy một cái gì đó giống như: + +``` +=== Recognized Text === +欢迎光临 +``` + +Nếu console in ra ký tự rác hoặc chuỗi trống, hãy kiểm tra lại rằng: + +1. Hình ảnh thực sự chứa các ký tự tiếng Trung rõ ràng, độ tương phản cao. +2. Đường dẫn tệp đúng (không có khoảng trắng thừa hoặc thiếu phần mở rộng). +3. Máy của bạn có thể truy cập `https://download.aspose.com` để tải gói ngôn ngữ. + +## Bước 5: Xử lý các trường hợp đặc biệt và những khó khăn thường gặp + +### 5.1 Xử lý hình ảnh chất lượng thấp + +Độ chính xác của OCR giảm khi hình ảnh nguồn bị mờ, nhiễu, hoặc ánh sáng kém. Một cách khắc phục nhanh là tiền xử lý hình ảnh: + +```csharp +using System.Drawing.Imaging; + +// Convert to grayscale +var gray = new Bitmap(image.Width, image.Height); +using (var g = Graphics.FromImage(gray)) +{ + var colorMatrix = new ColorMatrix( + new float[][]{ + new float[]{0.3f,0.3f,0.3f,0,0}, + new float[]{0.59f,0.59f,0.59f,0,0}, + new float[]{0.11f,0.11f,0.11f,0,0}, + new float[]{0,0,0,1,0}, + new float[]{0,0,0,0,1} + }); + var attributes = new ImageAttributes(); + attributes.SetColorMatrix(colorMatrix); + g.DrawImage(image, new Rectangle(0,0,image.Width,image.Height), + 0,0,image.Width,image.Height, GraphicsUnit.Pixel, attributes); +} + +// Use the processed bitmap for OCR +string recognizedText = ocrEngine.Recognize(gray); +``` + +### 5.2 Chạy trong môi trường không giao diện (headless) + +Nếu bạn triển khai vào container Linux không có GUI, hãy chắc chắn rằng thư viện `libgdiplus` (cần cho `System.Drawing`) đã được cài đặt: + +```bash +apt-get update && apt-get install -y libgdiplus +``` + +### 5.3 Lưu cache gói ngôn ngữ thủ công + +Bạn có thể tải tệp ngôn ngữ một lần và chỉ định cho Aspose thông qua API `License`, điều này loại bỏ lần gọi mạng duy nhất. Thực tế hữu ích cho các kịch bản offline. + +```csharp +// Assuming you have the .dat file downloaded to /opt/ocr/langs/ +ocrEngine.SetLicense("Aspose.OCR.lic"); // optional if you have a paid license +ocrEngine.LoadLanguage(@" /opt/ocr/langs/ChineseSimplified.dat"); +``` + +## Ví dụ hoàn chỉnh (Tất cả trong một) + +Dưới đây là chương trình *đầy đủ* mà bạn có thể sao chép và dán vào `Program.cs`. Không có đoạn mã ẩn, không có script bên ngoài. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; + +namespace OcrChineseDemo +{ + class Program + { + static void Main(string[] args) + { + // Initialise OCR engine with Simplified Chinese language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.ChineseSimplified + }; + + // Path to the JPG image containing Chinese text + string imagePath = @"YOUR_DIRECTORY/chinese_sign.jpg"; + + // Load the image (ensure the file exists) + using var image = Image.FromFile(imagePath); + + // Recognize text – first call may download the language pack + string recognizedText = ocrEngine.Recognize(image); + + // Display the result + Console.WriteLine("=== Recognized Text ==="); + Console.WriteLine(recognizedText); + } + } +} +``` + +### Đầu ra dự kiến + +Nếu JPG chứa cụm từ “欢迎光临”, console sẽ in ra: + +``` +=== Recognized Text === +欢迎光临 +``` + +Bạn có thể thay thế hình ảnh bằng bất kỳ biển hiệu tiếng Trung giản thể nào khác, tên đường, hoặc nhãn sản phẩm—engine sẽ cố gắng hết sức. + +## Kết luận + +Chúng ta vừa mới tìm hiểu **cách sử dụng OCR** trong C# để **trích xuất văn bản từ hình ảnh**; đặc biệt là giải quyết thách thức **nhận dạng ký tự tiếng Trung** trong một **JPG**. Bằng cách tận dụng việc tải ngôn ngữ ngay lập tức của Aspose.OCR, bạn có thể giữ cho việc triển khai nhẹ nhàng trong khi vẫn hỗ trợ **OCR Chinese Simplified** ngay từ đầu. + +Tiếp theo là gì? Hãy thử các ý tưởng sau: + +- **Xử lý hàng loạt**: Duyệt qua một thư mục các hình ảnh và ghi mỗi kết quả vào file CSV. +- **Kết hợp với API dịch thuật**: Đưa chuỗi đã nhận dạng vào Azure Translator để tạo ứng dụng đa ngôn ngữ thời gian thực. +- **Khám phá các ngôn ngữ khác**: Thay `OcrLanguage.ChineseSimplified` bằng `Japanese` hoặc `Arabic` và xem cách mã tương tự thích nghi. + +Có câu hỏi về tối ưu hiệu năng, giấy phép, hoặc tích hợp OCR vào dịch vụ web? Hãy để lại bình luận bên dưới—chúc lập trình vui! + +--- + +![Ảnh chụp màn hình đầu ra console cho thấy cách sử dụng OCR trong C# để nhận dạng văn bản tiếng Trung từ ảnh JPG](ocr-chinese-demo.png "cách sử dụng OCR đầu ra console") + +## Các hướng dẫn liên quan + +- [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/) +- [Cách trích xuất văn bản từ hình ảnh bằng cách chuẩn bị các hình chữ nhật trong OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file diff --git a/ocr/vietnamese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md b/ocr/vietnamese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md new file mode 100644 index 000000000..9b0572bbb --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/_index.md @@ -0,0 +1,307 @@ +--- +category: general +date: 2026-05-25 +description: Tìm hiểu cách OCR văn bản tiếng Nga trong C# và trích xuất văn bản từ + hình ảnh bằng Aspose OCR. Mã từng bước để nhanh chóng chuyển đổi hình ảnh thành + văn bản C#. +draft: false +keywords: +- ocr russian text +- extract text from image +- image to text c# +- aspose ocr c# +- load image for ocr +language: vi +og_description: OCR văn bản tiếng Nga trong C# trở nên dễ dàng. Tìm hiểu cách trích + xuất văn bản từ hình ảnh, chuyển đổi hình ảnh thành văn bản trong C#, và tải hình + ảnh cho OCR bằng Aspose OCR. +og_title: OCR Văn bản tiếng Nga trong C# – Hướng dẫn đầy đủ Aspose OCR +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + headline: OCR Russian Text in C# – Complete Guide Using Aspose OCR + type: TechArticle +- description: Learn how to OCR Russian text in C# and extract text from image with + Aspose OCR. Step‑by‑step code to convert image to text C# quickly. + name: OCR Russian Text in C# – Complete Guide Using Aspose OCR + steps: + - name: Adjusting Confidence Threshold + text: 'Aspose OCR returns a confidence value per character internally. While the + API doesn’t expose it directly, you can enable **detailed output** to see which + words were low‑confidence:' + - name: Batch Processing Multiple Images + text: 'If you need to **extract text from image** files in bulk, wrap the recognition + logic in a loop:' + - name: Handling Unicode Output + text: 'Cyrillic characters are Unicode, so make sure your console encoding can + display them:' + - name: What’s Next? + text: '- Explore **aspose ocr c#** advanced options like layout analysis or PDF + output. - Combine this with **extract text from image** workflows in Azure Functions + for serverless processing. - Try different languages—simply switch `OcrLanguage.Russian` + to `OcrLanguage.English` or another supported code.' + type: HowTo +tags: +- OCR +- C# +- Aspose +- Text Extraction +title: OCR Văn bản tiếng Nga trong C# – Hướng dẫn toàn diện sử dụng Aspose OCR +url: /vi/net/text-recognition/ocr-russian-text-in-c-complete-guide-using-aspose-ocr/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# OCR Văn Bản Tiếng Nga trong C# – Hướng Dẫn Toàn Diện Sử Dụng Aspose OCR + +Bạn đã bao giờ cần OCR văn bản tiếng Nga trong C# nhưng không chắc thư viện nào đáng tin cậy? Bạn không đơn độc. Việc lấy được các ký tự sạch, có thể đọc được từ một ảnh Cyrillic có thể giống như giải mã tin nhắn bí mật—đặc biệt nếu bạn chưa thiết lập đúng mô hình ngôn ngữ. + +Trong hướng dẫn này, chúng ta sẽ đi qua một ví dụ thực tế cho thấy cách **trích xuất văn bản từ ảnh**, chuyển *image to text C#* và xử lý các đặc thù của nhận dạng tiếng Nga bằng Aspose OCR. Khi hoàn thành, bạn sẽ có một ứng dụng console sẵn sàng chạy, tải ảnh để OCR, in ra chuỗi đã nhận dạng và cung cấp nền tảng vững chắc cho các kịch bản nâng cao hơn. + +## Những Điều Bạn Sẽ Học + +- Cách cài đặt và cấu hình **Aspose OCR C#** để hỗ trợ ngôn ngữ tiếng Nga. +- Các bước chính để **tải ảnh cho OCR** và gọi engine. +- Mẹo xử lý các vấn đề thường gặp như thiếu tài nguyên ngôn ngữ hoặc ảnh mờ. +- Cách mở rộng giải pháp, chẳng hạn xử lý hàng loạt nhiều tệp hoặc điều chỉnh ngưỡng confidence. + +Không cần kinh nghiệm trước với Aspose; chỉ cần một chút hiểu biết cơ bản về C# và .NET là đủ để bắt đầu. + +## Yêu Cầu Trước + +Trước khi bắt đầu, hãy chắc chắn bạn đã có: + +1. **.NET 6.0** (hoặc mới hơn) SDK đã được cài đặt – mã nguồn hoạt động trên .NET Core và .NET Framework đều được. +2. **Visual Studio 2022** (hoặc bất kỳ IDE nào bạn thích). +3. Gói **Aspose.OCR for .NET** từ NuGet – bạn có thể lấy khóa dùng thử miễn phí từ trang web Aspose. +4. Tệp **mô hình ngôn ngữ tiếng Nga** (`rus.traineddata`) – tải về từ trang tài nguyên Aspose và đặt vào thư mục bạn sẽ tham chiếu sau này. +5. Một ảnh mẫu (`russian_doc.png`) chứa văn bản Cyrillic rõ ràng. + +Đã có đầy đủ? Tuyệt—bắt đầu nào. + +## Bước 1: Tạo Dự Án và Cài Đặt Aspose OCR + +Đầu tiên, tạo một dự án console mới: + +```bash +dotnet new console -n OcrRussianDemo +cd OcrRussianDemo +``` + +Bây giờ thêm gói Aspose OCR: + +```bash +dotnet add package Aspose.OCR +``` + +> **Mẹo chuyên nghiệp:** Nếu bạn đang dùng giấy phép dùng thử, hãy giữ tệp `Aspose.Total.lic` ở gần; bạn sẽ tải nó trong mã để tránh watermark. + +Sau khi gói được cài đặt, mở `Program.cs`. Bạn sẽ thấy phương thức `Main` mặc định—thay thế nội dung của nó bằng khung sườn mà chúng ta sẽ xây dựng. + +## Bước 2: Cấu Hình Engine OCR cho Ngôn Ngữ Tiếng Nga + +Trái tim của quá trình là đối tượng `OcrEngine`. Chúng ta cần chỉ định cho nó hai điều: ngôn ngữ cần nhận dạng và vị trí chứa các tệp mô hình ngôn ngữ. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; // For Image class + +class Program +{ + static void Main() + { + // Optional: set your Aspose license here + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Create and configure the OCR engine for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, // Primary language + ResourceFolder = @"C:\OCRResources\" // Folder with rus.traineddata + }; + + // Continue with image loading... +``` + +> **Tại sao lại quan trọng:** Nếu bạn bỏ qua việc đặt `Language = OcrLanguage.Russian`, engine sẽ mặc định tiếng Anh, và mọi ký tự Cyrillic sẽ xuất hiện dưới dạng ký tự rối. `ResourceFolder` chỉ đường tới thư mục chứa tệp `rus.traineddata`; nếu không có, Aspose sẽ ném ngoại lệ *resource not found*. + +## Bước 3: Tải Ảnh Để OCR + +Bây giờ chúng ta cần **tải ảnh cho OCR**. Aspose OCR làm việc với `System.Drawing.Image`, vì vậy bạn có thể truyền bất kỳ định dạng hỗ trợ nào (PNG, JPEG, BMP, v.v.). Đảm bảo đường dẫn tệp đúng; đường dẫn tương đối cũng ổn nếu bạn để ảnh cạnh file thực thi. + +```csharp + // 2️⃣ Load the image you want to process + string imagePath = @"C:\OCRResources\russian_doc.png"; + + // Validate the file exists to avoid a runtime crash + if (!System.IO.File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + using Image sourceImage = Image.FromFile(imagePath); +``` + +> **Trường hợp đặc biệt:** Nếu ảnh quá lớn (hơn 5 MB) bạn có thể muốn thu nhỏ nó trước. Độ chính xác OCR giảm khi DPI quá thấp, nhưng các tệp khổng lồ có thể gây áp lực bộ nhớ. Bạn có thể nhanh chóng thay đổi kích thước bằng `Graphics` nếu cần. + +## Bước 4: Nhận Dạng Văn Bản – Từ Image to Text C# Style + +Với engine đã được cấu hình và ảnh đã được tải, việc nhận dạng thực tế chỉ là một lời gọi duy nhất: + +```csharp + // 3️⃣ Perform OCR – this is the core "image to text C#" step + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 4️⃣ Output the recognized text + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +Khi bạn chạy chương trình (`dotnet run`), bạn sẽ thấy đầu ra giống như: + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Nếu kết quả trông như vô nghĩa, hãy kiểm tra lại: + +- Tệp `rus.traineddata` có tồn tại trong `ResourceFolder` không. +- Ảnh không quá mờ; cân nhắc áp dụng bộ lọc nhị phân đơn giản trước khi OCR. +- Cài đặt ngôn ngữ thực sự là `OcrLanguage.Russian`. + +## Bước 5: Tinh Chỉnh và Các Rủi Ro Thường Gặp + +### Điều Chỉnh Ngưỡng Confidence + +Aspose OCR trả về giá trị confidence cho mỗi ký tự bên trong. Mặc dù API không cung cấp trực tiếp, bạn có thể bật **detailed output** để xem những từ nào có confidence thấp: + +```csharp +ocrEngine.Recognize(sourceImage, OcrOptions.PdfImageOnly); +``` + +Nếu bạn nhận thấy nhiều lỗi nhận dạng, hãy thử: + +- **Tiền xử lý**: Chuyển ảnh sang thang độ xám, tăng độ tương phản, hoặc áp dụng bộ lọc trung vị. +- **Cài đặt DPI**: Đảm bảo ảnh có ít nhất 300 DPI cho các script Cyrillic. + +### Xử Lý Hàng Loạt Nhiều Ảnh + +Nếu bạn cần **trích xuất văn bản từ ảnh** hàng loạt, hãy bao bọc logic nhận dạng trong một vòng lặp: + +```csharp +string[] files = Directory.GetFiles(@"C:\OCRResources\Batch\", "*.png"); +foreach (var file in files) +{ + using Image img = Image.FromFile(file); + string txt = ocrEngine.Recognize(img); + File.WriteAllText($"{Path.ChangeExtension(file, ".txt")}", txt); +} +``` + +Bây giờ mỗi PNG sẽ có một tệp `.txt` tương ứng—rất tiện cho việc lưu trữ tài liệu. + +### Xử Lý Đầu Ra Unicode + +Các ký tự Cyrillic là Unicode, vì vậy hãy chắc chắn console của bạn có thể hiển thị chúng: + +```csharp +Console.OutputEncoding = System.Text.Encoding.UTF8; +``` + +Đặt dòng này ngay sau khi phương thức `Main` bắt đầu. Nếu không, bạn có thể sẽ thấy dấu hỏi (`?`) thay vì các chữ cái tiếng Nga. + +## Ví Dụ Hoàn Chỉnh + +Dưới đây là mã hoàn chỉnh, sẵn sàng chạy. Sao chép‑dán vào `Program.cs`, điều chỉnh các đường dẫn, và bạn đã sẵn sàng. + +```csharp +using Aspose.OCR; +using System; +using System.Drawing; +using System.IO; + +class Program +{ + static void Main() + { + // Enable proper Unicode display in the console + Console.OutputEncoding = System.Text.Encoding.UTF8; + + // Optional: load your Aspose license + // var license = new Aspose.OCR.License(); + // license.SetLicense("Aspose.Total.lic"); + + // 1️⃣ Configure OCR for Russian language + var ocrEngine = new OcrEngine + { + Language = OcrLanguage.Russian, + ResourceFolder = @"C:\OCRResources\" // <-- folder with rus.traineddata + }; + + // 2️⃣ Path to the image containing Russian text + string imagePath = @"C:\OCRResources\russian_doc.png"; + + if (!File.Exists(imagePath)) + { + Console.WriteLine($"Image not found at {imagePath}"); + return; + } + + // 3️⃣ Load the image (this is the "load image for OCR" step) + using Image sourceImage = Image.FromFile(imagePath); + + // 4️⃣ Recognize text – the core "image to text C#" operation + string recognizedText = ocrEngine.Recognize(sourceImage); + + // 5️⃣ Show the result + Console.WriteLine("=== Recognized Russian Text ==="); + Console.WriteLine(recognizedText); + } +} +``` + +**Kết quả mong đợi** (giả sử ảnh mẫu chứa câu “Пример текста на русском языке.”): + +``` +=== Recognized Russian Text === +Пример текста на русском языке. +``` + +Nếu bạn thấy gì khác, hãy quay lại các mẹo khắc phục trong Bước 5. + +## Kết Luận + +Bạn đã có một ví dụ toàn diện, từ đầu đến cuối, về cách **ocr russian text** trong C# bằng Aspose OCR. Từ việc cài đặt thư viện, cấu hình mô hình ngôn ngữ tiếng Nga, tải ảnh và chuyển nó thành văn bản Unicode sạch, mọi khía cạnh đều được bao phủ. + +Hãy nhớ, yếu tố then chốt để OCR đáng tin cậy là nguồn tài liệu tốt: phông chữ rõ ràng, DPI đủ, và tài nguyên ngôn ngữ chính xác. Khi đã nắm vững nền tảng, bạn có thể mở rộng sang xử lý hàng loạt, tích hợp với lưu trữ đám mây, hoặc thậm chí kết hợp với AI để kiểm tra chính tả. + +### Tiếp Theo Bạn Nên Làm Gì? + +- Khám phá các tùy chọn nâng cao của **aspose ocr c#** như phân tích bố cục hoặc xuất PDF. +- Kết hợp với quy trình **extract text from image** trong Azure Functions để xử lý không máy chủ. +- Thử các ngôn ngữ khác—chỉ cần đổi `OcrLanguage.Russian` thành `OcrLanguage.English` hoặc mã ngôn ngữ hỗ trợ khác. + +Có câu hỏi hoặc ảnh khó chịu không hợp? Để lại bình luận bên dưới, và chúc bạn lập trình vui vẻ! + +![ocr russian text example](ocr-russian-example.png){alt="ví dụ văn bản OCR tiếng Nga"} + +## Các Bài Hướng Dẫn Liên Quan + +- [Trích xuất văn bản ảnh C# với lựa chọn ngôn ngữ bằng Aspose.OCR](/ocr/english/net/ocr-configuration/ocr-operation-with-language-selection/) +- [Nhận dạng văn bản ảnh với Aspose OCR cho nhiều ngôn ngữ](/ocr/english/net/ocr-settings/working-with-different-languages/) +- [Trích xuất Văn Bản Từ Ảnh Sử Dụng Aspose.OCR .NET](/ocr/english/net/image-and-drawing-recognition/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/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/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md b/ocr/vietnamese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md new file mode 100644 index 000000000..37249c29f --- /dev/null +++ b/ocr/vietnamese/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/_index.md @@ -0,0 +1,211 @@ +--- +category: general +date: 2026-05-25 +description: Nhận dạng văn bản từ hình ảnh bằng Aspose OCR trong C#. Tìm hiểu cách + tải hình ảnh cho OCR, thiết lập ngôn ngữ OCR, tạo engine OCR và trích xuất văn bản + từ tệp TIFF. +draft: false +keywords: +- recognize text from image +- extract text from tiff +- load image for OCR +- set OCR language +- create OCR engine +language: vi +og_description: Nhận dạng văn bản từ hình ảnh bằng Aspose OCR trong C#. Hướng dẫn + này cho thấy cách tạo engine OCR, tải hình ảnh để OCR, thiết lập ngôn ngữ OCR và + trích xuất văn bản từ TIFF. +og_title: Nhận dạng văn bản từ hình ảnh bằng Aspose OCR – Hướng dẫn đầy đủ C# +schemas: +- author: Aspose + dateModified: '2026-05-25' + description: recognize text from image using Aspose OCR in C#. Learn how to load + image for OCR, set OCR language, create OCR engine and extract text from TIFF. + headline: recognize text from image with Aspose OCR – Complete C# Guide + type: TechArticle +- questions: + - answer: Remove the `GpuDevice` line; the engine will automatically switch to CPU + mode. Performance will be slower but the results remain accurate. + question: What if my GPU isn’t detected? + - answer: Absolutely—`Image.FromFile` works with any format supported by System.Drawing, + so you can **load image for OCR** regardless of extension. + question: Can I process PNG or JPEG files? + - answer: Increase `ocrEngine.PreprocessOptions.Dpi` before calling `Recognize`. + Higher DPI gives the engine more pixels to work with, improving accuracy. + question: How do I handle low‑resolution scans? + - answer: The `GpuMemoryLimit` property caps GPU usage. If you hit the limit, the + engine will fallback to CPU for the remaining pages. + question: Is there a limit to the size of the TIFF? + type: FAQPage +tags: +- OCR +- C# +- Aspose +- GPU +- Text Extraction +title: Nhận dạng văn bản từ hình ảnh bằng Aspose OCR – Hướng dẫn C# đầy đủ +url: /vi/net/text-recognition/recognize-text-from-image-with-aspose-ocr-complete-c-guide/ +--- + +{{< blocks/products/pf/main-wrap-class >}} +{{< blocks/products/pf/main-container >}} +{{< blocks/products/pf/tutorial-page-section >}} + +# Nhận dạng văn bản từ hình ảnh với Aspose OCR – Hướng dẫn đầy đủ C# + +Bạn đã bao giờ cần **nhận dạng văn bản từ hình ảnh** nhưng không chắc thư viện nào sẽ cho bạn cả tốc độ và độ chính xác? Bạn không đơn độc. Trong nhiều dự án xử lý hoá đơn hoặc lưu trữ, vấn đề lớn nhất là lấy được văn bản sạch, có thể tìm kiếm từ các tệp TIFF mà không phải viết bộ phân tích tùy chỉnh. + +Thực tế là: Aspose OCR cho .NET biến toàn bộ quy trình này thành việc đơn giản. Trong hướng dẫn này, chúng ta sẽ đi qua mọi thứ bạn cần—cài đặt gói, **tạo engine OCR**, tải một tệp TIFF, thiết lập ngôn ngữ OCR, và cuối cùng **trích xuất văn bản từ TIFF**. Khi kết thúc, bạn sẽ có một ứng dụng console sẵn sàng chạy, có thể **nhận dạng văn bản từ hình ảnh** trong tích tắc. + +## Yêu cầu trước + +- .NET 6.0 hoặc mới hơn (mã cũng hoạt động với .NET Core và .NET Framework) +- Visual Studio 2022 (hoặc bất kỳ IDE nào bạn thích) +- Gói NuGet Aspose.OCR (hỗ trợ GPU yêu cầu add‑on `Aspose.OCR.Gpu`) +- Một GPU hỗ trợ CUDA nếu bạn muốn tốc độ cao hơn (tùy chọn nhưng nên có) + +> **Mẹo chuyên nghiệp:** Nếu bạn không có GPU, chỉ cần bỏ qua dòng `GpuDevice` và engine sẽ tự động chuyển sang CPU. + +## Bước 1: Cài đặt Aspose OCR và Tạo Engine OCR + +Đầu tiên, thêm các gói cần thiết qua NuGet: + +```bash +dotnet add package Aspose.OCR +dotnet add package Aspose.OCR.Gpu # optional GPU support +``` + +Bây giờ chúng ta có thể **tạo engine OCR**. Đối tượng này là trái tim của quá trình; nó chứa các cấu hình như thiết bị chạy và giới hạn bộ nhớ. + +```csharp +using Aspose.OCR; +using Aspose.OCR.Gpu; // GPU support +using System; +using System.Drawing; + +class Program +{ + static void Main() + { + // Step 1: Instantiate the OCR engine (GPU‑enabled) + var ocrEngine = new OcrEngine + { + // 0 = first GPU in the system; change if you have multiple cards + GpuDevice = new GpuDevice(0), + // Optional: cap GPU memory usage to 1024 MB + GpuMemoryLimit = 1024 + }; +``` + +**Tại sao lại quan trọng:** Khi gắn engine vào GPU, bạn giảm đáng kể thời gian **nhận dạng văn bản từ hình ảnh**, đặc biệt với các lô lớn các tệp TIFF độ phân giải cao. + +## Bước 2: Tải Hình Ảnh cho OCR + +Tiếp theo, chúng ta cần **tải hình ảnh cho OCR**. Aspose.OCR làm việc với `System.Drawing.Image`, vì vậy bất kỳ định dạng nào được GDI+ hỗ trợ (bao gồm TIFF đa trang) đều ổn. + +```csharp + // Step 2: Load the image you want to process + // Replace the path with the location of your TIFF file + var imagePath = @"C:\Invoices\invoice_batch.tif"; + Image image = Image.FromFile(imagePath); +``` + +Nếu bạn đang xử lý một tệp TIFF đa trang, bạn có thể lặp qua các trang bằng `image.SelectActiveFrame`, nhưng trong hầu hết các trường hợp một lần gọi duy nhất là đủ. + +## Bước 3: Thiết Lập Ngôn Ngữ OCR + +Engine không tự động biết bạn đang quét ngôn ngữ nào. **Thiết lập ngôn ngữ OCR** trước khi chạy bộ nhận dạng; nếu không bạn sẽ nhận được rất nhiều kết quả rối rắm. + +```csharp + // Step 3: Tell the engine which language to expect + ocrEngine.Language = OcrLanguage.English; // change to .German, .French, etc. as needed +``` + +> **Bạn có biết?** Thay đổi ngôn ngữ tại thời gian chạy rất nhanh—bạn thậm chí có thể xử lý tài liệu đa ngôn ngữ bằng cách thay đổi thuộc tính này giữa các trang. + +## Bước 4: Thực Hiện Nhận Dạng – Nhận Dạng Văn Bản Từ Hình Ảnh + +Bây giờ là phần thú vị: thực sự **nhận dạng văn bản từ hình ảnh**. Phương thức `Recognize` trả về một chuỗi plain với tất cả các ký tự được phát hiện. + +```csharp + // Step 4: Run OCR and capture the output + string recognizedText = ocrEngine.Recognize(image); +``` + +Nếu bạn cần điểm tin cậy hoặc hộp bao, có thể dùng overload trả về đối tượng `OcrResult`, nhưng đối với hầu hết các tác vụ trích xuất, chuỗi plain là đủ. + +## Bước 5: Trích Xuất Văn Bản Từ TIFF (và xử lý tệp đa trang) + +Khi nguồn là một TIFF chứa nhiều trang, bạn sẽ muốn lặp lại các bước 2‑4 cho mỗi khung. Dưới đây là một vòng lặp nhanh giúp **trích xuất văn bản từ TIFF** trang theo trang: + +```csharp + // Optional: process multi‑page TIFFs + var totalFrames = image.GetFrameCount(FrameDimension.Page); + for (int i = 0; i < totalFrames; i++) + { + image.SelectActiveFrame(FrameDimension.Page, i); + string pageText = ocrEngine.Recognize(image); + Console.WriteLine($"--- Page {i + 1} ---"); + Console.WriteLine(pageText); + } +``` + +Mã trên in ra văn bản đã trích xuất cho mỗi trang, giúp bạn dễ dàng đưa kết quả vào cơ sở dữ liệu hoặc chỉ mục tìm kiếm. + +## Bước 6: Hiển Thị hoặc Lưu Văn Bản Đã Trích Xuất + +Cuối cùng, hãy **hiển thị văn bản đã trích xuất** và tùy chọn ghi nó vào tệp để xử lý sau. + +```csharp + // Step 6: Output the result to console + Console.WriteLine("=== Full OCR Result ==="); + Console.WriteLine(recognizedText); + + // Optional: Save to a .txt file + System.IO.File.WriteAllText(@"C:\Invoices\extracted_text.txt", recognizedText); + } +} +``` + +Chạy chương trình sẽ xuất ra các ký tự đã nhận dạng và tạo tệp `extracted_text.txt` bên cạnh tệp TIFF nguồn của bạn. + +--- + +## Câu Hỏi Thường Gặp & Các Trường Hợp Cạnh + +- **GPU của tôi không được phát hiện thì sao?** + Xóa dòng `GpuDevice`; engine sẽ tự động chuyển sang chế độ CPU. Hiệu năng sẽ chậm hơn nhưng kết quả vẫn chính xác. + +- **Tôi có thể xử lý các tệp PNG hoặc JPEG không?** + Chắc chắn—`Image.FromFile` hoạt động với bất kỳ định dạng nào được System.Drawing hỗ trợ, vì vậy bạn có thể **tải hình ảnh cho OCR** bất kể phần mở rộng. + +- **Làm sao xử lý các bản quét độ phân giải thấp?** + Tăng `ocrEngine.PreprocessOptions.Dpi` trước khi gọi `Recognize`. DPI cao hơn cung cấp cho engine nhiều pixel hơn để làm việc, cải thiện độ chính xác. + +- **Có giới hạn kích thước TIFF không?** + Thuộc tính `GpuMemoryLimit` giới hạn việc sử dụng GPU. Nếu vượt quá giới hạn, engine sẽ chuyển sang CPU cho các trang còn lại. + +--- + +## Kết Luận + +Bạn đã có một đoạn mã hoàn chỉnh, sẵn sàng cho môi trường production, để **nhận dạng văn bản từ hình ảnh** bằng Aspose OCR trong C#. Hướng dẫn đã trình bày cách **tạo engine OCR**, **tải hình ảnh cho OCR**, **thiết lập ngôn ngữ OCR**, và **trích xuất văn bản từ TIFF**—tất cả đều tận dụng tăng tốc GPU để đạt tốc độ cao. + +Từ đây bạn có thể: + +- Thử nghiệm các ngôn ngữ khác (`OcrLanguage.Spanish`, `OcrLanguage.ChineseSimplified`, v.v.). +- Tích hợp đầu ra vào chỉ mục ElasticSearch có thể tìm kiếm. +- Thêm xử lý hậu kỳ (kiểm tra chính tả, làm sạch bằng regex) để nâng cao chất lượng dữ liệu. + +Hãy thử trên lô hoá đơn của bạn, điều chỉnh giới hạn bộ nhớ, và xem hiệu năng OCR tăng vọt. Chúc lập trình vui vẻ! + +## Các Hướng Dẫn Liên Quan + +- [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/) +- [Cách Trích Xuất Văn Bản Từ Hình Ảnh Bằng Cách Chuẩn Bị Các Hình Chữ Nhật Trong OCR](/ocr/english/net/ocr-optimization/prepare-rectangles/) +- [Trích Xuất Văn Bản Từ Hình Ảnh – Nhận Dạng Dòng Với Aspose.OCR](/ocr/english/net/image-and-drawing-recognition/recognize-line/) + +{{< /blocks/products/pf/tutorial-page-section >}} +{{< /blocks/products/pf/main-container >}} +{{< /blocks/products/pf/main-wrap-class >}} +{{< blocks/products/products-backtop-button >}} \ No newline at end of file