Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Use pyzbar for Barcode and QR Code Scanning on macOS

Pyzbar is a Python library that allows you to read one-dimensional barcodes and QR codes from images. It is widely used in various applications, such as inventory management, ticketing systems, and more. However, pyzbar is primarily designed for environments that support the ZBar library, which may not be natively available on macOS. This article will guide you through the process of setting up pyzbar on macOS and provide practical examples to help you get started.

Examples:

  1. Install Homebrew and ZBar:

    Homebrew is a package manager for macOS that simplifies the installation of software. First, you need to install Homebrew if you haven't already:

    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

    After installing Homebrew, you can install ZBar using the following command:

    brew install zbar
  2. Set Up a Python Environment:

    It's a good practice to use a virtual environment for your Python projects. You can create and activate a virtual environment using the following commands:

    python3 -m venv pyzbar-env
    source pyzbar-env/bin/activate
  3. Install pyzbar and Other Dependencies:

    With the virtual environment activated, you can install pyzbar and other necessary libraries like Pillow for image processing:

    pip install pyzbar Pillow
  4. Write a Python Script to Scan Barcodes and QR Codes:

    Create a Python script named scan.py and add the following code to it:

    from pyzbar.pyzbar import decode
    from PIL import Image
    
    def scan_image(image_path):
       image = Image.open(image_path)
       decoded_objects = decode(image)
       for obj in decoded_objects:
           print(f"Type: {obj.type}")
           print(f"Data: {obj.data.decode('utf-8')}")
           print(f"Position: {obj.rect}")
    
    if __name__ == "__main__":
       import sys
       if len(sys.argv) != 2:
           print("Usage: python scan.py <image_path>")
           sys.exit(1)
       image_path = sys.argv[1]
       scan_image(image_path)
  5. Run the Script via Terminal:

    Save an image containing a barcode or QR code to your working directory. You can then run the script using the following command:

    python scan.py example.png

    Replace example.png with the path to your image file. The script will output the type, data, and position of any detected barcodes or QR codes.

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.