1 // Copyright 2019 Google LLC.
2 // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
3 
4 // Image Diff:   Provides a metric for measuring the difference between two encoded images.   Prints
5 // out a single floating-point number between 0.0 and 1.0; 0 means that the images are identical; 1
6 // means that each pixel is maximally different in each channel.  A non-zero return value indicates
7 // that something went wrong.
8 
9 #include "include/codec/SkCodec.h"
10 #include "include/core/SkBitmap.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkPixmap.h"
13 #include "include/core/SkSize.h"
14 
15 #include <cmath>
16 #include <cstdio>
17 
main(int argc,char ** argv)18 int main(int argc, char** argv) {
19     if (argc != 3) {
20         const char usage[] = "\nUsage:\n  %s {FILE1}.png {FILE2}.png\n\n";
21         fprintf(stderr, usage, argv[0]);
22         return 1;
23     }
24     SkBitmap bm[2];
25     for (int i = 0; i < 2; ++i) {
26         const char* path = argv[i + 1];
27         if (std::unique_ptr<SkCodec> codec =
28                 SkCodec::MakeFromData(SkData::MakeFromFileName(path))) {
29             bm[i].allocN32Pixels(codec->dimensions().fWidth, codec->dimensions().fHeight);
30             if (SkCodec::kSuccess == codec->getPixels(bm[i].pixmap())) {
31                 continue;
32             }
33         }
34         fprintf(stderr, "\nBad file: '%s'.\n\n", path);
35         return 2;
36     }
37     SkISize dim = bm[0].dimensions();
38     if (dim != bm[1].dimensions()) {
39         fprintf(stderr, "\nImages must be same size: (%d,%d) != (%d,%d)\n\n",
40                 dim.fWidth, dim.fHeight, bm[1].dimensions().fWidth, bm[1].dimensions().fHeight);
41         return 3;
42     }
43     int64_t totalDiffs = 0; // Manhattan distance in ARGB color-space.
44     for (int y = 0; y < dim.fHeight; ++y) {
45         const uint8_t* row1 = reinterpret_cast<const uint8_t*>(bm[0].pixmap().addr32(0, y));
46         const uint8_t* row2 = reinterpret_cast<const uint8_t*>(bm[1].pixmap().addr32(0, y));
47         for (size_t i = 0; i < (size_t)dim.fWidth * (size_t)4; ++i) {
48             totalDiffs += std::abs((int)row1[i] - (int)row2[i]);
49         }
50     }
51     printf("%g\n", (double)totalDiffs /
52                    ((uint64_t)255 * 4 * (uint64_t)dim.fWidth * (uint64_t)dim.fHeight));
53     return 0;
54 }
55