简体   繁体   中英

ValueError when using image == None


I'm creating a fail-safe for my program so whenever the image is not there or image = None it will display a message and terminate the program. I am using the code below as a way to do this:

src_img = cv2.imread('/home/nazar/Downloads/img_4.png', 1)
if src_img == None:
    exit('No such file or direcory!')
copy = src_img.copy()

This works if there is no image but when there is an image, it will give an error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I tried following the error's suggestion and tried if src_img.all == None: and now when there is no image it gives the error:

AttributeError: 'NoneType' object has no attribute 'all'

is there a way to actually do this without getting these error messages and work if an image is given or there is no image given.

You are getting the first ValueError because NoneType does not define an equality comparison against numpy arrays, so the array's comparison method is used instead. Numpy converts None into an object array and broadcasts it to the size of your image. The result of == is an element-wise comparison, ie, a boolean array of the same size as your image.

Instead of all that, you should do

if src_img is None:

is compares the raw references. It is the recommended way to check for None since it is much faster and None is a singleton.

The second AttributeError comes from the fact that when src_img is None, it doesn't have a method named all . Even when it is a proper array, src_img.all is just a reference to that method, not the result of calling it.

Strangely enough, you could have totally gotten away with doing if np.all(src_img == None): , but you really shouldn't because it's a complete travesty in this case. When src_img is None, the comparison is scalar True, so np.all would return True. If src_img is a numeric array, every element would compare False, and np.all would return False. The only time this world give the wrong result is if you had an src_img that was an object array all of whose elements were None.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM