Search code examples
exceptionpixeldm-script

Catching the "Pixel outside the boundaries" exception?


I have an image with atoms that are periodically arranged.

I am trying to write a script that does count how many atoms are arranged in first column by assigning a ROI on top-left atom, then let the script to scan from left to right (column by column). My idea is that, by using ROI that scans from left to right, and when it hits pixel that is out of boundaries (which means, it is out of image), the script returns the number of atoms in one line, instead of giving an error output saying "A pixel outside the boundaries of the image has been referenced".

Is there any way to make the above case possible to write in script?

Thank you.


Solution

  • You can catch any exception thrown by the script-code to handle it yourself using the

    Try(){ }
    Catch{ break; } 
    

    construct. However, this is not the nicest solution for your problem. If you know the size of your image, your really rather should use that knowledge to prevent accessing data outside the bonds. Using Try{}Catch{} is better left to those situation where "anything unexpected" could happen, and you still want to handle the problem.

    Here is a code example for your question.

    number boxSize = 3
    
    number sx = 10
    number sy = 10
    image img := realImage( "Test", 4, sx, sy )
    img = random()
    
    // Output "sum" over scanned ROI area
    
    // Variant 1: Just scan -- Hits an exception, as you're moving out of range
    /*
    for( number j=0;j<sy;j++)
        for( number i=0;i<sx;i++)
            {
                Result("\n ScanPos: " + i +" / " + j )
                Result("\t SUM: "+ sum( img[j,i,j+boxSize,i+boxSize] ) );
            }
    */
    
    // Variant 2: As above, but catch exception to just continue
    for( number j=0;j<sy;j++)
        for( number i=0;i<sx;i++)
            {
                Result("\n ScanPos: " + i +" / " + j )
                Try
                {
                    Result( "\t SUM: "+ sum( img[j,i,j+boxSize,i+boxSize] ) );
                }
                catch
                {
                    Result( "\t ROI OUT OF RANGE" )
                    break;      // Needed in scripting, or the exception is re-thrown
                }
            }
    
    // Variant 3: (Better) Avoid hitting the exception by using the knowlede of data size
    for( number j=0;j<sy-boxSize;j++)
        for( number i=0;i<sx-boxSize;i++)
            {
                Result("\n ScanPos: " + i +" / " + j )
                Result("\t SUM: "+ sum( img[j,i,j+boxSize,i+boxSize] ) );
            }