Last active
April 27, 2021 06:18
-
-
Save klingtnet/09041998a7a3c335da6c0636b9d9e53b to your computer and use it in GitHub Desktop.
Image comparison using MagickWand/ImageMagick in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"gopkg.in/gographics/imagick.v3/imagick" | |
) | |
func run(refFile, srcFile, prefix string) (err error) { | |
refMW := imagick.NewMagickWand() | |
defer refMW.Destroy() | |
srcMW := imagick.NewMagickWand() | |
defer srcMW.Destroy() | |
err = refMW.ReadImage(refFile) | |
if err != nil { | |
return | |
} | |
err = srcMW.ReadImage(srcFile) | |
if err != nil { | |
return | |
} | |
err = srcMW.SetImageCompose(imagick.COMPOSITE_OP_SRC) | |
if err != nil { | |
return | |
} | |
diffFn := func(name string, metric imagick.MetricType) { | |
diff, dist := srcMW.CompareImages(refMW, metric) | |
log.Printf("Distortion (%s): %f", name, dist) | |
defer diff.Destroy() | |
diff.WriteImage(prefix + "-" + name + ".jpg") | |
} | |
for name, metric := range map[string]imagick.MetricType{ | |
"perceptual-hash-error": imagick.METRIC_PERCEPTUAL_HASH_ERROR, | |
"undefined": imagick.METRIC_UNDEFINED, | |
"absolute-error": imagick.METRIC_ABSOLUTE_ERROR, | |
"fuzz-error": imagick.METRIC_FUZZ_ERROR, | |
"mean-absolute-error": imagick.METRIC_MEAN_ABSOLUTE_ERROR, | |
"mean-error-per-pixel": imagick.METRIC_MEAN_ERROR_PER_PIXEL, | |
"mean-squared-error": imagick.METRIC_MEAN_SQUARED_ERROR, | |
"normalized-corss-correlation-error": imagick.METRIC_NORMALIZED_CROSS_CORRELATION_ERROR, | |
"peak-absolute-error": imagick.METRIC_PEAK_ABSOLUTE_ERROR, | |
"peak-snr": imagick.METRIC_PEAK_SIGNAL_TO_NOISE_RATIO, | |
"rms-error": imagick.METRIC_ROOT_MEAN_SQUARED_ERROR, | |
} { | |
diffFn(name, metric) | |
} | |
return nil | |
} | |
func main() { | |
imagick.Initialize() | |
defer imagick.Terminate() | |
// This implements the following ImageMagick CLI command: | |
// compare -compose src reference.jpg source.jpg diff.jpg | |
run("reference.jpg", "source.jpg", "diff") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment