Todos los productos
Search
Centro de documentos

Intelligent Media Management:Reconocimiento de códigos QR

Última actualización: Sep 22, 2026

Este tema describe cómo usar la función de reconocimiento de códigos QR.

Escenarios

  • Pagos con códigos QR: los pagadores escanean un código QR para completar sus pagos.

  • Marketing y publicidad con códigos QR: los equipos de marketing y publicidad agregan códigos QR a carteles y empaques de productos para promocionarlos.

Descripción general

Intelligent Media Management (IMM) ofrece una función de reconocimiento de códigos QR. Esta función detecta la posición y el contenido de uno o más códigos QR o códigos de barras en archivos de imagen, como fotografías y capturas de pantalla. Además, devuelve la información de posición y el texto que contienen los códigos. La información de posición incluye la coordenada x de la esquina superior izquierda, la coordenada y de la esquina superior izquierda, el ancho y la altura, tal como se muestra en la siguiente figura.

  • Código QR

    figqcode11

  • Código de barras

    image

Utilice esta función para implementar el escaneo y la lectura de códigos QR o de barras en sus aplicaciones empresariales. También puede desarrollar funciones que bloqueen o pixelen estos códigos en las imágenes a partir del reconocimiento de códigos QR.

Requisitos previos

  • Se creó y obtuvo un par de AccessKey. Para obtener más información, consulte Create an AccessKey.

  • Object Storage Service (OSS) está activado, se creó un bucket y se cargaron objetos en él. Para obtener más información, consulte Upload objects.

  • IMM está activado. Para obtener más información, consulte Activate IMM.

  • Se creó un proyecto en la consola de IMM. Para obtener más información, consulte Create a project.

    Nota
    • Llame a la operación CreateProject para crear un proyecto. Para obtener más información, consulte CreateProject.

    • Llame a la operación ListProjects para consultar los proyectos existentes en una región específica. Para obtener más información, consulte ListProjects.

Uso

Llame a la operación DetectImageCodes para detectar códigos de barras en una imagen.

Nota

La detección de códigos QR permite identificar hasta cinco códigos en una sola imagen.

Ejemplo de detección de códigos QR

Información de la imagen

  • Proyecto de IMM: test-project

  • Ubicación de almacenamiento de la imagen: oss://test-bucket/test-object1.jpg

  • Imagen de ejemplo

    figqcode11

Solicitud de ejemplo

{
    "ProjectName": "test-project",
    "SourceURI": "oss://test-bucket/test-object1.jpg",
}

Respuesta de ejemplo

{
  "Codes": [
    {
      "Type": "qrcode",
      "Content": "https://www.aliyun.com/product/imm",
      "Boundary": {
        "Left": 447,
        "Top": 288,
        "Height": 720,
        "Width": 767
      }
    }
  ],
  "RequestId": "9692C8B4-2AAF-55DE-91A0-B0B53725FBAB"
}

Nota

La respuesta de ejemplo anterior indica que la imagen contiene un código QR.

Código de ejemplo

El siguiente código de ejemplo muestra cómo usar el SDK de IMM para Python y detectar códigos QR en una imagen.

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import sys
import os
from typing import List

from alibabacloud_imm20200930.client import Client as imm20200930Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_imm20200930 import models as imm_20200930_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> imm20200930Client:
        """
        Use your AccessKey ID and AccessKey secret to initialize the client. 
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret
        )
        # Specify the IMM endpoint. 
        config.endpoint = f'imm.cn-beijing.aliyuncs.com'
        return imm20200930Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To prevent security risks, we recommend that you call API operations or perform routine O&M as a RAM user. 
        # We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
        # In this example, the AccessKey pair is read from the environment variables to implement identity verification for API access. For information about how to configure environment variables, see https://www.alibabacloud.com/help/document_detail/2361894.html. 
        imm_access_key_id = os.getenv("AccessKeyId")
        imm_access_key_secret = os.getenv("AccessKeySecret")
        # Initialize the client. 
        client = Sample.create_client(imm_access_key_id, imm_access_key_secret)
        detect_image_codes_request = imm_20200930_models.DetectImageCodesRequest(
            project_name='test-project',
            source_uri='oss://test-bucket/test-object1.jpg'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can choose to print the response of the API operation. 
            client.detect_image_codes_with_options(detect_image_codes_request, runtime)
        except Exception as error:
            # Print the error message if necessary. 
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To prevent security risks, we recommend that you call API operations or perform routine O&M as a RAM user. 
        # We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
        # In this example, the AccessKey pair is read from the environment variables to implement identity verification for API access. For information about how to configure environment variables, see https://www.alibabacloud.com/help/document_detail/2361894.html. 
        imm_access_key_id = os.getenv("AccessKeyId")
        imm_access_key_secret = os.getenv("AccessKeySecret")
        # Initialize the client. 
        client = Sample.create_client(imm_access_key_id, imm_access_key_secret)
        detect_image_codes_request = imm_20200930_models.DetectImageCodesRequest(
            project_name='test-project',
            source_uri='oss://test-bucket/test-object1.jpg'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can choose to print the response of the API operation. 
            await client.detect_image_codes_with_options_async(detect_image_codes_request, runtime)
        except Exception as error:
            # Print the error message if necessary. 
            UtilClient.assert_as_string(error.message)

if __name__ == '__main__':
    Sample.main(sys.argv[1:])

Ejemplo de detección de códigos de barras

Información de la imagen

  • Proyecto de IMM: test-project

  • Ubicación de almacenamiento de la imagen: oss://test-bucket/test-object2.jpg

  • Imagen de ejemplo

    test-object

Solicitud de ejemplo

{
    "ProjectName": "test-project",
    "SourceURI": "oss://test-bucket/test-object2.jpg",
}

Respuesta de ejemplo

{
  "Codes": [
    {
      "Type": "barcode",
      "Confidence": 0.433,
      "Content": "",
      "Boundary": {
        "Left": 162,
        "Top": 393,
        "Height": 86,
        "Width": 78
      }
    }
  ],
  "RequestId": "391A3AEC-FF64-5450-96DF-18DBDC234B2F"
}
Nota

La respuesta de ejemplo anterior indica que la imagen contiene un código de barras.

Código de ejemplo

# -*- coding: utf-8 -*-
# This file is auto-generated, don't edit it. Thanks.
import sys
import os
from typing import List

from alibabacloud_imm20200930.client import Client as imm20200930Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_imm20200930 import models as imm_20200930_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
        access_key_id: str,
        access_key_secret: str,
    ) -> imm20200930Client:
        """
        Use your AccessKey ID and AccessKey secret to initialize the client. 
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            access_key_id=access_key_id,
            access_key_secret=access_key_secret
        )
        # Specify the IMM endpoint. 
        config.endpoint = f'imm.cn-beijing.aliyuncs.com'
        return imm20200930Client(config)

    @staticmethod
    def main(
        args: List[str],
    ) -> None:
        # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To prevent security risks, we recommend that you call API operations or perform routine O&M as a RAM user. 
        # We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
        # In this example, the AccessKey pair is read from the environment variables to implement identity verification for API access. For information about how to configure environment variables, see https://www.alibabacloud.com/help/document_detail/2361894.html. 
        imm_access_key_id = os.getenv("AccessKeyId")
        imm_access_key_secret = os.getenv("AccessKeySecret")
        # Initialize the client. 
        client = Sample.create_client(imm_access_key_id, imm_access_key_secret)
        detect_image_codes_request = imm_20200930_models.DetectImageCodesRequest(
            project_name='test-project',
            source_uri='oss://test-bucket/test-object2.jpg'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can choose to print the response of the API operation. 
            client.detect_image_codes_with_options(detect_image_codes_request, runtime)
        except Exception as error:
            # Print the error message if necessary. 
            UtilClient.assert_as_string(error.message)

    @staticmethod
    async def main_async(
        args: List[str],
    ) -> None:
        # The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. To prevent security risks, we recommend that you call API operations or perform routine O&M as a RAM user. 
        # We recommend that you do not include your AccessKey pair (AccessKey ID and AccessKey secret) in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources within your account may be compromised. 
        # In this example, the AccessKey pair is read from the environment variables to implement identity verification for API access. For information about how to configure environment variables, see https://www.alibabacloud.com/help/document_detail/2361894.html. 
        imm_access_key_id = os.getenv("AccessKeyId")
        imm_access_key_secret = os.getenv("AccessKeySecret")
        # Initialize the client. 
        client = Sample.create_client(imm_access_key_id, imm_access_key_secret)
        detect_image_codes_request = imm_20200930_models.DetectImageCodesRequest(
            project_name='test-project',
            source_uri='oss://test-bucket/test-object2.jpg'
        )
        runtime = util_models.RuntimeOptions()
        try:
            # You can choose to print the response of the API operation. 
            await client.detect_image_codes_with_options_async(detect_image_codes_request, runtime)
        except Exception as error:
            # Print the error message if necessary. 
            UtilClient.assert_as_string(error.message)

if __name__ == '__main__':
    Sample.main(sys.argv[1:])