DM-scripting 中是否有累加函数?

Is there cumulative sum function in DM-scripting?

我想对图像数据做x方向或y方向的累加。 DM 脚本中是否有类似 Matlib 中的 "cumsum" 的函数? 谢谢!

例如一张 4x4 像素的图像,其像素值为

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

沿 x 方向的累积和将导致:

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 

有不同的方法可以实现这一点,但最快和最简单的方法可能是创建图像的“完全合并”版本。

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()

如果您想要一个 2D 图像作为结果,其中每个像素包含其左侧所有像素的总和,您可以通过添加偏移图像来实现:

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()

或者,您可以使用内部变量创建表达式,如

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 还提供了专门的、速度优化的命令:

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 )

另一种投影方式是矩阵乘法。将二维图像乘以 1 的一维矩阵会将图像投影到一维累积上。

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()

我也有一个

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()