w4m
w4m

Reputation: 145

Is there cumulative sum function in DM-scripting?

I would like to do cumulative sum along x or y direction of the image data. Is there any function in DM-scripting like "cumsum" in Matlib? Thanks!

for example an image of 4x4 pixels the pixel values are

1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

cumulative sum along x direction will result in:

1 1+2=3 1+2+3=6 1+2+3+4=10
2 5 9 14
3 7 12 18
4 9 15 22 

Upvotes: 0

Views: 463

Answers (3)

BmyGuest
BmyGuest

Reputation: 2949

There are differnt ways to achieve this, but potentially the fastest and easiest is to create a "fully binned" version of the image.

image img := GetFrontImage()
number sizeX, sizeY
img.GetSize( sizeX, sizeY )

image vSum = Rebin( img, 1, sizeY )
image hSum = Rebin( img, sizeX, 1 )
vSum.SetName( "vertical sum" )
vSum.ShowImage()
hSum.SetName( "horizontal sum" )
hSum.ShowImage()

If you want a 2D image as a result, where each pixel holds the sum of all its pixels to the left, you can do this by adding up offset images:

image img := GetFrontImage()
number sizeX, sizeY
img.GetSize( sizeX, sizeY )

image vCumSum := img.ImageClone() 
for( number x = 1; x<sizeX ; x++ )
{
    hCumSum += offset( img, -x, 0 )
}
hCumSum.SetName( "horizontal sum (cumulative)" )
hCumSum.ShowImage()

Alternatively, you can create an expression using intrinsic variables as in

image img := GetFrontImage()
image hCumSum := 0 * img.ImageClone() 
hCumSum += img[icol,irow] + hCumSum[ icol - 1, irow ]
hCumSum.SetName( "horizontal sum (cumulative)" )
hCumSum.ShowImage()

GMS 3.4 also offers a dedicated, speed optimized command:

RealImage Project( BasicImage img, Number axis )
RealImage Project( BasicImage img, Number axis, Boolean rescale )
void Project( BasicImage img, BasicImage dst, Number axis )
void Project( BasicImage img, BasicImage dst, Number axis, Boolean rescale )

Upvotes: 0

Renfong
Renfong

Reputation: 33

I also have one

image cumsum(image img)
//  computes the cumulative sum along x direction
{
    number sx, sy
    img.GetSize(sx,sy)

    for(number i=1; i<sx; i++)
    {
        img[0,i,sy,i+1]=img[0,i-1,sy,i]+img[0,i,sy,i+1]
    }
    return img
}

image im=getfrontimage()
im=im.cumsum()
im.showimage()

Upvotes: 0

user6406828
user6406828

Reputation: 11

Another way to do projection is by matrix multiplication. multiply a 2-D image by a 1-D matrix of 1's will project the image onto 1-D accumulation.

number d0, d1
image HProject, VProject, ones, img
img:=getfrontImage()
img.getSize(d0,d1)
ones:=exprSize(1,d0,1) 
HProject=MatrixMultiply(img,ones)
HProject.rotateLeft()
HProject.showImage()
ones:=exprSize(d1,1,1)
VProject=MatrixMultiply(ones,img)
VProject.showImage()

Upvotes: 0

Related Questions