summaryrefslogtreecommitdiff
path: root/src/pkg/image/decode_test.go
blob: 0716ad9055b85ec56b3b898f1dc06f45516cfcec (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package image_test

import (
	"bufio"
	"image"
	"os"
	"testing"

	// TODO(nigeltao): implement bmp, gif and tiff decoders.
	_ "image/jpeg"
	_ "image/png"
)

const goldenFile = "testdata/video-001.png"

type imageTest struct {
	filename  string
	tolerance int
}

var imageTests = []imageTest{
	//{"testdata/video-001.bmp", 0},
	// GIF images are restricted to a 256-color palette and the conversion
	// to GIF loses significant image quality.
	//{"testdata/video-001.gif", 64<<8},
	// JPEG is a lossy format and hence needs a non-zero tolerance.
	{"testdata/video-001.jpeg", 8 << 8},
	{"testdata/video-001.png", 0},
	//{"testdata/video-001.tiff", 0},
}

func decode(filename string) (image.Image, string, os.Error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, "", err
	}
	defer f.Close()
	return image.Decode(bufio.NewReader(f))
}

func delta(u0, u1 uint32) int {
	d := int(u0) - int(u1)
	if d < 0 {
		return -d
	}
	return d
}

func withinTolerance(c0, c1 image.Color, tolerance int) bool {
	r0, g0, b0, a0 := c0.RGBA()
	r1, g1, b1, a1 := c1.RGBA()
	r := delta(r0, r1)
	g := delta(g0, g1)
	b := delta(b0, b1)
	a := delta(a0, a1)
	return r <= tolerance && g <= tolerance && b <= tolerance && a <= tolerance
}

func TestDecode(t *testing.T) {
	golden, _, err := decode(goldenFile)
	if err != nil {
		t.Errorf("%s: %v", goldenFile, err)
	}
loop:
	for _, it := range imageTests {
		m, _, err := decode(it.filename)
		if err != nil {
			t.Errorf("%s: %v", it.filename, err)
			continue loop
		}
		b := golden.Bounds()
		if !b.Eq(m.Bounds()) {
			t.Errorf("%s: want bounds %v got %v", it.filename, b, m.Bounds())
			continue loop
		}
		for y := b.Min.Y; y < b.Max.Y; y++ {
			for x := b.Min.X; x < b.Max.X; x++ {
				if !withinTolerance(golden.At(x, y), m.At(x, y), it.tolerance) {
					t.Errorf("%s: at (%d, %d), want %v got %v", it.filename, x, y, golden.At(x, y), m.At(x, y))
					continue loop
				}
			}
		}
	}
}