文本识别

使用光学字符识别(OCR)服务,可以从图像中提取文本内容。 因此,在 Image Read test step(图像读取测试步骤) 的求值阶段,可以将图像与字符串进行比较。此外,还可以通过内部 Multimedia API 在图像中定位文本。 默认情况下,ecu.test 通过 Tesseract OCR 引擎支持文本识别。 此外,还可以使用 UserPyModules 集成用户自定义 OCR 服务。 可在测试配置的 media access tab(媒体访问标签页) 中配置 OCR 服务。

用户自定义文本识别

ecu.test 的文本识别功能使用 OCR 服务将图像转换为字符串,例如按字典序拼接所有识别出的文本,或者精确定位图像中的各个文本片段。除预集成的 Tesseract OCR 服务外,用户还可以使用自己的自定义版本扩展 ecu.test。 用户自定义 OCR 服务必须实现为 Python 模块,并满足以下要求:

  • 该模块必须位于当前 Workspace(工作区)的 UserPyModules 目录中。

  • 必须在脚本顶层定义变量 MODULE_TYPE = ‘UserOCRService’。

  • 必须实现一个满足以下接口的 OCR 服务类:

    • __init__

    • GetServiceId

    • ImageToText

    • FindTextPositions

    • GetAvailableParameters

    • GetParameter

    • SetParamter

  • 不得存在两个具有相同服务 Id 的服务。

有关该接口的更多细节,请参见下一节中的示例。

新增或修改后的服务在刷新用户库后即可使用,此操作可在 ecu.test 的“Extras”菜单中执行。

要在 test case(测试用例)中通过内部 Multimedia API 使用用户自定义 OCR 服务,可以通过调用以下方法创建实例:

  • api.Multimedia.GetOCRService 或

  • api.Multimedia.GetDefaultOCRService.

返回对象上可以直接调用该接口中已实现的方法,例如 api.Multimedia.GetOCRService('ExampleOCR').GetParamter('threshold').

文本识别最小示例

用户自定义 OCR 服务的示例实现可在 ecu.test 安装目录中找到:

  • Templates/DefaultData/UserPyModules/UserOCRService/ExampleOCRService.py

ExampleOCRService.py 中的最小示例包含以下代码。各个方法的进一步说明可参见相应的文档字符串。

from __future__ import annotations
import logging
from typing import Any, TYPE_CHECKING

MODULE_TYPE = 'OCRService'

if TYPE_CHECKING:
    import numpy.typing as npt


class ExampleOCR:

    def __init__(self):
        """
        The service can be created when *GetOCRService(serviceId)* is called on the internal
        multimedia API, where *serviceId* is the identifier returned by *GetServiceId()*.
        Further, if the service is selected in the test configuration's media access tab,
        the class is instantiated
        - when an image is compared to a string during evaluation in image read and
        - when GetDefaultOCRService() is called on the Multimedia API via
            *api.Multimedia.GetDefaultOCRService()*.
        """
        self.ocrMode = 'dummy'
        self.canDetectText = False
        self.threshold = 0.4

    @staticmethod
    def GetServiceId() -> str:
        """
        The identifier of the OCR service as displayed in the test configuration's media access tab
        and used to create service via the multimedia api (see __init__).

        :return: Identifier of the service
        """
        return 'ExampleOCR'

    def ImageToText(self, img: npt.NDArray) -> str:
        """
        Converts the image to a string representation, e.g. by concatenating all found text in
        lexicographic order.

        :param img: Numpy image (width x height x channels)
        :return: String representation of the image
        """
        height, width = img.shape[:2]
        return f'The image has dimension ({height}, {width}) and maybe some text.'

    def FindTextPositions(self, img: npt.NDArray) -> list[dict[str, int | float | str]]:
        """
        Returns a list of all text matches found in the image.
        Each text match is a dictionary that must contain information about
        - its location in terms of a bounding box with upper left corner (x,y) and
          dimensions (width, height),
        - its content (text) and
        - the confidence of the individual match (confidence).

        :param img: Numpy image (width x height x channels)
        :return: List of dictionaries describing all text matches
        """
        h, w, __ = img.shape
        return [
            {
                'x': int(w / 4.0),
                'y': int(h / 4.0),
                'width': int(w / 2),
                'height': int(h / 2),
                'text': 'Some large imaginary text in the middle of the image.',
                'confidence': 0.42,
            }
        ]

    def GetAvailableParameters(self) -> list[dict[str, Any]]:
        """
        Returns a list of all configureable parameters. Each parameter must be described by a unique
        name and a default value. A short description is optional and will be displayed in a
        configuration dialog (tcf, media access tab).

        :return: List of all available paramters
        """
        return [
            {
                'name': 'ocrMode',
                'default': 'dummy',
                'description': 'This text describes what can or cannot be done.'
            },
            {
                'name': 'canDetectText',
                'default': False
            },
            {
                'name': 'threshold',
                'default': 0.5,
                'description': 'Matches with confidence below this value are ignored.'
            },
        ]

    def GetParameter(self, name: str) -> Any:
        """
        Returns the value of the parameter addressed by name.

        :param name: Name of the parameter
        :return: Value of parameter addressed by name
        """
        try:
            return getattr(self, name)
        except AttributeError:
            logging.getLogger('ecu.test').info(
                '{}: No such parameter: {}'.format(self.GetServiceId(), name)
            )

    def SetParameter(self, name: str, value: Any) -> None:
        """
        Sets the value of the parameter addressed by name.

        :param name: Name of the parameter
        :param value: Value of the parameter
        """
        if hasattr(self, name):
            setattr(self, name, value)
        else:
            logging.getLogger('ecu.test').info(
                '{}: No such parameter: {}'.format(self.GetServiceId(), name)
            )