-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_difference.sf
60 lines (42 loc) · 1.03 KB
/
image_difference.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/ruby
#
## https://rosettacode.org/wiki/Percentage_difference_between_images
#
require('Imager')
func img_diff(a, b) {
func from_file(name) {
%O<Imager>.new(file => name)
}
func size(img) {
(img.getwidth, img.getheight)
}
func pixel_diff(p1, p2) {
[p1.rgba] »-« [p2.rgba] -> sum_by { .abs }
}
func read_pixel(img, x, y) {
img.getpixel(x => x, y => y)
}
func read_line(img, y) {
img.getscanline(y => y)
}
var(img1, img2) = (from_file(a), from_file(b))
var(w1, h1) = size(img1)
var(w2, h2) = size(img2)
if ((w1 != w2) || (h1 != h2)) {
return nil
}
var sum = 0
for y in (^h1) {
var *line1 = read_line(img1, y)
var *line2 = read_line(img2, y)
[line1, line2].zip {|p1, p2|
sum += pixel_diff(p1, p2)
}
}
sum / (w1 * h1 * 255 * 3)
}
if (ARGV.len != 2) {
say "usage: #{File(__MAIN__).basename} [img1] [img2]"
Sys.exit(1)
}
say 100*img_diff(ARGV[0], ARGV[1])