Search code examples
pythonopencvzbar

Opencv zbar python scanner error


import zbar
import Image
import cv2

# create a reader
scanner = zbar.ImageScanner()
# configure the reader
scanner.parse_config('enable')
#create video capture feed
cap = cv2.VideoCapture(0)

while(True):
    ret, cv = cap.read()
    cv = cv2.cvtColor(cv, cv2.COLOR_BGR2GRAY)
    pil = Image.fromarray(cv)
    width, height = pil.size
    raw = pil.tostring()
    # wrap image data
    image = zbar.Image(width, height, 'Y800', raw)

    # scan the image for barcodes
    scanner.scan(image)

    # extract results
    for symbol in image:
        # do something useful with results
        print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data

# clean up
print "/n ...Done"

I ran this code but this shows this error

Traceback (most recent call last):
  File "/home/joeydash/Desktop/InterIIT-UAV-challenge/zbar/main.py", line 17, in <module>
    raw = pil.tostring()
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 695, in tostring
    "Please call tobytes() instead.")
Exception: tostring() has been removed. Please call tobytes() instead.

Don't know what it means by image.tostring function. How can I solve this?


Solution

  • All credit to mark jay's comment. Your code will look like this

    import zbar
    import Image
    import cv2
    
    # create a reader
    scanner = zbar.ImageScanner()
    # configure the reader
    scanner.parse_config('enable')
    #create video capture feed
    cap = cv2.VideoCapture(0)
    
    while(True):
        ret, cv = cap.read()
        cv = cv2.cvtColor(cv, cv2.COLOR_BGR2GRAY)
        pil = Image.fromarray(cv)
        width, height = pil.size
        raw = pil.tobytes()
        # wrap image data
        image = zbar.Image(width, height, 'Y800', raw)
    
        # scan the image for barcodes
        scanner.scan(image)
    
        # extract results
        for symbol in image:
            # do something useful with results
            print 'decoded', symbol.type, 'symbol', '"%s"' % symbol.data
    
    # clean up
    print "/n ...Done"
    

    Notice how the line raw = pil.tostring() has been changed to raw = pil.tobytes()

    Hope this helps!