0

So I have an image processing code where each pixel is processed in a nested loop. The difficulty I experience is catching all of the possible errors that might arise. One of them is a ValueError during the least squares fitting of the signal in the pixel, in which case I want the current pixel to be denoted as nan value and move on to the next pixel (the next loop).

I fully understand try except does NOT break out of a code, it just catches the error and ensures it does not stop the programme. However, when the code continues with the caught error, the said error causes me further problems down the line, so I need it break out of this nested loop instead. Example:

for i in range(x):                                 # iterate through each pixel in the image 
    for j in range(y): 
         ## some pre-processing code 
         try:                                      # catch any value errors during the fitting 
            result = scipy.least_squares( .. )
         except ValueError as ve:
            print(ve)
            ## process unsuccessful pixel fit as nan 
            # now want to break out of this nested loop and continue with j+=1
         # instead further processing continues and break the code   
              

I don't have much experience in error handling especially in this context, I can't seem to find anything that matches what I need. Any advice would be great.

ISquared
  • 364
  • 4
  • 22
  • 1
    Add `continue` after `print()` or put further code in `else` clause. Read: [4.4. `break` and `continue` Statements, and `else` Clauses on Loops](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops). – Olvin Roght Mar 14 '22 at 08:50
  • 1
    "in which case I want the current pixel to be denoted as nan value" Okay, so the way that you cause "the current pixel to be denoted" as something is by `result =`, yes? So... do that? "and move on to the next pixel (the next loop)." That happens automatically. "However, when the code continues with the caught error, the said error causes me further problems down the line" I don't understand. I thought you wanted to set the pixel value to nan? Why does it cause further problems? "so I need it break out of this nested loop instead." Okay, but then what should happen to the rest of the array? – Karl Knechtel Mar 14 '22 at 08:54
  • 1
    Oh, hold on. The question is how to skip code **after** the `except` block, and move directly to the next iteration of the loop? Yeah, that's `continue`. If you aren't familiar with such tools, you should probably follow a Python tutorial first, and *make sure you understand all the fundamentals*, before trying to solve a complex problem like image processing or working with libraries like SciPy. (That said, normally when you use tools like NumPy or SciPy, you don't want to write your own loops - they can normally handle looping for you.) – Karl Knechtel Mar 14 '22 at 08:56

0 Answers0