Code From Image
Overview
Extract code, pseudocode, or algorithmic descriptions from images using OCR tools, then interpret and implement the extracted content as working code. This skill addresses the challenges of noisy OCR output, ambiguous character recognition, and verification of implementation correctness.
Workflow
Phase 1: Environment Setup
Before attempting OCR extraction:
Install OCR dependencies - Ensure tesseract and Python bindings are available:
# Check for existing tools
which tesseract
# Install if needed
apt-get install tesseract-ocr # or equivalent for the system
pip install pytesseract pillow
Install image processing tools - For preprocessing capabilities:
pip install opencv-python
# ImageMagick for command-line preprocessing
apt-get install imagemagick
Phase 2: Image Preprocessing
Raw OCR on unprocessed images often produces noisy output. Apply preprocessing to improve accuracy:
- Assess image quality - Check contrast, resolution, and clarity before OCR
- Apply preprocessing techniques:
- Convert to grayscale
- Increase contrast
- Apply thresholding (binary or adaptive)
- Resize if resolution is low
- Denoise if needed
Example preprocessing pipeline:
import cv2
from PIL import Image
# Load and preprocess
img = cv2.imread('code_image.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Increase contrast
contrast = cv2.convertScaleAbs(gray, alpha=1.5, beta=0)
# Apply threshold
_, thresh = cv2.threshold(contrast, 127, 255, cv2.THRESH_BINARY)
# Save preprocessed image
cv2.imwrite('preprocessed.png', thresh)
- Try multiple preprocessing configurations - Different images respond better to different techniques
Phase 3: OCR Extraction
Run OCR with multiple configurations:
import pytesseract
from PIL import Image
# Try different PSM modes for code-like content
# PSM 6: Assume uniform block of text
# PSM 4: Assume single column of variable sizes
text_psm6 = pytesseract.image_to_string(Image.open('preprocessed.png'), config='--psm 6')
text_psm4 = pytesseract.image_to_string(Image.open('preprocessed.png'), config='--psm 4')
Compare outputs - Different configurations may capture different parts correctly
Document raw OCR output - Keep the original OCR text for reference when making interpretations
Phase 4: Interpreting Noisy OCR Output
OCR output from code images is frequently corrupted. Apply systematic interpretation:
Identify common OCR errors:
0 (zero) ↔ O (letter O)
1 (one) ↔ l (lowercase L) ↔ I (uppercase i)
6 appearing before text (often a misread character)
- Missing or extra spaces
- Special characters corrupted (
= → -, " → ', etc.)
- Variable names partially corrupted
Document all assumptions - When interpreting ambiguous OCR:
- State what the OCR produced
- State what interpretation is being made
- Explain the reasoning
Look for structural patterns:
- Assignment statements (look for
= patterns)
- Function calls (parentheses patterns)
- Loop structures (indentation, keywords)
- Common programming constructs
Cross-reference with context:
- Variable naming conventions
- Expected operations based on the task
- Programming language syntax rules
Phase 5: Implementation with Verification
When a verification hint or expected output is available:
Implement the interpreted code
Test against expected output - If a hint like "output starts with X" is provided:
- Run the implementation
- Check if output matches the hint
- If not, revisit interpretations
Try alternative interpretations systematically:
- When initial implementation fails verification
- Create a list of ambiguous interpretations
- Test each alternative methodically
- Example alternatives to consider:
- String encoding (bytes vs string)
- Slice notation (characters vs bytes, 0-indexed vs 1-indexed)
- Concatenation order
- Hash output format (hex digest vs raw digest)
Document the working interpretation - Once verified, explain which interpretation worked and why
Common Pitfalls
OCR Quality Issues
- Mistake: Accepting noisy OCR output without improvement attempts
- Solution: Always try image preprocessing before OCR; compare multiple OCR configurations
Undocumented Assumptions
- Mistake: Making silent assumptions about corrupted characters
- Solution: Explicitly document each interpretation decision with reasoning
Single Interpretation Fixation
- Mistake: Committing to one interpretation without exploring alternatives
- Solution: When verification fails, systematically test alternative readings of ambiguous text
Missing Edge Case Considerations
- Mistake: Not considering encoding, indexing, or format variations
- Solution: When working with:
- Strings: Consider bytes vs unicode, encoding schemes
- Slices: Consider byte slices vs character slices, hex vs raw
- Hashes: Consider digest() vs hexdigest(), truncation points
Inefficient Tool Setup
- Mistake: Installing tools one at a time, checking availability repeatedly
- Solution: Consolidate tool checks and installations at the start
Verification Strategies
Use hints strategically - If output hints are provided, use them to validate interpretations early, not just for final verification
Test intermediate results - For multi-step algorithms, verify intermediate values when possible
Compare multiple OCR outputs - Run OCR with different settings and compare results to identify reliable vs uncertain portions
Sanity check interpretations - Does the interpreted code make logical sense? Are variable names reasonable? Is the algorithm plausible?
Resources
Refer to references/ocr_best_practices.md for detailed guidance on OCR configuration options and image preprocessing techniques.
1---2name: code-from-image3description: Extracting code or pseudocode from images using OCR, then interpreting and implementing it. This skill should be used when tasks involve reading code, pseudocode, or algorithms from image files (PNG, JPG, screenshots) and converting them to executable code. Applies to OCR-based code extraction, image-to-code conversion, and implementing algorithms shown in visual formats.4---56# Code From Image78## Overview910Extract code, pseudocode, or algorithmic descriptions from images using OCR tools, then interpret and implement the extracted content as working code. This skill addresses the challenges of noisy OCR output, ambiguous character recognition, and verification of implementation correctness.1112## Workflow1314### Phase 1: Environment Setup1516Before attempting OCR extraction:17181. **Install OCR dependencies** - Ensure tesseract and Python bindings are available:19 ```bash20 # Check for existing tools21 which tesseract22 # Install if needed23 apt-get install tesseract-ocr # or equivalent for the system24 pip install pytesseract pillow25 ```26272. **Install image processing tools** - For preprocessing capabilities:28 ```bash29 pip install opencv-python30 # ImageMagick for command-line preprocessing31 apt-get install imagemagick32 ```3334### Phase 2: Image Preprocessing3536Raw OCR on unprocessed images often produces noisy output. Apply preprocessing to improve accuracy:37381. **Assess image quality** - Check contrast, resolution, and clarity before OCR392. **Apply preprocessing techniques**:40 - Convert to grayscale41 - Increase contrast42 - Apply thresholding (binary or adaptive)43 - Resize if resolution is low44 - Denoise if needed4546Example preprocessing pipeline:47```python48import cv249from PIL import Image5051# Load and preprocess52img = cv2.imread('code_image.png')53gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)54# Increase contrast55contrast = cv2.convertScaleAbs(gray, alpha=1.5, beta=0)56# Apply threshold57_, thresh = cv2.threshold(contrast, 127, 255, cv2.THRESH_BINARY)58# Save preprocessed image59cv2.imwrite('preprocessed.png', thresh)60```61623. **Try multiple preprocessing configurations** - Different images respond better to different techniques6364### Phase 3: OCR Extraction65661. **Run OCR with multiple configurations**:67 ```python68 import pytesseract69 from PIL import Image7071 # Try different PSM modes for code-like content72 # PSM 6: Assume uniform block of text73 # PSM 4: Assume single column of variable sizes74 text_psm6 = pytesseract.image_to_string(Image.open('preprocessed.png'), config='--psm 6')75 text_psm4 = pytesseract.image_to_string(Image.open('preprocessed.png'), config='--psm 4')76 ```77782. **Compare outputs** - Different configurations may capture different parts correctly79803. **Document raw OCR output** - Keep the original OCR text for reference when making interpretations8182### Phase 4: Interpreting Noisy OCR Output8384OCR output from code images is frequently corrupted. Apply systematic interpretation:85861. **Identify common OCR errors**:87 - `0` (zero) ↔ `O` (letter O)88 - `1` (one) ↔ `l` (lowercase L) ↔ `I` (uppercase i)89 - `6` appearing before text (often a misread character)90 - Missing or extra spaces91 - Special characters corrupted (`=` → `-`, `"` → `'`, etc.)92 - Variable names partially corrupted93942. **Document all assumptions** - When interpreting ambiguous OCR:95 - State what the OCR produced96 - State what interpretation is being made97 - Explain the reasoning98993. **Look for structural patterns**:100 - Assignment statements (look for `=` patterns)101 - Function calls (parentheses patterns)102 - Loop structures (indentation, keywords)103 - Common programming constructs1041054. **Cross-reference with context**:106 - Variable naming conventions107 - Expected operations based on the task108 - Programming language syntax rules109110### Phase 5: Implementation with Verification111112When a verification hint or expected output is available:1131141. **Implement the interpreted code**1151162. **Test against expected output** - If a hint like "output starts with X" is provided:117 - Run the implementation118 - Check if output matches the hint119 - If not, revisit interpretations1201213. **Try alternative interpretations systematically**:122 - When initial implementation fails verification123 - Create a list of ambiguous interpretations124 - Test each alternative methodically125 - Example alternatives to consider:126 - String encoding (bytes vs string)127 - Slice notation (characters vs bytes, 0-indexed vs 1-indexed)128 - Concatenation order129 - Hash output format (hex digest vs raw digest)1301314. **Document the working interpretation** - Once verified, explain which interpretation worked and why132133## Common Pitfalls134135### OCR Quality Issues136- **Mistake**: Accepting noisy OCR output without improvement attempts137- **Solution**: Always try image preprocessing before OCR; compare multiple OCR configurations138139### Undocumented Assumptions140- **Mistake**: Making silent assumptions about corrupted characters141- **Solution**: Explicitly document each interpretation decision with reasoning142143### Single Interpretation Fixation144- **Mistake**: Committing to one interpretation without exploring alternatives145- **Solution**: When verification fails, systematically test alternative readings of ambiguous text146147### Missing Edge Case Considerations148- **Mistake**: Not considering encoding, indexing, or format variations149- **Solution**: When working with:150 - Strings: Consider bytes vs unicode, encoding schemes151 - Slices: Consider byte slices vs character slices, hex vs raw152 - Hashes: Consider digest() vs hexdigest(), truncation points153154### Inefficient Tool Setup155- **Mistake**: Installing tools one at a time, checking availability repeatedly156- **Solution**: Consolidate tool checks and installations at the start157158## Verification Strategies1591601. **Use hints strategically** - If output hints are provided, use them to validate interpretations early, not just for final verification1611622. **Test intermediate results** - For multi-step algorithms, verify intermediate values when possible1631643. **Compare multiple OCR outputs** - Run OCR with different settings and compare results to identify reliable vs uncertain portions1651664. **Sanity check interpretations** - Does the interpreted code make logical sense? Are variable names reasonable? Is the algorithm plausible?167168## Resources169170Refer to `references/ocr_best_practices.md` for detailed guidance on OCR configuration options and image preprocessing techniques.