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

本文介绍了如何通过PaddleOCR识别图片中的文字,将其结果存储在Elasticsearch中,并实现基于文本的搜索功能,返回包含搜索结果的图片。详细步骤包括部署PaddleOCR和Elasticsearch,创建索引并设置映射,以及处理和存储识别结果及搜索操作。
摘要由CSDN通过智能技术生成

通过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]

结果如下:
在这里插入图片描述

  • 23
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
,也称作以,其实是一种基于像识别技术的索方式。通过对输入的片进行分析、处理,然后从海量的本语料库中匹配相应的字描述或相关信息,从而达到实现的目的。而Python作为一种广受欢迎的编程语言,也提供了许多像处理和人工智能相关的开发工具和库,极大地方便了此类应用的开发。 实现的过程大体可以分为三部分:像处理、特征提取和本匹配。在像处理模块中,可以利用Python的像处理库Pillow或OpenCV等进行像的预处理操作。例如,可以将像进行resize、变形、裁剪等操作,以及进行各种像特效加工,以避免片失真或者不符合索标准。在特征提取模块,可以利用深度学习中的卷积神经网络提取片特征,或者使用传统像处理特征,如SIFT和SURF等,提取具有代表性的特征点。最后,在本匹配模块中,可以通过Python的自然语言处理工具(如NLTK、TexSoup等)对像特征提取的结果进行处理,将其与海量的语料库中的字描述进行比较,从而找出最相符的本结果,即实现功能。 总之,Python是一种优秀的编程语言,可以方便地实现像处理、深度学习、自然语言处理等众多功能模块,这些工具和库的支持使得以实现变得更加简便和高效。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值