类似微信的以文搜图功能实现

通过PaddleOCR识别图片中的文字,将识别结果报存到es中,利用es查询语句返回结果图片。

技术逻辑

  • PaddleOCR部署、es部署
  • 创建mapping
  • 将PaddleOCR识别结果保存至es
  • 通过查询,返回结果

前期准备

PaddleOCR、es部署请参考https://blog.csdn.net/zhanghan11366/article/details/137026144?spm=1001.2014.3001.5502

创建mapping

复制代码
from elasticsearch import Elasticsearch

# 连接Elasticsearch
es_client = Elasticsearch("http://0.0.0.0:9200/", basic_auth=("elastic", "ZargEZ7NmJRkXLFlEqgE"))

# 创建新的ES index
mapping = {
    'properties': {
        'description': {
            'type': 'text',
            'analyzer': 'ik_smart',
            'search_analyzer': 'ik_smart'
        },
        "insert_time": {
            "type": "date",
            "format": "yyyy-MM-dd HH:mm:ss"
         },
        "image_path":{
            'type': 'text'
        }
    }
}

es_client.indices.create(index='wechat_search_ocr', ignore=400)
result = es_client.indices.put_mapping(index='wechat_search_ocr', body=mapping)
print(result)

将PaddleOCR识别结果保存至es

核心代码展示

复制代码
def image_ocr(image_dir):
    files = os.listdir(image_dir)
    image_files = [file for file in files if file.endswith(('jpg', 'jpeg', 'png', 'gif'))]
    for image_file in image_files:
        image_path = os.path.join(image_dir, image_file)
        if not os.path.isfile(image_path):
            print(f"文件不存在:{image_path}")
            continue

        image = cv2.imread(image_path)
        if image is None:
            print(f"无法读取图像:{image_path}")
            continue

        image_base64 = cv2_to_base64(image)
        data = {'images': [image_base64]}

        headers = {"Content-type": "application/json"}
        url = "http://192.168.30.71:8866/predict/ch_pp-ocrv3"
        try:
            r = requests.post(url=url, headers=headers, data=json.dumps(data))
            r.raise_for_status()  # 检查请求是否成功
            ocr_results = r.json().get("results", [])
            if ocr_results:
                description = "\n".join([ocr_record["text"].strip() for ocr_record in ocr_results[0]["data"]])
                doc = {
                    "description": description,
                    "insert_time": dt.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "image_path": image_file
                }
                es_client.index(index="wechat_search_ocr", body=doc)
                print("成功插入到 Elasticsearch 中!")
            else:
                print("OCR 服务返回结果为空!")
        except Exception as e:
            print(f"处理图像 {image_path} 时发生错误:{str(e)}")

通过查询,返回结果

核心代码展示

复制代码
def image_search_by_text(query_str):
    result = []
    # 对query进行全文搜索
    queries = query_str.split()
    dsl = {
        "query": {
            "bool": {
                "must": [
                    {"match": {"description": _}} for _ in queries
                ]
            }
        },
        "size": 5
    }
    search_result = es_client.search(index='wechat_search_ocr', body=dsl)
    return search_result


def image_search_interface(query_str):
    # 查询图像
    search_results = image_search_by_text(query_str)
    # 构建结果
    images=[]
    for hit in search_results['hits']['hits']:
        image_filename = hit['_source']['image_path']
        image_path = os.path.join('./data', image_filename)
        image = Image.open(image_path).convert('RGB')
        images.append(image)
    if len(images) >= 3:
        images = images[:3]
    else:
        for _ in range(3 - len(images)):
            images.append(None)
    return images[0], images[1], images[2]

结果如下:

相关推荐
风象南2 小时前
普通人用AI加持赚到的第一个100块
人工智能·后端
牛奶2 小时前
2026年大模型怎么选?前端人实用对比
前端·人工智能·ai编程
牛奶2 小时前
前端人为什么要学AI?
前端·人工智能·ai编程
地平线开发者4 小时前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮4 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者5 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考5 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
冬奇Lab6 小时前
OpenClaw 源码精读(2):Channel & Routing——一条消息如何找到它的 Agent?
人工智能·开源·源码阅读
冬奇Lab6 小时前
一天一个开源项目(第38篇):Claude Code Telegram - 用 Telegram 远程用 Claude Code,随时随地聊项目
人工智能·开源·资讯
格砸7 小时前
从入门到辞职|从ChatGPT到OpenClaw,跟上智能时代的进化
前端·人工智能·后端