pythonloopsopencvtry-exceptimread

How to catch CV2 errors with try - except statements in Python


so, I have a few png files that are saved following the pattern

name_number1_section_number2

The two fields number1 and number 2 are taken up by integers, so a file would be named

name_1_section_23

for example.

Now, I want to load these with cv2 to read out the share of black pixels in each of them. I use two nested loops for this. The issue is, that some number1-number2 combinations do not exist. "name_4_section_27" might not exist, while "name_1_section27" does. This would not be an issue if this were a regular Python command, then I would just use except "FileNotFoundError".

I have tried:

for i in range(n, k):
    for j in range(n, z):
        try: img = cv2.imread(fp + r"name_" + str(i) + "_section_" + str(j) + ".png")
        except (cv2.error, cv2.Error.StsAssert): print(fp + r"name_" + str(i) + "_section_" + str(j) + ".png does not exist")
        some Code
        [...]

Yet, cv2 still throws me an error message. The except statement does not seem to work. I used the error code given here, see -215, but it does not help with the issue. I have tried most combinations of cv, cv2, opencv, opencv-python.error, yet I have had no success. I tried using except error as e which did not help. Apart from that I tried to get around this by using img = open(file, "b") to catch the FileNotFoundError there, but this cannot be used with cv2.imread (as least as far as I know).

Since there are a lot of files, I do not want to have to open them manually. Any way to catch CV2 errors with try - except or are there other workarounds?

KR


Solution

  • You can just use the Exception class to catch errors you are meant to catch.

    except Exception: print(fp + r"name_" + str(i) + "_section_" + str(j) + ".png does not exist")
    

    Edit.: As mentioned in the comments using Exception is not the most optimal solution. The documentation you linked is primarily a C++ documentation.

    What should work in python is the following which seems to be correct in your code:

    except cv2.error as e: <handle a cv2 error>
    

    however according to a older post related to this topic: #8873657

    Some OpenCV functions don't throw errors, they print out a message and exit the program (either with exit or abort, I can't remember). In other words, there are some errors that can't be caught.

    However as mentioned in the comments, you should use something like

    for f in glob.glob('*.png'):
    

    to loop through the files, rather then guessing wheatear the file exists. Or you can use the OS library to check if the file exists first:

    if os.path.exists(file_path):
        #load image