pythonimageopencvnoise-reduction

How to get barcode from image?


I need to get the information in the below barcode with the Python pyzbar library, but it does not recognize it. Should I make any improvement before using pyzbar?

BarCode

this is the code:

from pyzbar.pyzbar import decode
import cv2

    def barcodeReader(image):
        gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        barcodes = decode(gray_img)

    barcode = barcodeReader("My_image")
    print (barcode)

Result: []


Solution

  • You could try to reconstruct the barcode by:

    1. Inverse binarizing the image with cv2.threshold, such that you get white lines on black background.
    2. Counting all non-zero pixels along the rows using np.count_nonzero.
    3. Getting all indices, where the count exceeds a pre-defined threshold, let's say 100 here.
    4. On a new, all white image, drawing black lines at the found indices.

    Here's some code:

    import cv2
    import numpy as np
    from skimage import io      # Only needed for web grabbing images, use cv2.imread for local images
    
    # Read image from web, convert to grayscale, and inverse binary threshold
    image = cv2.cvtColor(io.imread('https://i.sstatic.net/D8Jk7.jpg'), cv2.COLOR_RGB2GRAY)
    _, image_thr = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY_INV)
    
    # Count non-zero pixels along the rows; get indices, where count exceeds certain threshold (here: 100)
    row_nz = np.count_nonzero(image_thr, axis=0)
    idx = np.argwhere(row_nz > 100)
    
    # Generate new image, draw lines at found indices
    image_new = np.ones_like(image_thr) * 255
    image_new[35:175, idx] = 0
    
    cv2.imshow('image_thr', image_thr)
    cv2.imshow('image_new', image_new)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    The inverse binarized image:

    Binarized

    The reconstructed image:

    Reconstruction

    I'm not sure, if the result is a valid barcode. To improve the solution you could get rid of the numbers beforehand. Also, play around with the threshold.

    Hope that helps!