如果您正在尝试比较两个图像,只需将其煮沸为一个数字,以下内容将起作用.这在(例如)遗传算法中很有用,在遗传算法中,您要比较一组候选者并选择与参考图像差异最小的候选者:
image.At(x,y).RGBA())这个数字可以让您大致了解图像的差异程度.
如果您知道这两个图像都是image.RGBA(或者您可以转换它们)的实例,那么您可以更快地执行某些操作:直接从中获取字节RGBA.Pix.这就是我在这里做的,它比img.At(x,y).RGBA()每个像素对快大约10倍:
func FastCompare(img1, img2 *image.RGBA) (int64, error) {
if img1.Bounds() != img2.Bounds() {
return 0, fmt.Errorf("image bounds not equal: %+v, %+v", img1.Bounds(), img2.Bounds())
}
accumError := int64(0)
for i := 0; i < len(img1.Pix); i++ {
accumError += int64(sqDiffUInt8(img1.Pix[i], img2.Pix[i]))
}
return int64(math.Sqrt(float64(accumError))), nil
}
func sqDiffUInt8(x, y uint8) uint64 {
d := uint64(x) - uint64(y)
return d * d
}
Run Code Online (Sandbox Code Playgroud)
小智 5
试试https://github.com/vitali-fedulov/images。我写这个包是为了能够找到接近的重复项。有一个使用相同算法的实时网络演示,因此您可以了解该软件包如何满足您的需求。