[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7C4E3RFZ1DBRPJ8ZP7RFW0Q":3,"skill-same:01M7C4E3RFZ1DBRPJ8ZP7RFW0Q":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7C4E3RFZ1DBRPJ8ZP7RFW0Q","image-ocr",null,"Extract text content from images using Tesseract OCR via Python","linyouxue\u002Fskill-repair-benchmark","linyouxue","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F216151464?v=4","01M7BJEVCXKD74KH6FG9CBVSQB","林宥学","01M7BJEVE02NP217V93BKZFC0J",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002F对于jpg-ocr-stat的尝试\u002Fruns\u002Fjpg-ocr-stat-round-17-r003\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\r\nname: image-ocr\r\ndescription: Extract text content from images using Tesseract OCR via Python\r\n---\r\n\r\n## Mandatory Structured Receipt Field Extraction and Delivery\r\n\r\n1. Preserve field evidence before selecting values\r\n\r\n   For every selected date and amount, retain the original text, field label, source region, recognition source, and reason for accepting or correcting it. Save this evidence with the working results, separately from the prescribed output schema. Compare only candidates for the same field. A value is confirmed only when its field-specific evidence supports it; being non-empty, correctly formatted, frequent, or from a high-confidence page is insufficient. Keep unsupported candidates explicitly unresolved.\r\n\r\n2. Select the final payable amount by its meaning\r\n\r\n   Identify the final payable field before selecting its number. Distinguish it from item prices, subtotals, sales totals, tax amounts, payments received, change, and identifiers; use the amount after applicable taxes, discounts, and rounding. Do not automatically exclude an amount because it includes GST. Select the complete number bound to that field, not simply the last number or latest line. For a next-line fallback, verify the label-to-number association and rule out an intervening field. An unverified association remains unresolved even if it yields a plausible amount.\r\n\r\n3. Parse numbers and dates conservatively and completely\r\n\r\n   Preserve the complete original number and its punctuation. Correct confusable characters or separators only within the confirmed field region, retaining the original reading and the evidence for the correction. Decimal placement or missing digits must be supported by that field: a decimal elsewhere on the page or the token's length is not evidence. Date order and any character correction likewise require date-field context. Never repair an invalid month by modulo, digit truncation, or merely making the date valid. A required interpretation without supporting evidence must stay unresolved and enter local review, not silently become an accepted value.\r\n\r\n4. Review uncertain fields locally\r\n\r\n   Local review is mandatory for missing, conflicting, ambiguous, or weak-fallback-dependent fields, including non-empty fields produced by unsupported digit or date repair. Recognize a crop containing the label and complete value; inspect the original image directly when needed. Resolve uncertainty using that field's semantics, applicable arithmetic relationships, and date context, then record the decision. Clear evidence can settle a field without additional voting. Changing a parser until a plausible value appears is not local review; repeatedly rerunning the entire batch does not resolve a specific uncertainty.\r\n\r\n5. Keep confirmed results stable\r\n\r\n   Keep confirmed fields and their evidence in saved working records. Retries for other fields must preserve them. Stronger same-field evidence may correct a value only with a recorded reason. After changing shared parsing logic, review affected records against their saved evidence and update only justified changes. A new global heuristic must not silently replace previously confirmed values.\r\n\r\n6. Save incrementally and reserve delivery budget\r\n\r\n   After the first extraction pass, save the field records and unresolved items before additional refinement. Retry only fields needing new evidence and apply incremental updates. Reserve time for execution, writing to disk, and verification. Materialize the final workbook from saved records: the saving command must not start another unnecessary full-batch OCR pass. A checkpoint alone is not delivery of the required file.\r\n\r\n7. Confirm completion from the actual deliverable\r\n\r\n   Execute modified scripts and update the target file. Before declaring completion or invoking a finish action, verify that every accepted field has saved supporting evidence and that all weak fallbacks have been reviewed. Reopen the target file and compare every saved row with the confirmed working records; also verify input coverage, format, structure, and ordering. File existence, legal formats, row counts, and printed values alone do not satisfy this check. If any field remains unresolved, use the task's prescribed missing-value representation, disclose the unresolved item, and do not claim extraction is complete. Correct values in logs or memory are not delivered until the actual file has been updated and verified.\r\n\r\n# Image OCR Skill\r\n\r\n## Purpose\r\nThis skill enables accurate text extraction from image files (JPG, PNG, etc.) using Tesseract OCR via the `pytesseract` Python library. It is suitable for scanned documents, screenshots, photos of text, receipts, forms, and other visual content containing text.\r\n\r\n## When to Use\r\n- Extracting text from scanned documents or photos\r\n- Reading text from screenshots or image captures\r\n- Processing batch image files that contain textual information\r\n- Converting visual documents to machine-readable text\r\n- Extracting structured data from forms, receipts, or tables in images\r\n\r\n## Required Libraries\r\n\r\nThe following Python libraries are required:\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport json\r\nimport os\r\n```\r\n\r\n## Input Requirements\r\n- **File formats**: JPG, JPEG, PNG, WEBP\r\n- **Image quality**: Minimum 300 DPI recommended for printed text; clear and legible text\r\n- **File size**: Under 5MB per image (resize if necessary)\r\n- **Text language**: Specify if non-English to improve accuracy\r\n\r\n## Output Schema\r\nAll extracted content must be returned as valid JSON conforming to this schema:\r\n\r\n```json\r\n{\r\n  \"success\": true,\r\n  \"filename\": \"example.jpg\",\r\n  \"extracted_text\": \"Full raw text extracted from the image...\",\r\n  \"confidence\": \"high|medium|low\",\r\n  \"metadata\": {\r\n    \"language_detected\": \"en\",\r\n    \"text_regions\": 3,\r\n    \"has_tables\": false,\r\n    \"has_handwriting\": false\r\n  },\r\n  \"warnings\": [\r\n    \"Text partially obscured in bottom-right corner\",\r\n    \"Low contrast detected in header section\"\r\n  ]\r\n}\r\n```\r\n\r\n\r\n### Field Descriptions\r\n\r\n- `success`: Boolean indicating whether text extraction completed\r\n- `filename`: Original image filename\r\n- `extracted_text`: Complete text content in reading order (top-to-bottom, left-to-right)\r\n- `confidence`: Overall OCR confidence level based on image quality and text clarity\r\n- `metadata.language_detected`: ISO 639-1 language code\r\n- `metadata.text_regions`: Number of distinct text blocks identified\r\n- `metadata.has_tables`: Whether tabular data structures were detected\r\n- `metadata.has_handwriting`: Whether handwritten text was detected\r\n- `warnings`: Array of quality issues or potential errors\r\n\r\n\r\n## Code Examples\r\n\r\n### Basic OCR Extraction\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\n\r\ndef extract_text_from_image(image_path):\r\n    \"\"\"Extract text from a single image using Tesseract OCR.\"\"\"\r\n    img = Image.open(image_path)\r\n    text = pytesseract.image_to_string(img)\r\n    return text.strip()\r\n```\r\n\r\n### OCR with Confidence Data\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\n\r\ndef extract_with_confidence(image_path):\r\n    \"\"\"Extract text with per-word confidence scores.\"\"\"\r\n    img = Image.open(image_path)\r\n\r\n    # Get detailed OCR data including confidence\r\n    data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\r\n\r\n    words = []\r\n    confidences = []\r\n\r\n    for i, word in enumerate(data['text']):\r\n        if word.strip():  # Skip empty strings\r\n            words.append(word)\r\n            confidences.append(data['conf'][i])\r\n\r\n    # Calculate average confidence\r\n    avg_confidence = sum(c for c in confidences if c > 0) \u002F len([c for c in confidences if c > 0]) if confidences else 0\r\n\r\n    return {\r\n        'text': ' '.join(words),\r\n        'average_confidence': avg_confidence,\r\n        'word_count': len(words)\r\n    }\r\n```\r\n\r\n### Full OCR with JSON Output\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport json\r\nimport os\r\n\r\ndef ocr_to_json(image_path):\r\n    \"\"\"Perform OCR and return results as JSON.\"\"\"\r\n    filename = os.path.basename(image_path)\r\n    warnings = []\r\n\r\n    try:\r\n        img = Image.open(image_path)\r\n\r\n        # Get detailed OCR data\r\n        data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\r\n\r\n        # Extract text preserving structure\r\n        text = pytesseract.image_to_string(img)\r\n\r\n        # Calculate confidence\r\n        confidences = [c for c in data['conf'] if c > 0]\r\n        avg_conf = sum(confidences) \u002F len(confidences) if confidences else 0\r\n\r\n        # Determine confidence level\r\n        if avg_conf >= 80:\r\n            confidence = \"high\"\r\n        elif avg_conf >= 50:\r\n            confidence = \"medium\"\r\n        else:\r\n            confidence = \"low\"\r\n            warnings.append(f\"Low OCR confidence: {avg_conf:.1f}%\")\r\n\r\n        # Count text regions (blocks)\r\n        block_nums = set(data['block_num'])\r\n        text_regions = len([b for b in block_nums if b > 0])\r\n\r\n        result = {\r\n            \"success\": True,\r\n            \"filename\": filename,\r\n            \"extracted_text\": text.strip(),\r\n            \"confidence\": confidence,\r\n            \"metadata\": {\r\n                \"language_detected\": \"en\",\r\n                \"text_regions\": text_regions,\r\n                \"has_tables\": False,\r\n                \"has_handwriting\": False\r\n            },\r\n            \"warnings\": warnings\r\n        }\r\n\r\n    except Exception as e:\r\n        result = {\r\n            \"success\": False,\r\n            \"filename\": filename,\r\n            \"extracted_text\": \"\",\r\n            \"confidence\": \"low\",\r\n            \"metadata\": {\r\n                \"language_detected\": \"unknown\",\r\n                \"text_regions\": 0,\r\n                \"has_tables\": False,\r\n                \"has_handwriting\": False\r\n            },\r\n            \"warnings\": [f\"OCR failed: {str(e)}\"]\r\n        }\r\n\r\n    return result\r\n\r\n# Usage\r\nresult = ocr_to_json(\"document.jpg\")\r\nprint(json.dumps(result, indent=2))\r\n```\r\n\r\n### Batch Processing Multiple Images\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport json\r\nimport os\r\nfrom pathlib import Path\r\n\r\ndef process_image_directory(directory_path, output_file):\r\n    \"\"\"Process all images in a directory and save results.\"\"\"\r\n    image_extensions = {'.jpg', '.jpeg', '.png', '.webp'}\r\n    results = []\r\n\r\n    for file_path in sorted(Path(directory_path).iterdir()):\r\n        if file_path.suffix.lower() in image_extensions:\r\n            result = ocr_to_json(str(file_path))\r\n            results.append(result)\r\n            print(f\"Processed: {file_path.name}\")\r\n\r\n    # Save results\r\n    with open(output_file, 'w') as f:\r\n        json.dump(results, f, indent=2)\r\n\r\n    return results\r\n```\r\n\r\n\r\n## Tesseract Configuration Options\r\n\r\n### Language Selection\r\n\r\n```python\r\n# Specify language (default is English)\r\ntext = pytesseract.image_to_string(img, lang='eng')\r\n\r\n# Multiple languages\r\ntext = pytesseract.image_to_string(img, lang='eng+fra+deu')\r\n```\r\n\r\n### Page Segmentation Modes (PSM)\r\n\r\nUse `--psm` to control how Tesseract segments the image:\r\n\r\n```python\r\n# PSM 3: Fully automatic page segmentation (default)\r\ntext = pytesseract.image_to_string(img, config='--psm 3')\r\n\r\n# PSM 4: Assume single column of text\r\ntext = pytesseract.image_to_string(img, config='--psm 4')\r\n\r\n# PSM 6: Assume uniform block of text\r\ntext = pytesseract.image_to_string(img, config='--psm 6')\r\n\r\n# PSM 11: Sparse text - find as much text as possible\r\ntext = pytesseract.image_to_string(img, config='--psm 11')\r\n```\r\n\r\nCommon PSM values:\r\n- `0`: Orientation and script detection (OSD) only\r\n- `3`: Fully automatic page segmentation (default)\r\n- `4`: Single column of text of variable sizes\r\n- `6`: Uniform block of text\r\n- `7`: Single text line\r\n- `11`: Sparse text\r\n- `13`: Raw line\r\n\r\n\r\n## Image Preprocessing\r\n\r\nFor better OCR accuracy, preprocess images:\r\n\r\n```python\r\nfrom PIL import Image, ImageFilter, ImageOps\r\n\r\ndef preprocess_image(image_path):\r\n    \"\"\"Preprocess image for better OCR results.\"\"\"\r\n    img = Image.open(image_path)\r\n\r\n    # Convert to grayscale\r\n    img = img.convert('L')\r\n\r\n    # Increase contrast\r\n    img = ImageOps.autocontrast(img)\r\n\r\n    # Apply slight sharpening\r\n    img = img.filter(ImageFilter.SHARPEN)\r\n\r\n    return img\r\n\r\n# Use preprocessed image for OCR\r\nimg = preprocess_image(\"document.jpg\")\r\ntext = pytesseract.image_to_string(img)\r\n```\r\n\r\n### Advanced Preprocessing Strategies\r\n\r\nFor difficult images (low contrast, faded text, dark backgrounds), try multiple preprocessing approaches:\r\n\r\n1. **Grayscale + Autocontrast** - Basic enhancement for most images\r\n2. **Inverted** - Use `ImageOps.invert()` for dark backgrounds with light text\r\n3. **Scaling** - Upscale small images (e.g., 2x) before OCR to improve character recognition\r\n4. **Thresholding** - Convert to binary using `img.point(lambda p: 255 if p > threshold else 0)` with different threshold values (e.g., 100, 128)\r\n5. **Sharpening** - Apply `ImageFilter.SHARPEN` to improve edge clarity\r\n\r\n\r\n## Multi-Pass OCR Strategy\r\n\r\nFor challenging images, a single OCR pass may miss text. Use multiple passes with different configurations:\r\n\r\n1. **Try multiple PSM modes** - Different page segmentation modes work better for different layouts (e.g., `--psm 6` for blocks, `--psm 4` for columns, `--psm 11` for sparse text)\r\n\r\n2. **Try multiple preprocessing variants** - Run OCR on several preprocessed versions of the same image\r\n\r\n3. **Combine results** - Aggregate text from all passes to maximize extraction coverage\r\n\r\n```python\r\ndef multi_pass_ocr(image_path):\r\n    \"\"\"Run OCR with multiple strategies and combine results.\"\"\"\r\n    img = Image.open(image_path)\r\n    gray = ImageOps.grayscale(img)\r\n\r\n    # Generate preprocessing variants\r\n    variants = [\r\n        ImageOps.autocontrast(gray),\r\n        ImageOps.invert(ImageOps.autocontrast(gray)),\r\n        gray.filter(ImageFilter.SHARPEN),\r\n    ]\r\n\r\n    # PSM modes to try\r\n    psm_modes = ['--psm 6', '--psm 4', '--psm 11']\r\n\r\n    all_text = []\r\n    for variant in variants:\r\n        for psm in psm_modes:\r\n            try:\r\n                text = pytesseract.image_to_string(variant, config=psm)\r\n                if text.strip():\r\n                    all_text.append(text)\r\n            except Exception:\r\n                pass\r\n\r\n    # Combine all extracted text\r\n    return \"\\n\".join(all_text)\r\n```\r\n\r\nThis approach improves extraction for receipts, faded documents, and images with varying quality.\r\n\r\n\r\n## Error Handling\r\n\r\n### Common Issues and Solutions\r\n\r\n**Issue**: Tesseract not found\r\n\r\n```python\r\n# Verify Tesseract is installed\r\ntry:\r\n    pytesseract.get_tesseract_version()\r\nexcept pytesseract.TesseractNotFoundError:\r\n    print(\"Tesseract is not installed or not in PATH\")\r\n```\r\n\r\n**Issue**: Poor OCR quality\r\n\r\n- Preprocess image (grayscale, contrast, sharpen)\r\n- Use appropriate PSM mode for the document type\r\n- Ensure image resolution is sufficient (300+ DPI)\r\n\r\n**Issue**: Empty or garbage output\r\n\r\n- Check if image contains actual text\r\n- Try different PSM modes\r\n- Verify image is not corrupted\r\n\r\n\r\n## Quality Self-Check\r\n\r\nBefore returning results, verify:\r\n\r\n- [ ] Output is valid JSON (use `json.loads()` to validate)\r\n- [ ] All required fields are present (`success`, `filename`, `extracted_text`, `confidence`, `metadata`)\r\n- [ ] Text preserves logical reading order\r\n- [ ] Confidence level reflects actual OCR quality\r\n- [ ] Warnings array includes all detected issues\r\n- [ ] Special characters are properly escaped in JSON\r\n\r\n\r\n## Limitations\r\n\r\n- Tesseract works best with printed text; handwriting recognition is limited\r\n- Accuracy decreases with decorative fonts, artistic text, or extreme stylization\r\n- Mathematical equations and special notation may not extract accurately\r\n- Redacted or watermarked text cannot be recovered\r\n- Severe image degradation (blur, noise, low resolution) reduces accuracy\r\n- Complex multi-column layouts may require custom PSM configuration\r\n\r\n\r\n## Version History\r\n\r\n- **1.0.0** (2026-01-13): Initial release with Tesseract\u002Fpytesseract OCR\r\n","## Mandatory Structured Receipt Field Extraction and Delivery\r\n\r\n1. Preserve field evidence before selecting values\r\n\r\n   For every selected date and amount, retain the original text, field label, source region, recognition source, and reason for accepting or correcting it. Save this evidence with the working results, separately from the prescribed output schema. Compare only candidates for the same field. A value is confirmed only when its field-specific evidence supports it; being non-empty, correctly formatted, frequent, or from a high-confidence page is insufficient. Keep unsupported candidates explicitly unresolved.\r\n\r\n2. Select the final payable amount by its meaning\r\n\r\n   Identify the final payable field before selecting its number. Distinguish it from item prices, subtotals, sales totals, tax amounts, payments received, change, and identifiers; use the amount after applicable taxes, discounts, and rounding. Do not automatically exclude an amount because it includes GST. Select the complete number bound to that field, not simply the last number or latest line. For a next-line fallback, verify the label-to-number association and rule out an intervening field. An unverified association remains unresolved even if it yields a plausible amount.\r\n\r\n3. Parse numbers and dates conservatively and completely\r\n\r\n   Preserve the complete original number and its punctuation. Correct confusable characters or separators only within the confirmed field region, retaining the original reading and the evidence for the correction. Decimal placement or missing digits must be supported by that field: a decimal elsewhere on the page or the token's length is not evidence. Date order and any character correction likewise require date-field context. Never repair an invalid month by modulo, digit truncation, or merely making the date valid. A required interpretation without supporting evidence must stay unresolved and enter local review, not silently become an accepted value.\r\n\r\n4. Review uncertain fields locally\r\n\r\n   Local review is mandatory for missing, conflicting, ambiguous, or weak-fallback-dependent fields, including non-empty fields produced by unsupported digit or date repair. Recognize a crop containing the label and complete value; inspect the original image directly when needed. Resolve uncertainty using that field's semantics, applicable arithmetic relationships, and date context, then record the decision. Clear evidence can settle a field without additional voting. Changing a parser until a plausible value appears is not local review; repeatedly rerunning the entire batch does not resolve a specific uncertainty.\r\n\r\n5. Keep confirmed results stable\r\n\r\n   Keep confirmed fields and their evidence in saved working records. Retries for other fields must preserve them. Stronger same-field evidence may correct a value only with a recorded reason. After changing shared parsing logic, review affected records against their saved evidence and update only justified changes. A new global heuristic must not silently replace previously confirmed values.\r\n\r\n6. Save incrementally and reserve delivery budget\r\n\r\n   After the first extraction pass, save the field records and unresolved items before additional refinement. Retry only fields needing new evidence and apply incremental updates. Reserve time for execution, writing to disk, and verification. Materialize the final workbook from saved records: the saving command must not start another unnecessary full-batch OCR pass. A checkpoint alone is not delivery of the required file.\r\n\r\n7. Confirm completion from the actual deliverable\r\n\r\n   Execute modified scripts and update the target file. Before declaring completion or invoking a finish action, verify that every accepted field has saved supporting evidence and that all weak fallbacks have been reviewed. Reopen the target file and compare every saved row with the confirmed working records; also verify input coverage, format, structure, and ordering. File existence, legal formats, row counts, and printed values alone do not satisfy this check. If any field remains unresolved, use the task's prescribed missing-value representation, disclose the unresolved item, and do not claim extraction is complete. Correct values in logs or memory are not delivered until the actual file has been updated and verified.\r\n\r\n# Image OCR Skill\r\n\r\n## Purpose\r\nThis skill enables accurate text extraction from image files (JPG, PNG, etc.) using Tesseract OCR via the `pytesseract` Python library. It is suitable for scanned documents, screenshots, photos of text, receipts, forms, and other visual content containing text.\r\n\r\n## When to Use\r\n- Extracting text from scanned documents or photos\r\n- Reading text from screenshots or image captures\r\n- Processing batch image files that contain textual information\r\n- Converting visual documents to machine-readable text\r\n- Extracting structured data from forms, receipts, or tables in images\r\n\r\n## Required Libraries\r\n\r\nThe following Python libraries are required:\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport json\r\nimport os\r\n```\r\n\r\n## Input Requirements\r\n- **File formats**: JPG, JPEG, PNG, WEBP\r\n- **Image quality**: Minimum 300 DPI recommended for printed text; clear and legible text\r\n- **File size**: Under 5MB per image (resize if necessary)\r\n- **Text language**: Specify if non-English to improve accuracy\r\n\r\n## Output Schema\r\nAll extracted content must be returned as valid JSON conforming to this schema:\r\n\r\n```json\r\n{\r\n  \"success\": true,\r\n  \"filename\": \"example.jpg\",\r\n  \"extracted_text\": \"Full raw text extracted from the image...\",\r\n  \"confidence\": \"high|medium|low\",\r\n  \"metadata\": {\r\n    \"language_detected\": \"en\",\r\n    \"text_regions\": 3,\r\n    \"has_tables\": false,\r\n    \"has_handwriting\": false\r\n  },\r\n  \"warnings\": [\r\n    \"Text partially obscured in bottom-right corner\",\r\n    \"Low contrast detected in header section\"\r\n  ]\r\n}\r\n```\r\n\r\n\r\n### Field Descriptions\r\n\r\n- `success`: Boolean indicating whether text extraction completed\r\n- `filename`: Original image filename\r\n- `extracted_text`: Complete text content in reading order (top-to-bottom, left-to-right)\r\n- `confidence`: Overall OCR confidence level based on image quality and text clarity\r\n- `metadata.language_detected`: ISO 639-1 language code\r\n- `metadata.text_regions`: Number of distinct text blocks identified\r\n- `metadata.has_tables`: Whether tabular data structures were detected\r\n- `metadata.has_handwriting`: Whether handwritten text was detected\r\n- `warnings`: Array of quality issues or potential errors\r\n\r\n\r\n## Code Examples\r\n\r\n### Basic OCR Extraction\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\n\r\ndef extract_text_from_image(image_path):\r\n    \"\"\"Extract text from a single image using Tesseract OCR.\"\"\"\r\n    img = Image.open(image_path)\r\n    text = pytesseract.image_to_string(img)\r\n    return text.strip()\r\n```\r\n\r\n### OCR with Confidence Data\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\n\r\ndef extract_with_confidence(image_path):\r\n    \"\"\"Extract text with per-word confidence scores.\"\"\"\r\n    img = Image.open(image_path)\r\n\r\n    # Get detailed OCR data including confidence\r\n    data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\r\n\r\n    words = []\r\n    confidences = []\r\n\r\n    for i, word in enumerate(data['text']):\r\n        if word.strip():  # Skip empty strings\r\n            words.append(word)\r\n            confidences.append(data['conf'][i])\r\n\r\n    # Calculate average confidence\r\n    avg_confidence = sum(c for c in confidences if c > 0) \u002F len([c for c in confidences if c > 0]) if confidences else 0\r\n\r\n    return {\r\n        'text': ' '.join(words),\r\n        'average_confidence': avg_confidence,\r\n        'word_count': len(words)\r\n    }\r\n```\r\n\r\n### Full OCR with JSON Output\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport json\r\nimport os\r\n\r\ndef ocr_to_json(image_path):\r\n    \"\"\"Perform OCR and return results as JSON.\"\"\"\r\n    filename = os.path.basename(image_path)\r\n    warnings = []\r\n\r\n    try:\r\n        img = Image.open(image_path)\r\n\r\n        # Get detailed OCR data\r\n        data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)\r\n\r\n        # Extract text preserving structure\r\n        text = pytesseract.image_to_string(img)\r\n\r\n        # Calculate confidence\r\n        confidences = [c for c in data['conf'] if c > 0]\r\n        avg_conf = sum(confidences) \u002F len(confidences) if confidences else 0\r\n\r\n        # Determine confidence level\r\n        if avg_conf >= 80:\r\n            confidence = \"high\"\r\n        elif avg_conf >= 50:\r\n            confidence = \"medium\"\r\n        else:\r\n            confidence = \"low\"\r\n            warnings.append(f\"Low OCR confidence: {avg_conf:.1f}%\")\r\n\r\n        # Count text regions (blocks)\r\n        block_nums = set(data['block_num'])\r\n        text_regions = len([b for b in block_nums if b > 0])\r\n\r\n        result = {\r\n            \"success\": True,\r\n            \"filename\": filename,\r\n            \"extracted_text\": text.strip(),\r\n            \"confidence\": confidence,\r\n            \"metadata\": {\r\n                \"language_detected\": \"en\",\r\n                \"text_regions\": text_regions,\r\n                \"has_tables\": False,\r\n                \"has_handwriting\": False\r\n            },\r\n            \"warnings\": warnings\r\n        }\r\n\r\n    except Exception as e:\r\n        result = {\r\n            \"success\": False,\r\n            \"filename\": filename,\r\n            \"extracted_text\": \"\",\r\n            \"confidence\": \"low\",\r\n            \"metadata\": {\r\n                \"language_detected\": \"unknown\",\r\n                \"text_regions\": 0,\r\n                \"has_tables\": False,\r\n                \"has_handwriting\": False\r\n            },\r\n            \"warnings\": [f\"OCR failed: {str(e)}\"]\r\n        }\r\n\r\n    return result\r\n\r\n# Usage\r\nresult = ocr_to_json(\"document.jpg\")\r\nprint(json.dumps(result, indent=2))\r\n```\r\n\r\n### Batch Processing Multiple Images\r\n\r\n```python\r\nimport pytesseract\r\nfrom PIL import Image\r\nimport json\r\nimport os\r\nfrom pathlib import Path\r\n\r\ndef process_image_directory(directory_path, output_file):\r\n    \"\"\"Process all images in a directory and save results.\"\"\"\r\n    image_extensions = {'.jpg', '.jpeg', '.png', '.webp'}\r\n    results = []\r\n\r\n    for file_path in sorted(Path(directory_path).iterdir()):\r\n        if file_path.suffix.lower() in image_extensions:\r\n            result = ocr_to_json(str(file_path))\r\n            results.append(result)\r\n            print(f\"Processed: {file_path.name}\")\r\n\r\n    # Save results\r\n    with open(output_file, 'w') as f:\r\n        json.dump(results, f, indent=2)\r\n\r\n    return results\r\n```\r\n\r\n\r\n## Tesseract Configuration Options\r\n\r\n### Language Selection\r\n\r\n```python\r\n# Specify language (default is English)\r\ntext = pytesseract.image_to_string(img, lang='eng')\r\n\r\n# Multiple languages\r\ntext = pytesseract.image_to_string(img, lang='eng+fra+deu')\r\n```\r\n\r\n### Page Segmentation Modes (PSM)\r\n\r\nUse `--psm` to control how Tesseract segments the image:\r\n\r\n```python\r\n# PSM 3: Fully automatic page segmentation (default)\r\ntext = pytesseract.image_to_string(img, config='--psm 3')\r\n\r\n# PSM 4: Assume single column of text\r\ntext = pytesseract.image_to_string(img, config='--psm 4')\r\n\r\n# PSM 6: Assume uniform block of text\r\ntext = pytesseract.image_to_string(img, config='--psm 6')\r\n\r\n# PSM 11: Sparse text - find as much text as possible\r\ntext = pytesseract.image_to_string(img, config='--psm 11')\r\n```\r\n\r\nCommon PSM values:\r\n- `0`: Orientation and script detection (OSD) only\r\n- `3`: Fully automatic page segmentation (default)\r\n- `4`: Single column of text of variable sizes\r\n- `6`: Uniform block of text\r\n- `7`: Single text line\r\n- `11`: Sparse text\r\n- `13`: Raw line\r\n\r\n\r\n## Image Preprocessing\r\n\r\nFor better OCR accuracy, preprocess images:\r\n\r\n```python\r\nfrom PIL import Image, ImageFilter, ImageOps\r\n\r\ndef preprocess_image(image_path):\r\n    \"\"\"Preprocess image for better OCR results.\"\"\"\r\n    img = Image.open(image_path)\r\n\r\n    # Convert to grayscale\r\n    img = img.convert('L')\r\n\r\n    # Increase contrast\r\n    img = ImageOps.autocontrast(img)\r\n\r\n    # Apply slight sharpening\r\n    img = img.filter(ImageFilter.SHARPEN)\r\n\r\n    return img\r\n\r\n# Use preprocessed image for OCR\r\nimg = preprocess_image(\"document.jpg\")\r\ntext = pytesseract.image_to_string(img)\r\n```\r\n\r\n### Advanced Preprocessing Strategies\r\n\r\nFor difficult images (low contrast, faded text, dark backgrounds), try multiple preprocessing approaches:\r\n\r\n1. **Grayscale + Autocontrast** - Basic enhancement for most images\r\n2. **Inverted** - Use `ImageOps.invert()` for dark backgrounds with light text\r\n3. **Scaling** - Upscale small images (e.g., 2x) before OCR to improve character recognition\r\n4. **Thresholding** - Convert to binary using `img.point(lambda p: 255 if p > threshold else 0)` with different threshold values (e.g., 100, 128)\r\n5. **Sharpening** - Apply `ImageFilter.SHARPEN` to improve edge clarity\r\n\r\n\r\n## Multi-Pass OCR Strategy\r\n\r\nFor challenging images, a single OCR pass may miss text. Use multiple passes with different configurations:\r\n\r\n1. **Try multiple PSM modes** - Different page segmentation modes work better for different layouts (e.g., `--psm 6` for blocks, `--psm 4` for columns, `--psm 11` for sparse text)\r\n\r\n2. **Try multiple preprocessing variants** - Run OCR on several preprocessed versions of the same image\r\n\r\n3. **Combine results** - Aggregate text from all passes to maximize extraction coverage\r\n\r\n```python\r\ndef multi_pass_ocr(image_path):\r\n    \"\"\"Run OCR with multiple strategies and combine results.\"\"\"\r\n    img = Image.open(image_path)\r\n    gray = ImageOps.grayscale(img)\r\n\r\n    # Generate preprocessing variants\r\n    variants = [\r\n        ImageOps.autocontrast(gray),\r\n        ImageOps.invert(ImageOps.autocontrast(gray)),\r\n        gray.filter(ImageFilter.SHARPEN),\r\n    ]\r\n\r\n    # PSM modes to try\r\n    psm_modes = ['--psm 6', '--psm 4', '--psm 11']\r\n\r\n    all_text = []\r\n    for variant in variants:\r\n        for psm in psm_modes:\r\n            try:\r\n                text = pytesseract.image_to_string(variant, config=psm)\r\n                if text.strip():\r\n                    all_text.append(text)\r\n            except Exception:\r\n                pass\r\n\r\n    # Combine all extracted text\r\n    return \"\\n\".join(all_text)\r\n```\r\n\r\nThis approach improves extraction for receipts, faded documents, and images with varying quality.\r\n\r\n\r\n## Error Handling\r\n\r\n### Common Issues and Solutions\r\n\r\n**Issue**: Tesseract not found\r\n\r\n```python\r\n# Verify Tesseract is installed\r\ntry:\r\n    pytesseract.get_tesseract_version()\r\nexcept pytesseract.TesseractNotFoundError:\r\n    print(\"Tesseract is not installed or not in PATH\")\r\n```\r\n\r\n**Issue**: Poor OCR quality\r\n\r\n- Preprocess image (grayscale, contrast, sharpen)\r\n- Use appropriate PSM mode for the document type\r\n- Ensure image resolution is sufficient (300+ DPI)\r\n\r\n**Issue**: Empty or garbage output\r\n\r\n- Check if image contains actual text\r\n- Try different PSM modes\r\n- Verify image is not corrupted\r\n\r\n\r\n## Quality Self-Check\r\n\r\nBefore returning results, verify:\r\n\r\n- [ ] Output is valid JSON (use `json.loads()` to validate)\r\n- [ ] All required fields are present (`success`, `filename`, `extracted_text`, `confidence`, `metadata`)\r\n- [ ] Text preserves logical reading order\r\n- [ ] Confidence level reflects actual OCR quality\r\n- [ ] Warnings array includes all detected issues\r\n- [ ] Special characters are properly escaped in JSON\r\n\r\n\r\n## Limitations\r\n\r\n- Tesseract works best with printed text; handwriting recognition is limited\r\n- Accuracy decreases with decorative fonts, artistic text, or extreme stylization\r\n- Mathematical equations and special notation may not extract accurately\r\n- Redacted or watermarked text cannot be recovered\r\n- Severe image degradation (blur, noise, low resolution) reduces accuracy\r\n- Complex multi-column layouts may require custom PSM configuration\r\n\r\n\r\n## Version History\r\n\r\n- **1.0.0** (2026-01-13): Initial release with Tesseract\u002Fpytesseract OCR\r\n",{"name":5,"description":7},"main","cdcb6d230f3b15c3c33f8a2bdd16439f43602cbe","evaluation\u002Fresults\u002F对于jpg-ocr-stat的尝试\u002Fruns\u002Fjpg-ocr-stat-round-17-r003\u002Finputs\u002Fskills\u002Fimage-ocr",1,"https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark","https:\u002F\u002Fgithub.com\u002Flinyouxue","2026-11-14 20:28:35",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add linyouxue\u002Fskill-repair-benchmark --skill image-ocr",{"tool":37,"command":38},"bunx","bunx skills add linyouxue\u002Fskill-repair-benchmark --skill image-ocr",{"tool":40,"command":41},"pnpm","pnpm dlx skills add linyouxue\u002Fskill-repair-benchmark --skill image-ocr","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fevaluation\u002Fresults\u002F对于jpg-ocr-stat的尝试\u002Fruns\u002Fjpg-ocr-stat-round-17-r003\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",true,[],[46,53,60,66,71,76],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":19},"01M7E1HGVRY73NBJ022CJG13X6","video-frame-extraction","Extract frames from video files and save them as images using OpenCV","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":19},"01M7E1HAG5R7CJ9C8NYJS771MB","openai-vision","Analyze images and multi-frame sequences using OpenAI GPT vision models","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":61,"name":5,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7E1H7DADKB6QBWKC2KQ63SZ","Extract text content from images using Tesseract OCR via Python, including structured field extraction from receipts and forms","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_03\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[],{"skillNo":67,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":19},"01M7E1H0WBNT43TENGQY7AVZHD","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fvideo-frame-extraction\u002FSKILL.md",[],[],{"skillNo":72,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M7E1GTC7D4N4Q2EF03875J9E","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fopenai-vision\u002FSKILL.md",[],[],{"skillNo":77,"name":5,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7E1GQ92CWFMGH53KSSE4WER","https:\u002F\u002Fgithub.com\u002Flinyouxue\u002Fskill-repair-benchmark\u002Fblob\u002Fmain\u002Fjpg-ocr-stat\u002Fresult\u002Fskilltta-claude4.7\u002Fgroup_03\u002Frun_02\u002Finputs\u002Fskills\u002Fimage-ocr\u002FSKILL.md",[],[]]