Home > database >  OpenCV; Read Camera on macOS; TypeError
OpenCV; Read Camera on macOS; TypeError

Time:07-15

I try to run a camera reading code in macOS. Here is my code:

import cv2
from pyzbar.pyzbar import decode
import os

os.system("clear")

cap = cv2.VideoCapture(0)
cap.set(3 , 640) 
cap.set(4 , 480) 

while True:
    success, img = cap.read()

    for barcode in decode(img):
    
        print(barcode.data)
    
        print(barcode.rect)
    
        x = barcode.data.decode('utf-8')
        print(x)

    cv2.imshow('Result', img)
    cv2.waitKey(1)

This is current error:

Traceback (most recent call last):
  File "/Users/username/Documents/Pyzbar Lesson 2.py", line 21, in <module>
    for barcode in decode(img):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 207, in decode
    pixels, width, height = _pixel_data(image)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pyzbar/pyzbar.py", line 173, in _pixel_data
    pixels, width, height = image
TypeError: cannot unpack non-iterable NoneType object

Please, share if I miss anything or other error in the code.

Thanks.

CodePudding user response:

This code works fine on my Windows machine (after changing 'clear' to 'cls' of course).

You're getting a Type Error because decode is trying to operate on a None type. In line 21 you call for barcode in decode(img). Here it is img that is 'None` and since decode cannot handle 'None' you get the error.

I suspect that your hardware is not cooperating properly. This could be due to your camera access preferences. You can use the cap.isOpen() and cap.isValid() checks to add an additional layer of trouble shooting.

CodePudding user response:

I FINALLY FOUND THE ANSWER Apparently, for some macOS users, having 'cap.set()' in your code would give you errors. But after removing it, it works perfectly

'''

import cv2
from pyzbar.pyzbar import decode
import os

os.system("clear")

cap = cv2.VideoCapture(0)

while True:
    success, img = cap.read()
    if not success:
        break

    for barcode in decode(img):

        print(barcode.data)

        print(barcode.rect)

        x = barcode.data.decode('utf-8')
        print(x)

    cv2.imshow('Result', img)
    cv2.waitKey(1)

'''

  • Related