返回

产品包装图片成分提取技术方案:OCR与深度学习

python

从产品包装图片中提取成分信息的技术方案

产品成分提取是一个常见需求,特别是在电商、健康饮食和市场调研等领域。 当我们只有产品包装图片时,如何高效准确地提取成分信息?本文将深入探讨几种可行的技术方案,并提供详细的实现步骤和代码示例。

OCR 技术方案

光学字符识别(OCR)是解决该问题的基础方法。OCR 的核心在于将图片中的文字转换为可编辑的文本数据。对于成分列表这种结构化信息,OCR 效果很大程度取决于图像质量、字体、排版等因素。

方案实现

  1. 图像预处理: 首先对图像进行预处理,包括图像去噪、二值化、倾斜校正等操作,提高图像质量,从而提升 OCR 识别精度。可以使用 OpenCV 等图像处理库。

    • 代码示例 (Python with OpenCV):

      import cv2
      import numpy as np
      
      def preprocess_image(image_path):
          img = cv2.imread(image_path)
          gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
          _, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
          return thresh
      
      processed_image = preprocess_image("product_image.jpg")
      cv2.imwrite("processed_image.jpg",processed_image)
      
    • 操作步骤:

      • 安装 OpenCV 库: pip install opencv-python numpy
      • product_image.jpg 替换为实际图片路径。
      • 运行脚本,将生成预处理后的图像 processed_image.jpg
  2. 文字识别: 使用 OCR 引擎识别预处理后的图像中的文字。目前有很多成熟的 OCR 引擎,如 Tesseract、Google Cloud Vision API、Amazon Textract 等。

    • 代码示例 (Python with Tesseract):

      import pytesseract
      from PIL import Image
      
      #  Tesseract 可执行文件路径(Windows 上需要手动指定)
      # pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
      
      def extract_text(image_path):
         image = Image.open(image_path)
         text = pytesseract.image_to_string(image,lang='eng')
         return text
      
      ingredients_text = extract_text("processed_image.jpg")
      print(ingredients_text)
      
    • 操作步骤:

      • 安装 Tesseract OCR 引擎和 pytesseract 库:
        • Linux (Debian/Ubuntu): sudo apt update && sudo apt install tesseract-ocr && pip install pytesseract pillow
        • macOS: brew install tesseract && pip install pytesseract pillow
        • Windows: 从 Tesseract 下载并安装,并设置 pytesseract.pytesseract.tesseract_cmd 的路径。 然后安装 pip install pytesseract pillow
      • 运行脚本,将打印识别出的成分文本。
      • 如需要其他语言识别,比如中文,需要安装相应的语言包, 并更改lang参数。
        例如中文:
        • Linux (Debian/Ubuntu): sudo apt-get install tesseract-ocr-chi-sim
        • 然后将 lang='eng'更改为lang='chi_sim'
  3. 成分提取: 从 OCR 识别的文本中提取成分信息。 这一步通常需要结合自然语言处理(NLP)技术,如关键词匹配、正则表达式匹配等。 也可根据成分列表的特征,比如"成分: ", "Ingredients:"等标识进行文本分割和提取。

    • 代码示例 (Python):

      import re
      
      def extract_ingredients(text):
          # 使用正则表达式提取成分信息
          match = re.search(r"(Ingredients:|成分:)(.+)", text,re.IGNORECASE|re.DOTALL)
          if match:
              ingredients_string = match.group(2)
              #根据逗号分句
              ingredients_list = [s.strip() for s in ingredients_string.split(',')]
              return ingredients_list
          else:
             return []
      
      ingredients = extract_ingredients(ingredients_text)
      print(ingredients)
      
      
    • 操作步骤:

      • 运行代码,将提取到的成分列表打印出来。
      • 正则表达可能需要根据实际成分文本结构调整。

安全与优化建议

  • 图像质量至关重要 。 尽可能获取高分辨率、光照均匀的图片。
  • 预处理是提升 OCR 效果的关键 。 针对不同类型的图片,可能需要调整预处理参数。
  • 选择合适的 OCR 引擎 。 不同 OCR 引擎在识别准确率、速度、支持语言等方面有所差异,需根据实际需求进行选择。 商业 OCR 引擎(如 Google Cloud Vision API)通常比开源引擎具有更高的精度和更丰富的功能。
  • 后处理不可或缺 。 OCR 结果可能存在错误,需要进行后处理校正,例如拼写检查、语法检查等。
  • 考虑隐私安全 。 如果使用第三方 OCR 服务,应注意保护用户隐私,避免上传敏感信息。 必要时可选择本地 OCR 方案或对数据进行脱敏处理。

结合深度学习的方案

当 OCR 效果不佳或成分信息提取逻辑复杂时,可以考虑使用深度学习技术。 通过训练深度学习模型,可以直接从图像中识别和提取成分信息,无需进行 OCR 。

方案实现

  1. 数据集构建: 准备大量带有成分标注的商品图片作为训练数据集。
  2. 模型选择: 选择合适的深度学习模型,如卷积神经网络 (CNN) 用于图像特征提取,循环神经网络 (RNN) 或 Transformer 用于序列标注。 目前也有一些预训练好的模型,比如PaddleOCR的模型,可以用来直接进行成分识别。
  3. 模型训练: 使用数据集对模型进行训练。 可以采用迁移学习的方法,在预训练模型的基础上进行微调,以加快训练速度和提高模型性能。
  4. 成分提取: 使用训练好的模型直接从新的商品图片中提取成分信息。

代码示例 (使用 PaddleOCR ):

from paddleocr import PaddleOCR, draw_ocr

# Paddleocr supports Chinese, English, French, German, Korean and Japanese.
# You can set the parameter `lang` as `ch`, `en`, `fr`, `german`, `korean`, `japan`
# to switch the language model in order.
ocr = PaddleOCR(use_angle_cls=True, lang='en') # need to run only once to download and load model into memory
img_path = './product_image.jpg'
result = ocr.ocr(img_path, cls=True)
for line in result:
    print(line)

# draw result
from PIL import Image
image = Image.open(img_path).convert('RGB')
boxes = [line[0] for line in result]
txts = [line[1][0] for line in result]
scores = [line[1][1] for line in result]
im_show = draw_ocr(image, boxes, txts, scores, font_path='./fonts/simfang.ttf')
im_show = Image.fromarray(im_show)
im_show.save('result.jpg')

#ingredients extraction
def extract_ingredients(result):
        ingredients = []
        bIngre = False
        for line in result:
            text = line[1][0]
            if bIngre:
                 ingredients.append(text)
                 #ingredients += [s.strip() for s in text.split(',')]
            if re.search(r"(Ingredients:|成分:)",text,re.IGNORECASE):
                 bIngre = True
        return ingredients

ingredients_list = extract_ingredients(result)
print (ingredients_list)

操作步骤:

  • 安装 PaddlePaddle 和 PaddleOCR : pip install paddlepaddle paddleocr
  • 下载 PaddleOCR 检测、识别、方向分类模型, 命令行执行 paddleocr --init_model
  • (可选) 下载中文字体用于可视化结果: 下载 simfang.ttf 放到 ./fonts 目录下
  • 替换 img_path 为实际图片路径.
  • 运行脚本, 会打印识别结果,并在当前目录生成 result.jpg 显示OCR的识别结果。

安全与优化建议

  • 数据集质量直接决定模型效果 。 标注数据需要准确、一致,并包含足够多的样本。
  • 模型选择和调优是关键 。 不同的模型适用于不同类型的任务,