Python 调用智谱 GLM-4V 实现图片视觉识别(本地/网页图片通用)
智谱 GLM-4V 是高性能多模态大模型,支持图片 + 文本的混合输入,能精准识别图片内容(如验证码、图文分析、物体识别等)。本文将手把手教你实现本地图片、网页截图、Base64 编码图片三种方式调用 GLM-4V,结合实际场景(hCaptcha 验证码识别)完成落地。
本文介绍使用 Python 调用智谱 GLM-4V 多模态大模型进行图片视觉识别的方法。涵盖本地图片、网页截图及 Base64 编码三种输入方式,重点演示了 hCaptcha 验证码的识别流程。通过封装通用函数,结合 DrissionPage 实现自动化截图与解析,提供环境配置、代码示例及优化建议,帮助开发者高效落地图像识别场景。
智谱 GLM-4V 是高性能多模态大模型,支持图片 + 文本的混合输入,能精准识别图片内容(如验证码、图文分析、物体识别等)。本文将手把手教你实现本地图片、网页截图、Base64 编码图片三种方式调用 GLM-4V,结合实际场景(hCaptcha 验证码识别)完成落地。
requests(接口调用)、pillow(图片处理)、DrissionPage(网页截图)# 基础依赖
pip install requests pillow
# 网页自动化/截图(可选,用于网页图片场景)
pip install DrissionPage
# 数据解析(可选)
pip install json re
先封装通用调用函数,适配所有图片输入方式:
import requests
import base64
import json
# 智谱 AI 配置(替换为你的密钥)
AI_CONFIG = {
"api_key": "你的 GLM-4V API Key",
"base_url": "https://open.bigmodel.cn/api/paas/v4/chat/completions",
"model": "glm-4v-plus"
}
def encode_image_to_base64(image_path):
""" 本地图片转 Base64 编码(核心步骤)
:param image_path: 本地图片路径
:return: Base64 编码字符串
"""
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode('utf-8')
def call_glm4v(image_content, prompt, is_base64=False):
""" 调用 GLM-4V 模型
:param image_content: 图片内容(本地路径/Base64 字符串)
:param prompt: 提示词
:param is_base64: 是否为 Base64 编码(False=本地路径,True=Base64 字符串)
:return: AI 响应文本
"""
# 处理图片输入
if not is_base64:
base64_img = encode_image_to_base64(image_content)
else:
base64_img = image_content
# 请求头
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {AI_CONFIG['api_key']}"
}
# 请求体(智谱 GLM-4V 标准格式)
payload = {
"model": AI_CONFIG["model"],
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": base64_img}}
]
}],
"max_tokens": 1000,
"temperature": 0.1
}
# 发送请求
try:
response = requests.post(
AI_CONFIG["base_url"],
headers=headers,
json=payload,
timeout=60
)
response.raise_for_status()
result = response.json()
return result["choices"][0]["message"]["content"]
except Exception as e:
raise Exception(f"GLM-4V 调用失败:{str(e)}")
识别本地保存的图片(如验证码截图、产品图片、文档图片等)。
def local_image_demo():
"""本地图片调用 GLM-4V 示例(识别验证码)"""
# 1. 本地图片路径
local_img_path = "captcha_screenshot.png"
# 2. 定制化提示词(以 hCaptcha 九宫格验证码为例)
prompt = """ 图片尺寸 400×600,坐标系左上角 (0,0)、右下角 (1000,1000),3×3 九宫格验证码。 输出格式:[(x,y), (x,y)],仅返回坐标列表,无多余文字。 """
# 3. 调用 GLM-4V
try:
ai_response = call_glm4v(local_img_path, prompt)
print("AI 识别结果:", ai_response)
# 4. 解析坐标(可选,根据实际需求)
import re
coord_pattern = r'\((\d+),(\d+)\)'
coords = re.findall(coord_pattern, ai_response)
coords = [(int(x), int(y)) for x, y in coords]
print("解析后的坐标:", coords)
except Exception as e:
print("识别失败:", e)
if __name__ == "__main__":
local_image_demo()
自动化爬虫中实时截取网页元素(如验证码、弹窗图片)并识别。
from DrissionPage import ChromiumPage, ChromiumOptions
def web_screenshot_demo():
"""网页截图+GLM-4V 识别示例(验证码)"""
# 1. 初始化浏览器
co = ChromiumOptions().auto_port()
page = ChromiumPage(co)
try:
# 2. 访问目标页面(示例:带 hCaptcha 的页面)
page.get("https://你的目标网址.com")
# 3. 定位验证码区域并截图
captcha_ele = page.ele('.xxxxxx')
screenshot_path = "web_captcha.png"
captcha_ele.get_screenshot(screenshot_path)
print(f"网页截图已保存:{screenshot_path}")
# 4. 调用 GLM-4V 识别
prompt = """ 分析这张验证码图片,返回所有'有尾巴的动物'的中心坐标,格式:[(x,y), (x,y)] 仅返回坐标,无其他文字。 """
ai_response = call_glm4v(screenshot_path, prompt)
print("验证码识别结果:", ai_response)
finally:
page.close()
if __name__ == "__main__":
web_screenshot_demo()
图片已在内存中(如网络请求返回的图片、二进制流),无需保存到本地。
def base64_image_demo():
"""Base64 编码图片调用 GLM-4V 示例"""
# 1. 模拟获取 Base64 图片(实际场景可从网络/内存读取)
# 方式 1:本地图片转 Base64(测试用)
base64_img = encode_image_to_base64("captcha.png")
# 方式 2:网络图片转 Base64(实际场景)
# import requests
# img_response = requests.get("https://xxx.com/captcha.png")
# base64_img = base64.b64encode(img_response.content).decode('utf-8')
# 2. 调用 GLM-4V(指定 is_base64=True)
prompt = "识别这张图片中的所有动物名称,仅返回名称列表,用逗号分隔"
ai_response = call_glm4v(base64_img, prompt, is_base64=True)
print("Base64 图片识别结果:", ai_response)
if __name__ == "__main__":
base64_image_demo()
max_tokens(如 500)、精简提示词减少 Tokens 消耗通过本文的封装函数和场景示例,你可以快速实现各类图片的 GLM-4V 视觉识别,无论是本地图片分析、网页验证码破解,还是自动化爬虫中的图片处理,都能高效落地。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online