Skip to content

Instantly share code, notes, and snippets.

@IronSavior
Last active February 5, 2022 01:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IronSavior/ff0d6a8a7635013cc7e2837c63c00386 to your computer and use it in GitHub Desktop.
Save IronSavior/ff0d6a8a7635013cc7e2837c63c00386 to your computer and use it in GitHub Desktop.
Compute mean luma of image files
package main
import (
"fmt"
"image"
"image/color"
_ "image/jpeg"
"os"
)
func MeanLuma(img image.Image) (mean float64) {
bounds := img.Bounds()
count := 0
for x := bounds.Min.X; x < bounds.Max.X; x++ {
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
count++
pixel := color.YCbCrModel.Convert(img.At(x, y)).(color.YCbCr)
luma := float64(pixel.Y)
mean += (luma - mean) / float64(count)
}
}
return
}
func LoadImageFile(path string) (image.Image, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, err
}
return img, nil
}
func main() {
for _, arg := range os.Args[1:] {
img, err := LoadImageFile(arg)
if err != nil {
fmt.Printf("Failed to load %q: %v\n", arg, err)
continue
}
fmt.Printf("%s: mean Luma: %v\n", arg, MeanLuma(img))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment