maestromusica před 8 roky
rodič
revize
c76197d556
2 změnil soubory, kde provedl 85 přidání a 0 odebrání
  1. 43 0
      histogram.go
  2. 42 0
      histogram_test.go

+ 43 - 0
histogram.go

@@ -0,0 +1,43 @@
+package imaging
+
+import (
+	"image"
+)
+
+// Histogram returns a normalized histogram of an image.
+//
+// Resulting histogram is represented as an array of 256 floats, where
+// histogram[i] is a probability of a pixel being of a particular luminance i.
+func Histogram(img image.Image) [256]float64 {
+	src := toNRGBA(img)
+	width := src.Bounds().Max.X
+	height := src.Bounds().Max.Y
+
+	var histogram [256]float64
+	var total float64
+
+	if width == 0 || height == 0 {
+		return histogram		
+	}
+
+	for y := 0; y < height; y++ {
+		for x := 0; x < width; x++ {
+			i := y*src.Stride + x*4
+
+			r := src.Pix[i+0]
+			g := src.Pix[i+1]
+			b := src.Pix[i+2]
+
+			var y float32 = 0.299*float32(r) + 0.587*float32(g) + 0.114*float32(b)
+
+			histogram[int(y+0.5)]++
+			total++
+		}
+	}
+
+	for i := 0; i < 256; i++ {
+		histogram[i] = histogram[i] / total
+	}
+
+	return histogram
+}

+ 42 - 0
histogram_test.go

@@ -0,0 +1,42 @@
+package imaging
+
+import (
+	"image"
+	"image/color"
+	"testing"
+)
+
+func TestHistogram(t *testing.T) {
+	b := image.Rectangle{image.Point{0, 0}, image.Point{2, 2}}
+
+	i1 := image.NewRGBA(b)
+	i1.Set(0, 0, image.Black)
+	i1.Set(1, 0, image.White)
+	i1.Set(1, 1, image.White)
+	i1.Set(0, 1, color.Gray{123})
+
+	h := Histogram(i1)
+	if h[0] != 0.25 || h[123] != 0.25 || h[255] != 0.5 {
+		t.Errorf("Incorrect histogram for image i1")
+	}
+
+	i2 := image.NewRGBA(b)
+	i2.Set(0, 0, color.Gray{51})
+	i2.Set(0, 1, color.Gray{14})
+	i2.Set(1, 0, color.Gray{14})
+
+	h = Histogram(i2)
+	if h[14] != 0.5 || h[51] != 0.25 || h[0] != 0.25 {
+		t.Errorf("Incorrect histogram for image i2")
+	}
+
+	b = image.Rectangle{image.Point{0, 0}, image.Point{0, 0}}
+	i3 := image.NewRGBA(b)
+	h = Histogram(i3)
+	for _, val := range h {
+		if val != 0 {
+			t.Errorf("Histogram for an empty image should be a zero histogram.")
+			return 
+		}
+	}
+}