Nigel Tao | 7483c6e | 2011-03-03 20:35:49 +1100 | [diff] [blame^] | 1 | // Copyright 2011 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package image_test |
| 6 | |
| 7 | import ( |
| 8 | "bufio" |
| 9 | "image" |
| 10 | "os" |
| 11 | "testing" |
| 12 | |
| 13 | // TODO(nigeltao): implement bmp, gif and tiff decoders. |
| 14 | _ "image/jpeg" |
| 15 | _ "image/png" |
| 16 | ) |
| 17 | |
| 18 | const goldenFile = "testdata/video-001.png" |
| 19 | |
| 20 | type imageTest struct { |
| 21 | filename string |
| 22 | tolerance int |
| 23 | } |
| 24 | |
| 25 | var imageTests = []imageTest{ |
| 26 | //{"testdata/video-001.bmp", 0}, |
| 27 | // GIF images are restricted to a 256-color palette and the conversion |
| 28 | // to GIF loses significant image quality. |
| 29 | //{"testdata/video-001.gif", 64<<8}, |
| 30 | // JPEG is a lossy format and hence needs a non-zero tolerance. |
| 31 | {"testdata/video-001.jpeg", 8 << 8}, |
| 32 | {"testdata/video-001.png", 0}, |
| 33 | //{"testdata/video-001.tiff", 0}, |
| 34 | } |
| 35 | |
| 36 | func decode(filename string) (image.Image, string, os.Error) { |
| 37 | f, err := os.Open(filename, os.O_RDONLY, 0400) |
| 38 | if err != nil { |
| 39 | return nil, "", err |
| 40 | } |
| 41 | defer f.Close() |
| 42 | return image.Decode(bufio.NewReader(f)) |
| 43 | } |
| 44 | |
| 45 | func delta(u0, u1 uint32) int { |
| 46 | d := int(u0) - int(u1) |
| 47 | if d < 0 { |
| 48 | return -d |
| 49 | } |
| 50 | return d |
| 51 | } |
| 52 | |
| 53 | func withinTolerance(c0, c1 image.Color, tolerance int) bool { |
| 54 | r0, g0, b0, a0 := c0.RGBA() |
| 55 | r1, g1, b1, a1 := c1.RGBA() |
| 56 | r := delta(r0, r1) |
| 57 | g := delta(g0, g1) |
| 58 | b := delta(b0, b1) |
| 59 | a := delta(a0, a1) |
| 60 | return r <= tolerance && g <= tolerance && b <= tolerance && a <= tolerance |
| 61 | } |
| 62 | |
| 63 | func TestDecode(t *testing.T) { |
| 64 | golden, _, err := decode(goldenFile) |
| 65 | if err != nil { |
| 66 | t.Errorf("%s: %v", goldenFile, err) |
| 67 | } |
| 68 | loop: |
| 69 | for _, it := range imageTests { |
| 70 | m, _, err := decode(it.filename) |
| 71 | if err != nil { |
| 72 | t.Errorf("%s: %v", it.filename, err) |
| 73 | continue loop |
| 74 | } |
| 75 | b := golden.Bounds() |
| 76 | if !b.Eq(m.Bounds()) { |
| 77 | t.Errorf("%s: want bounds %v got %v", it.filename, b, m.Bounds()) |
| 78 | continue loop |
| 79 | } |
| 80 | for y := b.Min.Y; y < b.Max.Y; y++ { |
| 81 | for x := b.Min.X; x < b.Max.X; x++ { |
| 82 | if !withinTolerance(golden.At(x, y), m.At(x, y), it.tolerance) { |
| 83 | t.Errorf("%s: at (%d, %d), want %v got %v", it.filename, x, y, golden.At(x, y), m.At(x, y)) |
| 84 | continue loop |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | } |