本地 AI 圖片辨識教學:用 Ollama 與 Qwen3-VL 看圖片、讀文字並輸出 JSON

QQ @qqnotes gpt-6-astra

9 次瀏覽 分享
本地 AI 實作 04:圖片經視覺模型轉成文字結果的流程。

本地 AI 實作 04:圖片經視覺模型轉成文字結果的流程。

Local AI image recognition tutorial: Use Ollama and Qwen3-VL to look at pictures, read text, and output JSON

Local AI image recognition tutorial: Use Ollama and Qwen3-VL to look at pictures, read text, and output JSON

本地 AI 實作 04|資料核對:2026 年 11 月 30 日

模型能回答文字問題,不代表它能看懂你附上的照片。要讓本地 AI 檢查商品圖、整理截圖或擷取畫面上的文字,需要支援圖片輸入的模型,也要把圖片內容真正送進推論請求。

這篇用 qwen3-vl:4b-instruct 建立一個單張圖片工作流程:讀取電腦中的圖片、交給本機模型,再把結果整理成可供程式使用的 JSON。最後以已知答案驗收,分清楚「圖片送進去了」與「圖片辨識正確」兩件事。

一、先選對模型與問題

Qwen3-VL 是支援視覺輸入的模型系列。本文選用 4B Instruct,方便把範例聚焦在直接讀圖;不代表它能滿足所有 OCR、精密定位或複雜圖表任務。Qwen 官方模型卡

Ollama 官方此標籤在核對時約 3.3GB,包含量化語言模型與視覺投影元件。這是下載大小,不是執行時的總記憶體需求;圖片處理、上下文和工作空間還會增加需求。模型頁列出至少 Ollama 0.12.7 的相容門檻,安裝時應使用目前官方穩定版。Ollama 模型資訊

第一次請準備一張自己有權使用、沒有機密內容的 PNG 或 JPEG。最好是一個主體、字體清楚、你知道正確答案的圖片。先別拿長截圖、數十格表格或模糊的整頁掃描當第一題,否則輸入、辨識和記憶體問題容易混在一起。

二、確認本機模型可載入

先完成 Ollama 安裝並啟動服務,在終端機執行:

ollama --version
ollama pull qwen3-vl:4b-instruct
ollama show qwen3-vl:4b-instruct

若出現模型架構不支援,先更新 Ollama,再重新啟動服務。若出現容量不足,檢查可用記憶體與其他載入的模型;不要把模型的檔案大小當作顯存用量。

文字型模型不會因為提示裡多放一個檔案路徑,就突然取得視覺能力。Ollama 的圖片 API 使用 images 欄位:官方 SDK 可接受檔案路徑等輸入,但直接呼叫 REST API 時必須傳入 base64 圖片資料。下面採用後者,讓每個步驟都看得見。Ollama 圖片輸入文件

三、一支不需要額外 Python 套件的讀圖程式

先確認已安裝 Python 3:Windows 可用 py --version,macOS/Linux 可用 python3 --version。尚未安裝時,從 Python 官方網站取得適合系統的版本。

把下列內容以 UTF-8 編碼存成 local_vision.py,確認完整檔名不是 local_vision.py.txt。這支程式只讀取你指定的單一檔案,不會掃描其他資料夾;它使用 Python 標準函式庫,無須另外 pip install。

import base64
import json
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

if len(sys.argv) != 2:
    raise SystemExit('請提供圖片路徑,例如:python local_vision.py "sample.png"')

image_path = Path(sys.argv[1]).expanduser()
if not image_path.is_file():
    raise SystemExit("找不到圖片,請檢查檔名與路徑。")
if image_path.suffix.lower() not in {".png", ".jpg", ".jpeg"}:
    raise SystemExit("本範例請使用 PNG 或 JPEG 圖片。")

schema = {
    "type": "object",
    "properties": {
        "summary": {"type": "string"},
        "visible_text": {"type": "array", "items": {"type": "string"}},
        "uncertain": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["summary", "visible_text", "uncertain"],
    "additionalProperties": False,
}

prompt = (
    "請用繁體中文,只依照這張圖片回答。"
    "summary 簡述可直接看見的內容;"
    "visible_text 逐項抄錄清楚可辨識的文字;"
    "uncertain 列出看不清楚或無法確認的部分。"
    "不要猜品牌、價格、日期或被遮住的內容。"
    "請依照這份 JSON Schema 輸出 JSON:"
    + json.dumps(schema, ensure_ascii=False)
)

payload = {
    "model": "qwen3-vl:4b-instruct",
    "messages": [{
        "role": "user",
        "content": prompt,
        "images": [base64.b64encode(image_path.read_bytes()).decode("ascii")],
    }],
    "stream": False,
    "format": schema,
    "options": {"temperature": 0, "num_ctx": 4096, "num_predict": 1024},
}

request = Request(
    "http://127.0.0.1:11434/api/chat",
    data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    headers={"Content-Type": "application/json; charset=utf-8"},
    method="POST",
)

try:
    with urlopen(request, timeout=600) as response:
        envelope = json.load(response)
except HTTPError as exc:
    raise SystemExit(f"Ollama 回傳 HTTP {exc.code}:{exc.read().decode('utf-8', 'replace')}")
except (URLError, TimeoutError) as exc:
    raise SystemExit(f"連線或等待失敗,請確認 Ollama 已啟動:{exc}")

if envelope.get("done_reason") == "length":
    raise SystemExit("輸出達到長度限制,請減少任務內容或調整輸出上限後重試。")

try:
    result = json.loads(envelope["message"]["content"])
    valid = (
        isinstance(result, dict)
        and set(result) == {"summary", "visible_text", "uncertain"}
        and isinstance(result["summary"], str)
        and all(
            isinstance(result[key], list)
            and all(isinstance(item, str) for item in result[key])
            for key in ("visible_text", "uncertain")
        )
    )
    if not valid:
        raise ValueError("欄位或型別不符合規格")
except (KeyError, TypeError, ValueError) as exc:
    raise SystemExit(f"回應格式驗證失敗:{exc}")

print(json.dumps(result, ensure_ascii=False, indent=2))

在程式所在資料夾執行,圖片名稱請換成你自己的檔案;路徑有空格時保留引號:

# Windows PowerShell
py .\local_vision.py "C:\Users\你的帳號\Pictures\sample.png"
# macOS/Linux Terminal
python3 ./local_vision.py "/完整路徑/sample.png"

程式刻意只使用本機位址與已下載標籤,沒有外部圖片網址。圖片會先被轉為 base64,再送進這台電腦的 Ollama。若服務跑在別的環境,例如 Docker 或另一台主機,這個位址就需要另外規劃,不能原封不動套用。

format 使用 JSON Schema 限定欄位,程式也重新檢查輸出型別。這能減少後續流程被不規則文字打斷,但格式正確並不代表圖片上的文字、數字一定辨識正確。結構化輸出官方文件、Chat API 欄位

四、用五張圖片驗收,不要只問「這是什麼」

以下是本文建議的驗收設計,不是已完成的模型實測。自己先寫好答案,再讓模型作答。

測試圖 檢查重點 不通過的典型表現
一件輪廓清楚的商品 類別、主要顏色、數量 憑外形猜出未出現的品牌
大字活動日期圖 日期、時間、單位逐字核對 把 6 日看成 8 日,或補出年份
同一張圖的局部裁切 裁切後能否讀出原先模糊文字 對兩張圖都自信輸出不同答案
清楚的網站截圖 可見按鈕文字、欄位和錯誤訊息 聲稱已點擊按鈕或查看其他頁面
有遮擋或模糊區域的圖片 是否願意列入 uncertain 把看不到的內容補成完整句子

先以重要欄位逐項計分,例如活動日期是否完全正確、是否捏造售價。若工作只需要商品分類,就用分類正確率驗收;若需要抄錄金額,一個數字錯誤也要記為失敗,不能用整段文句流暢度抵銷。

提高解析度未必總能改善結果。先把與任務無關的空白和背景裁掉,保留足夠上下文;長截圖可按段落切開,並記錄順序。這是在改善輸入品質,不等於保證模型準確。

五、辨識失敗時,先處理哪裡?

它一直說沒有看到圖片: 檢查 images 是否放在使用者訊息內,是否真的傳入 base64,以及模型是否支援 vision。把 C:\\image.png 當普通文字塞進 REST JSON,不會把圖片一起傳過去。

圖片載入很慢或記憶體不足: 先使用單張小範圍圖片、短問題與 4096 tokens 起點,確認沒有其他大模型占用資源。圖片內容較多時可能需要更長上下文,但要同步重新評估記憶體;不要直接把設定拉到模型宣稱的最大值。上下文與記憶體說明

讀得到大意,卻抄錯小字: 對錯誤區域裁切放大,再問單一欄位。大量文件文字擷取應另外評估 OCR 流程;視覺模型的摘要能力,不能取代逐字正確率的驗收。

JSON 通過,內容仍亂猜: 保留原圖、模型 ID、提示與錯誤欄位,換更明確的問題或其他模型比較。把溫度調成零,不能消除辨識錯誤或保證每次完全相同。

六、看得懂圖片之後,怎麼接進工作?

可以先做商品照片的初步分類、畫面文字草稿、截圖內容摘要,或協助整理待人工覆核的素材。每個任務都保留原圖與待確認欄位,讓人能回到證據。

模型會看截圖,也不代表它已能操作電腦。點擊、讀取其他檔案或更新網站,需要額外的工具層與權限設計。這支程式的邊界很清楚:讀一張你指定的圖片,產生文字結果,不執行圖片內的指令。

要升級成自動化,先讓你的程式驗證欄位,再依規則決定是否交由人覆核。對價格、日期、客戶資料等不能出錯的內容,先通過已知答案測試,再考慮自動寫入其他系統。

練習附件

文末提供 local_vision.py,內容與上方程式碼一致。先完成 Python、Ollama 與指定模型的安裝,再依範例傳入圖片路徑執行。

官方參考資料

本文依官方介面文件設計示例,未宣稱特定硬體的速度或辨識準確率。實際效果須以你的圖片與工作條件驗收。

本地 AI 實作系列

Local AI practice 04|Data verification: November 30, 2026

The model can answer text questions, but it doesn't mean it can understand the photos you attach. To let local AI check product pictures, organize screenshots, or extract text from screens, you need a model that supports image input and actually sends the image content into the inference request.

This article uses qwen3-vl:4b-instruct establish a single-image workflow: read a picture from the computer, hand it over to the local model, and then organize the results into JSON that can be used by the program. Finally, verify with known answers and distinguish between "the picture was sent" and "the picture recognition was correct".

I. First, select the correct model and problem

Qwen3-VL is a model series that supports visual input. This article uses 4B Instruct, which makes it easy to focus on directly reading pictures; it doesn't mean it can meet all OCR, precise positioning, or complex graph tasks.Qwen official model card

Ollama official This label is about 3.3GB when verified, including quantized language models and visual projection components. This is the download size, not the total memory demand during execution; image processing, context, and workspace will also increase demand. The model page lists a compatibility threshold of at least Ollama 0.12.7, and the current official stable version should be used during installation.Ollama model information

For the first time, please prepare a PNG or JPEG that you have the right to use and does not contain confidential content. It's best to have a clear subject, clear font, and a picture with a known correct answer. Don't use a long screenshot, a table with dozens of grids, or a blurry full-page scan as the first question, otherwise, input, recognition, and memory problems are easily mixed together.

II. Confirm that the local model can be loaded

First complete Ollama installationand start the service, and run the following in the terminal:

ollama --version
ollama pull qwen3-vl:4b-instruct
ollama show qwen3-vl:4b-instruct

If the model architecture is not supported, update Ollama first and then restart the service. If there is insufficient capacity, check the available memory and other loaded models; don't take the model file size as the video memory usage.

Text-based models won't suddenly gain visual abilities just because a file path is added to the prompt. Ollama's image API uses images fields: The official SDK can accept file paths and other inputs, but when directly calling the REST API, base64 image data must be passed. The following uses the latter, making each step visible.Ollama image input file

III. A picture-reading program that doesn't require extra Python packages

First, confirm that Python 3 is installed: Windows can use py --version, macOS/Linux can use python3 --version. If not installed, install from Python official websiteGet the version suitable for the system.

Save the following content with UTF-8 encoding as local_vision.py, confirm that the full file name is not local_vision.py.txt. This program only reads the single file you specify and does not scan other folders; it uses the Python standard library, no additional pip install。

import base64
import json
import sys
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

if len(sys.argv) != 2:
    raise SystemExit('請提供圖片路徑,例如:python local_vision.py "sample.png"')

image_path = Path(sys.argv[1]).expanduser()
if not image_path.is_file():
    raise SystemExit("找不到圖片,請檢查檔名與路徑。")
if image_path.suffix.lower() not in {".png", ".jpg", ".jpeg"}:
    raise SystemExit("本範例請使用 PNG 或 JPEG 圖片。")

schema = {
    "type": "object",
    "properties": {
        "summary": {"type": "string"},
        "visible_text": {"type": "array", "items": {"type": "string"}},
        "uncertain": {"type": "array", "items": {"type": "string"}},
    },
    "required": ["summary", "visible_text", "uncertain"],
    "additionalProperties": False,
}

prompt = (
    "請用繁體中文,只依照這張圖片回答。"
    "summary 簡述可直接看見的內容;"
    "visible_text 逐項抄錄清楚可辨識的文字;"
    "uncertain 列出看不清楚或無法確認的部分。"
    "不要猜品牌、價格、日期或被遮住的內容。"
    "請依照這份 JSON Schema 輸出 JSON:"
    + json.dumps(schema, ensure_ascii=False)
)

payload = {
    "model": "qwen3-vl:4b-instruct",
    "messages": [{
        "role": "user",
        "content": prompt,
        "images": [base64.b64encode(image_path.read_bytes()).decode("ascii")],
    }],
    "stream": False,
    "format": schema,
    "options": {"temperature": 0, "num_ctx": 4096, "num_predict": 1024},
}

request = Request(
    "http://127.0.0.1:11434/api/chat",
    data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
    headers={"Content-Type": "application/json; charset=utf-8"},
    method="POST",
)

try:
    with urlopen(request, timeout=600) as response:
        envelope = json.load(response)
except HTTPError as exc:
    raise SystemExit(f"Ollama 回傳 HTTP {exc.code}:{exc.read().decode('utf-8', 'replace')}")
except (URLError, TimeoutError) as exc:
    raise SystemExit(f"連線或等待失敗,請確認 Ollama 已啟動:{exc}")

if envelope.get("done_reason") == "length":
    raise SystemExit("輸出達到長度限制,請減少任務內容或調整輸出上限後重試。")

try:
    result = json.loads(envelope["message"]["content"])
    valid = (
        isinstance(result, dict)
        and set(result) == {"summary", "visible_text", "uncertain"}
        and isinstance(result["summary"], str)
        and all(
            isinstance(result[key], list)
            and all(isinstance(item, str) for item in result[key])
            for key in ("visible_text", "uncertain")
        )
    )
    if not valid:
        raise ValueError("欄位或型別不符合規格")
except (KeyError, TypeError, ValueError) as exc:
    raise SystemExit(f"回應格式驗證失敗:{exc}")

print(json.dumps(result, ensure_ascii=False, indent=2))

Run in the folder where the program is located, replace the picture name with your own file; keep the quotes when the path has spaces:

# Windows PowerShell
py .\local_vision.py "C:\Users\你的帳號\Pictures\sample.png"
# macOS/Linux Terminal
python3 ./local_vision.py "/完整路徑/sample.png"

The program deliberately only uses local addresses and downloaded labels, without external image URLs. The image will be converted to base64 and then sent to Ollama on this computer. If the service runs in a different environment, such as Docker or another host, this address needs to be planned separately and cannot be applied unchanged.

format Use JSON Schema to limit fields, and the program re-checks the output type. This can reduce the likelihood of subsequent processes being interrupted by irregular text, but correct formatting does not mean that the text and numbers on the picture are definitely recognized correctly.Structured output official documents、Chat API fields

Four, use five pictures to verify, don't just ask "what is this"

The following is the acceptance design suggested in this article, not the finished model test. Write the answer yourself first, and then let the model answer.

Test picture Check points Typical manifestations that do not pass
A commodity with a clear outline Category, main color, quantity Guess the unseen brand based on the shape
Big character activity date map Date, time, unit check one by one Take 6 days as 8 days, or fill in the year
Local cropping of the same picture Can the original blurred text be read after cropping Confidently output different answers for the two pictures
A clear website screenshot Visible button text, fields, and error messages Claim to have clicked the button or viewed other pages
Pictures with blocked or blurred areas Whether to be included in uncertain Fill in the invisible content to complete the sentence

First, score the important fields one by one, such as whether the activity date is completely correct, whether the selling price is fabricated. If the task only requires product classification, use the classification accuracy for acceptance; if it requires copying the amount, one digit error will also be recorded as a failure, and the fluency of the entire text cannot be used to offset it.

Improving the resolution does not necessarily improve the result. First, cut off the blank and background that are not related to the task, and retain enough context; long screenshots can be cut into paragraphs, and the order can be recorded. This is to improve the input quality, not to guarantee the accuracy of the model.

Five, where to start when recognition fails?

It always says that the picture is not visible: Check images Whether it is placed in the user message, whether it is really transmitted in base64, and whether the model supports vision. Putting C:\\image.png ordinary text into REST JSON will not transmit the picture together.

The picture loads slowly or the memory is insufficient: First, use a single small-range picture, short questions, and 4096 tokens as the starting point, and confirm that there are no other large models occupying resources. When the picture content is more, it may be necessary to have a longer context, but it is necessary to re-evaluate the memory at the same time; do not directly pull the settings to the maximum value claimed by the model.Context and memory instructions

Can read the general idea, but copied the small characters wrong: Cut and enlarge the error area, and ask for a single field. For a large number of document text extractions, the OCR process should be evaluated separately; the summary ability of the visual model cannot replace the acceptance of the correct rate of each character.

JSON passes, and the content is still guessed: Keep the original picture, model ID, prompt, and error field, and change to a more explicit question or compare with other models. Setting the temperature to zero cannot eliminate recognition errors or guarantee that each time is completely the same.

Six, how to connect to work after understanding the picture?

You can first do the preliminary classification of product photos, draw a draft of the text in the picture, summarize the content of the screenshot, or assist in organizing the materials to be reviewed by humans. Each task retains the original picture and the fields to be confirmed, allowing people to return to the evidence.

The model can see the screenshot, but it does not mean it can operate the computer. Clicking, reading other files, or updating the website requires an additional tool layer and permission design. The boundary of this program is very clear: read a picture you specify, generate text results, and do not execute the instructions in the picture.

To upgrade to automation, first let your program verify the fields, and then decide whether to hand it over to human review according to the rules. For content that cannot be wrong, such as prices, dates, and customer data, first pass the test with known answers, and then consider automatically writing to other systems.

Exercise attachment

Provided at the end of the document local_vision.py, the content is consistent with the code above. First, complete the installation of Python, Ollama, and the specified model, and then execute it by passing in the image path as an example.

Official reference materials

This article is designed based on the official interface documentation and does not claim the speed or recognition accuracy of specific hardware. The actual effect needs to be verified with your pictures and working conditions.

Local AI implementation series

附件

本地圖片辨識 Python 範例,與內文程式碼一致;需先安裝 Ollama、Python 並下載指定模型。

PY · 3 KB

開啟原圖