Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(539)

Side by Side Diff: samples/image_diff.cc

Issue 1433543005: Cleanup image_diff.cc. (Closed) Base URL: https://pdfium.googlesource.com/pdfium@master
Patch Set: self review Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // This file input format is based loosely on 5 // This file input format is based loosely on
6 // Tools/DumpRenderTree/ImageDiff.m 6 // Tools/DumpRenderTree/ImageDiff.m
7 7
8 // The exact format of this tool's output to stdout is important, to match 8 // The exact format of this tool's output to stdout is important, to match
9 // what the run-webkit-tests script expects. 9 // what the run-webkit-tests script expects.
10 10
11 #include <assert.h> 11 #include <assert.h>
12 #include <stdint.h> 12 #include <stdint.h>
13 #include <stdio.h> 13 #include <stdio.h>
14 #include <string.h> 14 #include <string.h>
15 15
16 #include <algorithm> 16 #include <algorithm>
17 #include <iostream> 17 #include <iostream>
18 #include <map> 18 #include <map>
19 #include <string> 19 #include <string>
20 #include <vector> 20 #include <vector>
21 21
22 #include "../third_party/base/logging.h" 22 #include "../third_party/base/logging.h"
23 #include "../third_party/base/numerics/safe_conversions.h" 23 #include "../third_party/base/numerics/safe_conversions.h"
24 #include "image_diff_png.h" 24 #include "image_diff_png.h"
25 25
26 #if defined(OS_WIN) 26 #if defined(OS_WIN)
27 #include "windows.h" 27 #include <windows.h>
28 #endif 28 #endif
29 29
30 // Return codes used by this utility. 30 // Return codes used by this utility.
31 static const int kStatusSame = 0; 31 static const int kStatusSame = 0;
32 static const int kStatusDifferent = 1; 32 static const int kStatusDifferent = 1;
33 static const int kStatusError = 2; 33 static const int kStatusError = 2;
34 34
35 // Color codes. 35 // Color codes.
36 static const uint32_t RGBA_RED = 0x000000ff; 36 static const uint32_t RGBA_RED = 0x000000ff;
37 static const uint32_t RGBA_ALPHA = 0xff000000; 37 static const uint32_t RGBA_ALPHA = 0xff000000;
(...skipping 26 matching lines...) Expand all
64 } 64 }
65 65
66 // Creates the image from the given filename on disk, and returns true on 66 // Creates the image from the given filename on disk, and returns true on
67 // success. 67 // success.
68 bool CreateFromFilename(const std::string& path) { 68 bool CreateFromFilename(const std::string& path) {
69 FILE* f = fopen(path.c_str(), "rb"); 69 FILE* f = fopen(path.c_str(), "rb");
70 if (!f) 70 if (!f)
71 return false; 71 return false;
72 72
73 std::vector<unsigned char> compressed; 73 std::vector<unsigned char> compressed;
74 const int buf_size = 1024; 74 const size_t kBufSize = 1024;
75 unsigned char buf[buf_size]; 75 unsigned char buf[kBufSize];
76 size_t num_read = 0; 76 size_t num_read = 0;
77 while ((num_read = fread(buf, 1, buf_size, f)) > 0) { 77 while ((num_read = fread(buf, 1, kBufSize, f)) > 0) {
78 compressed.insert(compressed.end(), buf, buf + num_read); 78 compressed.insert(compressed.end(), buf, buf + num_read);
79 } 79 }
80 80
81 fclose(f); 81 fclose(f);
82 82
83 if (!image_diff_png::DecodePNG(&compressed[0], compressed.size(), 83 if (!image_diff_png::DecodePNG(&compressed[0], compressed.size(),
84 &data_, &w_, &h_)) { 84 &data_, &w_, &h_)) {
85 Clear(); 85 Clear();
86 return false; 86 return false;
87 } 87 }
88 return true; 88 return true;
89 } 89 }
90 90
91 void Clear() { 91 void Clear() {
92 w_ = h_ = 0; 92 w_ = h_ = 0;
93 data_.clear(); 93 data_.clear();
94 } 94 }
95 95
96 // Returns the RGBA value of the pixel at the given location 96 // Returns the RGBA value of the pixel at the given location
97 uint32_t pixel_at(int x, int y) const { 97 uint32_t pixel_at(int x, int y) const {
98 if (x >= 0 && x < w_ && y >= 0 && y < h_) 98 if (!pixel_in_bounds(x, y))
99 return *reinterpret_cast<const uint32_t*>(&(data_[(y * w_ + x) * 4])); 99 return 0;
100 return 0; 100 return *reinterpret_cast<const uint32_t*>(&(data_[pixel_address(x, y)]));
101 } 101 }
102 102
103 void set_pixel_at(int x, int y, uint32_t color) const { 103 void set_pixel_at(int x, int y, uint32_t color) {
104 if (x >= 0 && x < w_ && y >= 0 && y < h_) { 104 if (!pixel_in_bounds(x, y))
105 void* addr = &const_cast<unsigned char*>(&data_.front())[(y * w_ + x) * 4] ; 105 return;
106 *reinterpret_cast<uint32_t*>(addr) = color; 106
107 } 107 void* addr = &data_[pixel_address(x, y)];
108 *reinterpret_cast<uint32_t*>(addr) = color;
108 } 109 }
109 110
110 private: 111 private:
111 // pixel dimensions of the image 112 bool pixel_in_bounds(int x, int y) const {
112 int w_, h_; 113 return x >= 0 && x < w_ && y >= 0 && y < h_;
114 }
115
116 size_t pixel_address(int x, int y) const { return (y * w_ + x) * 4; }
117
118 // Pixel dimensions of the image.
119 int w_;
120 int h_;
113 121
114 std::vector<unsigned char> data_; 122 std::vector<unsigned char> data_;
115 }; 123 };
116 124
125 float CalculateDifferencePercentage(const Image& actual, int pixels_different) {
126 // Like the WebKit ImageDiff tool, we define percentage different in terms
127 // of the size of the 'actual' bitmap.
128 float total_pixels =
129 static_cast<float>(actual.w()) * static_cast<float>(actual.h());
130 if (total_pixels == 0) {
131 // When the bitmap is empty, they are 100% different.
132 return 100.0f;
133 }
134 return 100.0f * pixels_different / total_pixels;
135 }
136
137 void CountImageSizeMismatchAsPixelDifference(const Image& baseline,
138 const Image& actual,
139 int* pixels_different) {
140 int w = std::min(baseline.w(), actual.w());
141 int h = std::min(baseline.h(), actual.h());
142
143 // Count pixels that are a difference in size as also being different.
144 int max_w = std::max(baseline.w(), actual.w());
145 int max_h = std::max(baseline.h(), actual.h());
146 // These pixels are off the right side, not including the lower right corner.
147 *pixels_different += (max_w - w) * h;
148 // These pixels are along the bottom, including the lower right corner.
149 *pixels_different += (max_h - h) * max_w;
150 }
151
117 float PercentageDifferent(const Image& baseline, const Image& actual) { 152 float PercentageDifferent(const Image& baseline, const Image& actual) {
118 int w = std::min(baseline.w(), actual.w()); 153 int w = std::min(baseline.w(), actual.w());
119 int h = std::min(baseline.h(), actual.h()); 154 int h = std::min(baseline.h(), actual.h());
120 155
121 // Compute pixels different in the overlap. 156 // Compute pixels different in the overlap.
122 int pixels_different = 0; 157 int pixels_different = 0;
123 for (int y = 0; y < h; y++) { 158 for (int y = 0; y < h; ++y) {
124 for (int x = 0; x < w; x++) { 159 for (int x = 0; x < w; ++x) {
125 if (baseline.pixel_at(x, y) != actual.pixel_at(x, y)) 160 if (baseline.pixel_at(x, y) != actual.pixel_at(x, y))
126 pixels_different++; 161 ++pixels_different;
127 } 162 }
128 } 163 }
129 164
130 // Count pixels that are a difference in size as also being different. 165 CountImageSizeMismatchAsPixelDifference(baseline, actual, &pixels_different);
131 int max_w = std::max(baseline.w(), actual.w()); 166 return CalculateDifferencePercentage(actual, pixels_different);
132 int max_h = std::max(baseline.h(), actual.h());
133 // These pixels are off the right side, not including the lower right corner.
134 pixels_different += (max_w - w) * h;
135 // These pixels are along the bottom, including the lower right corner.
136 pixels_different += (max_h - h) * max_w;
137
138 // Like the WebKit ImageDiff tool, we define percentage different in terms
139 // of the size of the 'actual' bitmap.
140 float total_pixels = static_cast<float>(actual.w()) *
141 static_cast<float>(actual.h());
142 if (total_pixels == 0) {
143 // When the bitmap is empty, they are 100% different.
144 return 100.0f;
145 }
146 return 100.0f * pixels_different / total_pixels;
147 } 167 }
148 168
149 // FIXME: Replace with unordered_map when available. 169 // FIXME: Replace with unordered_map when available.
150 typedef std::map<uint32_t, int32_t> RgbaToCountMap; 170 typedef std::map<uint32_t, int32_t> RgbaToCountMap;
151 171
152 float HistogramPercentageDifferent(const Image& baseline, const Image& actual) { 172 float HistogramPercentageDifferent(const Image& baseline, const Image& actual) {
153 // TODO(johnme): Consider using a joint histogram instead, as described in 173 // TODO(johnme): Consider using a joint histogram instead, as described in
154 // "Comparing Images Using Joint Histograms" by Pass & Zabih 174 // "Comparing Images Using Joint Histograms" by Pass & Zabih
155 // http://www.cs.cornell.edu/~rdz/papers/pz-jms99.pdf 175 // http://www.cs.cornell.edu/~rdz/papers/pz-jms99.pdf
156 176
157 int w = std::min(baseline.w(), actual.w()); 177 int w = std::min(baseline.w(), actual.w());
158 int h = std::min(baseline.h(), actual.h()); 178 int h = std::min(baseline.h(), actual.h());
159 179
160 // Count occurences of each RGBA pixel value of baseline in the overlap. 180 // Count occurences of each RGBA pixel value of baseline in the overlap.
161 RgbaToCountMap baseline_histogram; 181 RgbaToCountMap baseline_histogram;
162 for (int y = 0; y < h; y++) { 182 for (int y = 0; y < h; ++y) {
163 for (int x = 0; x < w; x++) { 183 for (int x = 0; x < w; ++x) {
164 // hash_map operator[] inserts a 0 (default constructor) if key not found. 184 // hash_map operator[] inserts a 0 (default constructor) if key not found.
165 baseline_histogram[baseline.pixel_at(x, y)]++; 185 ++baseline_histogram[baseline.pixel_at(x, y)];
166 } 186 }
167 } 187 }
168 188
169 // Compute pixels different in the histogram of the overlap. 189 // Compute pixels different in the histogram of the overlap.
170 int pixels_different = 0; 190 int pixels_different = 0;
171 for (int y = 0; y < h; y++) { 191 for (int y = 0; y < h; ++y) {
172 for (int x = 0; x < w; x++) { 192 for (int x = 0; x < w; ++x) {
173 uint32_t actual_rgba = actual.pixel_at(x, y); 193 uint32_t actual_rgba = actual.pixel_at(x, y);
174 RgbaToCountMap::iterator it = baseline_histogram.find(actual_rgba); 194 RgbaToCountMap::iterator it = baseline_histogram.find(actual_rgba);
175 if (it != baseline_histogram.end() && it->second > 0) 195 if (it != baseline_histogram.end() && it->second > 0)
176 it->second--; 196 --it->second;
177 else 197 else
178 pixels_different++; 198 ++pixels_different;
179 } 199 }
180 } 200 }
181 201
182 // Count pixels that are a difference in size as also being different. 202 CountImageSizeMismatchAsPixelDifference(baseline, actual, &pixels_different);
183 int max_w = std::max(baseline.w(), actual.w()); 203 return CalculateDifferencePercentage(actual, pixels_different);
184 int max_h = std::max(baseline.h(), actual.h());
185 // These pixels are off the right side, not including the lower right corner.
186 pixels_different += (max_w - w) * h;
187 // These pixels are along the bottom, including the lower right corner.
188 pixels_different += (max_h - h) * max_w;
189
190 // Like the WebKit ImageDiff tool, we define percentage different in terms
191 // of the size of the 'actual' bitmap.
192 float total_pixels = static_cast<float>(actual.w()) *
193 static_cast<float>(actual.h());
194 if (total_pixels == 0) {
195 // When the bitmap is empty, they are 100% different.
196 return 100.0f;
197 }
198 return 100.0f * pixels_different / total_pixels;
199 } 204 }
200 205
201 void PrintHelp() { 206 void PrintHelp() {
202 fprintf(stderr, 207 fprintf(stderr,
203 "Usage:\n" 208 "Usage:\n"
204 " image_diff [--histogram] <compare file> <reference file>\n" 209 " image_diff [--histogram] <compare file> <reference file>\n"
205 " Compares two files on disk, returning 0 when they are the same;\n" 210 " Compares two files on disk, returning 0 when they are the same;\n"
206 " passing \"--histogram\" additionally calculates a diff of the\n" 211 " passing \"--histogram\" additionally calculates a diff of the\n"
207 " RGBA value histograms (which is resistant to shifts in layout)\n" 212 " RGBA value histograms (which is resistant to shifts in layout)\n"
208 " image_diff --diff <compare file> <reference file> <output file>\n" 213 " image_diff --diff <compare file> <reference file> <output file>\n"
(...skipping 15 matching lines...) Expand all
224 fprintf(stderr, "image_diff: Unable to open file \"%s\"\n", file2.c_str()); 229 fprintf(stderr, "image_diff: Unable to open file \"%s\"\n", file2.c_str());
225 return kStatusError; 230 return kStatusError;
226 } 231 }
227 232
228 if (compare_histograms) { 233 if (compare_histograms) {
229 float percent = HistogramPercentageDifferent(actual_image, baseline_image); 234 float percent = HistogramPercentageDifferent(actual_image, baseline_image);
230 const char* passed = percent > 0.0 ? "failed" : "passed"; 235 const char* passed = percent > 0.0 ? "failed" : "passed";
231 printf("histogram diff: %01.2f%% %s\n", percent, passed); 236 printf("histogram diff: %01.2f%% %s\n", percent, passed);
232 } 237 }
233 238
234 const char* diff_name = compare_histograms ? "exact diff" : "diff"; 239 const char* const diff_name = compare_histograms ? "exact diff" : "diff";
235 float percent = PercentageDifferent(actual_image, baseline_image); 240 float percent = PercentageDifferent(actual_image, baseline_image);
236 const char* passed = percent > 0.0 ? "failed" : "passed"; 241 const char* const passed = percent > 0.0 ? "failed" : "passed";
237 printf("%s: %01.2f%% %s\n", diff_name, percent, passed); 242 printf("%s: %01.2f%% %s\n", diff_name, percent, passed);
243
238 if (percent > 0.0) { 244 if (percent > 0.0) {
239 // failure: The WebKit version also writes the difference image to 245 // failure: The WebKit version also writes the difference image to
240 // stdout, which seems excessive for our needs. 246 // stdout, which seems excessive for our needs.
241 return kStatusDifferent; 247 return kStatusDifferent;
242 } 248 }
243 // success 249 // success
244 return kStatusSame; 250 return kStatusSame;
245
246 /* Untested mode that acts like WebKit's image comparator. I wrote this but
247 decided it's too complicated. We may use it in the future if it looks useful
248
249 char buffer[2048];
250 while (fgets(buffer, sizeof(buffer), stdin)) {
251
252 if (strncmp("Content-length: ", buffer, 16) == 0) {
253 char* context;
254 strtok_s(buffer, " ", &context);
255 int image_size = strtol(strtok_s(NULL, " ", &context), NULL, 10);
256
257 bool success = false;
258 if (image_size > 0 && actual_image.has_image() == 0) {
259 if (!actual_image.CreateFromStdin(image_size)) {
260 fputs("Error, input image can't be decoded.\n", stderr);
261 return 1;
262 }
263 } else if (image_size > 0 && baseline_image.has_image() == 0) {
264 if (!baseline_image.CreateFromStdin(image_size)) {
265 fputs("Error, baseline image can't be decoded.\n", stderr);
266 return 1;
267 }
268 } else {
269 fputs("Error, image size must be specified.\n", stderr);
270 return 1;
271 }
272 }
273
274 if (actual_image.has_image() && baseline_image.has_image()) {
275 float percent = PercentageDifferent(actual_image, baseline_image);
276 if (percent > 0.0) {
277 // failure: The WebKit version also writes the difference image to
278 // stdout, which seems excessive for our needs.
279 printf("diff: %01.2f%% failed\n", percent);
280 } else {
281 // success
282 printf("diff: %01.2f%% passed\n", percent);
283 }
284 actual_image.Clear();
285 baseline_image.Clear();
286 }
287
288 fflush(stdout);
289 }
290 */
291 } 251 }
292 252
293 bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) { 253 bool CreateImageDiff(const Image& image1, const Image& image2, Image* out) {
294 int w = std::min(image1.w(), image2.w()); 254 int w = std::min(image1.w(), image2.w());
295 int h = std::min(image1.h(), image2.h()); 255 int h = std::min(image1.h(), image2.h());
296 *out = Image(image1); 256 *out = Image(image1);
297 bool same = (image1.w() == image2.w()) && (image1.h() == image2.h()); 257 bool same = (image1.w() == image2.w()) && (image1.h() == image2.h());
298 258
299 // TODO(estade): do something with the extra pixels if the image sizes 259 // TODO(estade): do something with the extra pixels if the image sizes
300 // are different. 260 // are different.
301 for (int y = 0; y < h; y++) { 261 for (int y = 0; y < h; ++y) {
302 for (int x = 0; x < w; x++) { 262 for (int x = 0; x < w; ++x) {
303 uint32_t base_pixel = image1.pixel_at(x, y); 263 uint32_t base_pixel = image1.pixel_at(x, y);
304 if (base_pixel != image2.pixel_at(x, y)) { 264 if (base_pixel != image2.pixel_at(x, y)) {
305 // Set differing pixels red. 265 // Set differing pixels red.
306 out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA); 266 out->set_pixel_at(x, y, RGBA_RED | RGBA_ALPHA);
307 same = false; 267 same = false;
308 } else { 268 } else {
309 // Set same pixels as faded. 269 // Set same pixels as faded.
310 uint32_t alpha = base_pixel & RGBA_ALPHA; 270 uint32_t alpha = base_pixel & RGBA_ALPHA;
311 uint32_t new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA); 271 uint32_t new_pixel = base_pixel - ((alpha / 2) & RGBA_ALPHA);
312 out->set_pixel_at(x, y, new_pixel); 272 out->set_pixel_at(x, y, new_pixel);
(...skipping 22 matching lines...) Expand all
335 Image diff_image; 295 Image diff_image;
336 bool same = CreateImageDiff(baseline_image, actual_image, &diff_image); 296 bool same = CreateImageDiff(baseline_image, actual_image, &diff_image);
337 if (same) 297 if (same)
338 return kStatusSame; 298 return kStatusSame;
339 299
340 std::vector<unsigned char> png_encoding; 300 std::vector<unsigned char> png_encoding;
341 image_diff_png::EncodeRGBAPNG( 301 image_diff_png::EncodeRGBAPNG(
342 diff_image.data(), diff_image.w(), diff_image.h(), 302 diff_image.data(), diff_image.w(), diff_image.h(),
343 diff_image.w() * 4, &png_encoding); 303 diff_image.w() * 4, &png_encoding);
344 304
345 FILE *f = fopen(out_file.c_str(), "wb"); 305 FILE* f = fopen(out_file.c_str(), "wb");
346 if (!f) 306 if (!f)
347 return kStatusError; 307 return kStatusError;
348 308
349 size_t size = png_encoding.size(); 309 size_t size = png_encoding.size();
350 char *ptr = reinterpret_cast<char*>(&png_encoding.front()); 310 char* ptr = reinterpret_cast<char*>(&png_encoding.front());
351 if (fwrite(ptr, 1, size, f) != size) 311 if (fwrite(ptr, 1, size, f) != size)
352 return kStatusError; 312 return kStatusError;
353 313
354 return kStatusDifferent; 314 return kStatusDifferent;
355 } 315 }
356 316
357 int main(int argc, const char* argv[]) { 317 int main(int argc, const char* argv[]) {
358 bool histograms = false; 318 bool histograms = false;
359 bool produce_diff_image = false; 319 bool produce_diff_image = false;
360 std::string filename1; 320 std::string filename1;
361 std::string filename2; 321 std::string filename2;
362 std::string diff_filename; 322 std::string diff_filename;
363 323
364 int i; 324 int i;
365 for (i = 1; i < argc; ++i) { 325 for (i = 1; i < argc; ++i) {
366 const char* arg = argv[i]; 326 const char* arg = argv[i];
367 if (strstr(arg, "--") != arg) 327 if (strstr(arg, "--") != arg)
368 break; 328 break;
369 if (strcmp(arg, "--histogram") == 0) { 329 if (strcmp(arg, "--histogram") == 0) {
370 histograms = true; 330 histograms = true;
371 } else if (strcmp(arg, "--diff") == 0) { 331 } else if (strcmp(arg, "--diff") == 0) {
372 produce_diff_image = true; 332 produce_diff_image = true;
373 } 333 }
374 } 334 }
375 if (i < argc) { 335 if (i < argc)
376 filename1 = argv[i]; 336 filename1 = argv[i++];
377 ++i; 337 if (i < argc)
378 } 338 filename2 = argv[i++];
379 if (i < argc) { 339 if (i < argc)
380 filename2 = argv[i]; 340 diff_filename = argv[i++];
381 ++i;
382 }
383 if (i < argc) {
384 diff_filename = argv[i];
385 ++i;
386 }
387 341
388 if (produce_diff_image) { 342 if (produce_diff_image) {
389 if (!diff_filename.empty()) { 343 if (!diff_filename.empty()) {
390 return DiffImages(filename1, filename2, diff_filename); 344 return DiffImages(filename1, filename2, diff_filename);
391 } 345 }
392 } else if (!filename2.empty()) { 346 } else if (!filename2.empty()) {
393 return CompareImages(filename1, filename2, histograms); 347 return CompareImages(filename1, filename2, histograms);
394 } 348 }
395 349
396 PrintHelp(); 350 PrintHelp();
397 return kStatusError; 351 return kStatusError;
398 } 352 }
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698