如何在Google Go中获取图像的FFT ?
Go DSP库(github.com/mjibson/go-dsp/fft)有一个2D FFT函数,具有以下签名:
func FFT2Real(x [][]float64) [][]complex128
如何将图像从标准go图像类型转换为float64?这是正确的方法吗?
这是文档的链接
您有两个选择,都涉及复制像素。您可以使用Image
接口提供的方法,即At(x,y)
,也可以将图像断言为image
包提供的图像类型之一,并直接访问Pix
属性。
由于您很可能会使用灰度图像,因此您可以轻松地将图像断言为输入*image.Gray
并直接访问像素,但为了抽象起见,我没有在示例中这样做:
inImage, _, err := image.Decode(inFile)
// error checking
bounds := inImage.Bounds()
realPixels := make([][]float64, bounds.Dy())
for y := 0; y < bounds.Dy(); y++ {
realPixels[y] = make([]float64, bounds.Dx())
for x := 0; x < bounds.Dx(); x++ {
r, _, _, _ := inImage.At(x, y).RGBA()
realPixels[y][x] = float64(r)
}
}
通过这种方式,您可以读取图像inImage
的所有像素,并将它们作为float64
值存储在二维切片中,准备由fft.FFT2Real
处理:
// apply discrete fourier transform on realPixels.
coeffs := fft.FFT2Real(realPixels)
// use inverse fourier transform to transform fft
// values back to the original image.
coeffs = fft.IFFT2(coeffs)
// write everything to a new image
outImage := image.NewGray(bounds)
for y := 0; y < bounds.Dy(); y++ {
for x := 0; x < bounds.Dx(); x++ {
px := uint8(cmplx.Abs(coeffs[y][x]))
outImage.SetGray(x, y, color.Gray{px})
}
}
err = png.Encode(outFile, outImage)
在上面的代码中,我对存储在realPixels
中的像素应用FFT,然后,看看它是否工作,对结果使用逆FFT。预期结果为原始图像。