How to use Python to identify QR codes in pictures

How to use Python to identify QR codes in pictures

QR codes are a convenient and fast way of information transmission, and they are widely used in e-commerce, advertising and other fields. In many cases, we need to recognize QR codes in pictures in order to obtain information from them. Python is a popular programming language with rich image processing libraries that can help us recognize QR codes.

Using Python to identify QR codes in pictures is mainly divided into two steps: reading pictures and recognizing QR codes. First, we need to load the image. Using the imread function in the OpenCV library, we can read image files. Then, we need to use the PyZbar library to recognize the QR code. PyZbar is a Python interface that can use the ZBar library to recognize QR codes.

The following is a code example that uses Python to recognize a QR code in an image:

import cv2
from pyzbar.pyzbar import decode

def identify_qrcode(img_path):
    # read image
    img = cv2.imread(img_path)

    # Convert to grayscale image
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Identify the QR code
    decoded = decode(gray)

    # print the result
    for d in decoded:
        print(d.data.decode())

    # draw the rectangle
    for obj in decoded:
        rect = obj.rect
        cv2.rectangle(img, (rect.left, rect.top), (rect.left + rect.width, rect.top + rect.height), (0, 255, 0), 2)

    # Show results
    cv2.imshow("Result", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

identify_qrcode('qrcode.jpg')

In this example, we use the imread function in the OpenCV library to read the image and convert it to a grayscale image using the cvtColor function. Then, we use the decode function in the PyZbar library to recognize the QR code, and use the data attribute to get the content of the QR code. Finally, we use the rectangle function in the OpenCV library to draw a rectangle to mark the position of the QR code, and use the imshow function to display the result.

It should be noted that the code in this example is only suitable for recognizing a single QR code. If a picture contains multiple QR codes, each QR code needs to be identified and marked.

In short, Python has a powerful image processing library that can help us quickly and accurately identify QR codes in pictures. By using these libraries, we can more easily get the information in the picture.

More exchange of learning resources: Q: 2633739505 or visit www.ttocr.com

Guess you like

Origin blog.csdn.net/hdhddhdjxjc/article/details/129478567