如何在 Google Go 中对图像进行 FFT?
Go DSP 库 (github.com/mjibson/go-dsp/fft) 具有一个具有以下签名的 2D FFT 函数:
func FFT2Real(x [][]float64) [][]complex128
如何将图像从标准 go 图像类型转换为 float64?这是正确的方法吗?
最佳答案
您有两种选择,都涉及复制像素。您可以使用方法 provided by the Image
interface ,即 At(x,y)
或者您可以将图像断言为 image
数据包提供的图像类型之一并访问 Pix
直接属性。
由于您很可能会使用灰色图像,因此您可以轻松断言图像以键入 *image.Gray
并访问 the pixels directly但为了抽象起见,我没有在我的示例中:
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
并将它们存储为二维 slice 中的 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。预期结果是原始图像。
可以找到一个完整的例子here .
关于go - 在 Google Go 中对图像进行 FFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24578126/