当前位置: 首页 > news >正文

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

通过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}")continueimage = cv2.imread(image_path)if image is None:print(f"无法读取图像:{image_path}")continueimage_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_resultdef 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]

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

http://www.lryc.cn/news/336180.html

相关文章:

  • Android 13.0 Launcher3定制化之最近任务的全部清除由左边移到下边显示
  • 成都数字产业园落地全生命周期服务方案, 让企业对成都发展更有信心
  • SpringBoot实现RabbitMQ的通配符交换机(SpringAMQP 实现Topic交换机)
  • opencv图像处理技术(形态学操作)
  • 如何构建数据指标体系
  • python统计分析——一般线性回归模型
  • 【cocos creator】【TS】贝塞尔曲线,地图之间显示曲线
  • COMFYUI换脸ReActor报错Value not in list: face_restore_model: ‘codeformer.pth‘解决
  • 深入理解Java中的字段与属性的区别
  • 【Locust分布式压力测试】
  • 富格林:出金异常警惕黑幕陷阱受骗
  • Docker - Nginx
  • 免费搭建幻兽帕鲁服务器(Palworld免费开服教程)
  • 作业习题
  • 解决unbuntu更新到23.10 mantic firefox无法使用的问题
  • idea常用配置——注释快捷键
  • Hidl 学习总结 2
  • 深度学习学习日记4.7
  • 五一假期来临,各地景区云旅游、慢直播方案设计与平台搭建
  • 自动驾驶中的交通标志识别原理及应用
  • 数据挖掘入门项目二手交易车价格预测之建模调参
  • 【Java】Java使用Swing实现一个模拟计算器(有源码)
  • MC9S12DJ64微控制器
  • 小程序打开空白的问题处理
  • langchain + azure chatgpt组合配置并运行
  • 【JVM性能调优】- GC调优实操思路
  • 四川教育装备行业协会考察团走访云轴科技ZStack共话技术创新应用
  • KIVY 学习1
  • 在Go语言中使用select和channel来期待确定性行为
  • 【MATLAB源码-第19期】matlab基于导频的OFDM系统瑞利信道rayleigh的信道估计仿真,输出估计与未估计误码率对比图。