Extracting Text and Information from Screenshots

Ma Mahalakshmi V Updated 16 Sep 2026
6 min read ·Lesson 99 of 224

Vision Models as an OCR Alternative

Optical character recognition (OCR) is the general term for pulling text out of an image. Traditional OCR engines work by detecting character shapes and matching them against known glyphs, which works well on clean, high-contrast, well-aligned text but tends to struggle with UI screenshots, handwriting, skewed photos, or dense mixed layouts like invoices and forms.

A vision-capable language model approaches the same problem differently: instead of only recognizing character shapes, it interprets the image the way a person would, understanding layout and context alongside the literal text. This makes it noticeably more capable at tasks like "read the total on this receipt" or "what does the error dialog say," because the model isn't just transcribing characters — it's also reasoning about which piece of text on the screen actually answers your question. This is genuinely new ground beyond what Unit 7 introduced: there, you learned how to attach an image at all; here, you use that capability specifically to pull structured, targeted information out of dense visual text.

A Basic Screenshot Extraction Example

import base64
from openai import OpenAI

client = OpenAI()


def encode_image(path: str) -> str:
    with open(path, "rb") as f:
        return base64.b64encode(f.read()).decode("utf-8")


image_b64 = encode_image("screenshots/error_dialog.png")

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "Transcribe all visible text in this screenshot exactly as it appears, preserving line breaks.",
                },
                {
                    "type": "input_image",
                    "image_url": f"data:image/png;base64,{image_b64}",
                    "detail": "high",
                },
            ],
        }
    ],
)

print(response.output_text)

Two details matter here that are specific to text-heavy images:

  • detail is explicitly set to "high". Text extraction is exactly the kind of task that benefits from higher resolution processing, because small or dense text is the first thing lost when an image is downscaled. Leaving this at a low or default setting on a text-dense screenshot is one of the most common causes of missed or garbled words.
  • The instruction asks for an exact transcription "preserving line breaks." Vision models, like text models, respond to how precisely you phrase the task. A vague instruction like "what does this say?" invites a summarized or paraphrased answer. If you need a faithful transcription rather than a summary, say so explicitly.

Extracting Specific Fields Instead of Full Text

Often you don't want the entire screen transcribed — you want particular fields, the way you'd extract data from a form. You can ask directly:

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": (
                        "This is a screenshot of an online order confirmation. "
                        "Extract only: order number, total price, and estimated delivery date. "
                        "If a field is not visible, respond with 'not found' for that field."
                    ),
                },
                {
                    "type": "input_image",
                    "image_url": f"data:image/png;base64,{image_b64}",
                    "detail": "high",
                },
            ],
        }
    ],
)

print(response.output_text)

The instruction to respond with "not found" for missing fields is deliberate and important. Without it, a model asked to extract a field that isn't actually present in the image may guess at a plausible-looking value rather than admit the field is absent — this is a form of hallucination, and it is far more dangerous in a data-extraction pipeline than a model simply saying it doesn't know. Explicitly telling the model what to do when information is missing closes off that failure mode and produces more trustworthy pipelines. (You'll take this further in Lesson 6, where structured output formats make missing fields impossible to represent ambiguously in the first place.)

Handling Dense or Tabular Content

Screenshots of tables, spreadsheets, or dashboards are harder than a single receipt because the spatial relationship between values matters — a number means nothing without knowing which row and column it belongs to. Give the model that structure explicitly in your instructions rather than assuming it will infer the ideal output format on its own:

response = client.responses.create(
    model="gpt-5.6-terra",
    input=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": (
                        "This screenshot shows a table of monthly expenses. "
                        "Reproduce it as a Markdown table with the same columns and rows. "
                        "If a cell is unreadable, write 'unclear' in that cell instead of guessing."
                    ),
                },
                {
                    "type": "input_image",
                    "image_url": f"data:image/png;base64,{image_b64}",
                    "detail": "high",
                },
            ],
        }
    ],
)

print(response.output_text)

Asking for a specific output format ("a Markdown table with the same columns and rows") gives the model a concrete target structure to preserve, rather than leaving it to decide how to linearize two-dimensional information into text — a decision that, left unconstrained, different runs might make differently. The "unclear" instruction serves the same anti-hallucination purpose as "not found" did in the previous example, adapted for a per-cell context.

When Screenshot Extraction Is the Wrong Tool

Vision-based extraction is not the right approach when:

  • You control the data's original source. If a screenshot is being taken of a web page your own application rendered, it is almost always better to read the underlying data directly (from your database, your API response, the DOM) rather than round-tripping it through an image and asking a model to read it back out. This is faster, cheaper, and immune to misreading.
  • You need guaranteed, deterministic accuracy on every character, such as extracting a legal document's exact wording for a compliance system. Vision models are highly capable but not infallible; a single misread digit in a legal or financial field can have serious consequences, and outputs should be validated or reviewed rather than trusted blindly in high-stakes settings.
  • The image quality is too degraded for any method to read reliably — extreme blur, extreme low resolution, or heavy compression artifacts. No extraction technique, human or automated, can recover information that the image no longer visually contains (see Lesson 8 for more on quality limitations).

Common Mistakes

Leaving detail at a low or default setting for text-dense images, which silently degrades the model's ability to read small text, producing plausible-looking but subtly wrong transcriptions rather than an obvious failure. Always use detail="high" for screenshots and documents where exact text matters.

Asking an open-ended question instead of specifying the exact fields needed, which causes the model to decide on its own what's "important" to report, often omitting a field your downstream code actually depends on. Always name the exact fields or format you expect back.

Not instructing the model on what to do with missing or unclear information, which leaves the door open to confident-sounding guesses standing in for genuinely absent data. Always give an explicit instruction such as "write 'not found'" for fields that might not be present.

Best Practices

Crop or highlight the relevant region before sending the image when possible, especially for large screenshots where only a small part is relevant — this reduces ambiguity and often improves accuracy more than any prompt wording change would.

Always request an explicit fallback value for missing data ("not found," "unclear," null) rather than leaving the model free to decide how to represent absence.

Treat extracted text as untrusted input until validated, especially for numbers that feed into calculations or fields that trigger downstream actions — apply the same sanity checks you would to any OCR pipeline, such as format validation on dates, currency amounts, or IDs.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Extracting Text and Information from Screenshots and get answers drawn from it.

Signed-in readers only.