Search code examples
dm-script

Returning an image in a function


I am writing a function that takes in an image, modifies it, and returns the modified image.

Image SomeFunction(Image img)
{
   Image modified = img
   
   // modify the clone

   return modified
}

Now in the main code block, setting an image variable to be the returned clone throws off an error: "Unable to determine the physical size of this image expression". Passing an image is obviously not like in another language, say Python. Could someone please help?


Solution

  • In DM script, it is important to distinguish between and understand the two ways to do image assignment, via = or :=. Unfortunately, this is not covered very coherently in the on-line documentation (being only very briefly and tangentially covered in the "Types and Variables" and "Expressions" sections), so this is a common conundrum for those who are new to DM scripting.

    The key thing to realize is that := is really the only way to assign an Image object to an Image variable, like this:

    Image targeting := GetFrontImage();
    

    So this is probably what you are intending to do in your code.

    The simple = sign is only for pixel-by-pixel operations, so-called "image expressions". These are actually very powerful and the fastest way to change image pixel values in systematic ways via mathematical expressions (much, much faster and more efficient than using GetPixel() and SetPixel(), avoid these as much as possible). However, when doing such pixel-by-pixel assignments, it is important that images on both sides of the = sign have exactly the same dimensions and sizes.

    In fact, the simpler, faster, and more typical way to implement the sort of function you show in your example would be to truly clone the input image object and then modify its pixel values via an image expression, as follows:

    Image ModifyImage(Image inputImg)
    {
        Image modifiedImg := inputImg.ImageClone();
        modifiedImg = [a mathematical image expression];
    
        return modifiedImg;
    }