Last active
February 5, 2022 01:27
-
-
Save IronSavior/ff0d6a8a7635013cc7e2837c63c00386 to your computer and use it in GitHub Desktop.
Compute mean luma of image files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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