Created
April 25, 2014 08:33
-
-
Save Bwooce/11282166 to your computer and use it in GitHub Desktop.
Get the average and peak intensity (sum of r/g/b channels) of the centre 100x100px of an image.
This file contains 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 ( | |
"os" | |
"fmt" | |
"image/jpeg" | |
"bufio" | |
"log" | |
) | |
func main() { | |
if len(os.Args) < 2 { | |
log.Fatal("Supply filename as argument") | |
} | |
var fname = os.Args[1] | |
// open file | |
f,err := os.Open(fname) | |
if err != nil { | |
log.Fatal("File:", fname, "Error:", err) | |
} | |
defer f.Close() | |
fb := bufio.NewReader(f) | |
// decode | |
img, err := jpeg.Decode(fb) | |
if err != nil { | |
log.Fatal("File:", fname, "Error:", err) | |
} | |
// iterate over pixels, using a square of 100x100 in the middle | |
const SampleSize=100 | |
r := img.Bounds() | |
var totalPixels, peakR, peakG, peakB, avg uint32 | |
sizeX := r.Max.X - r.Min.X | |
sizeY := r.Max.Y - r.Min.Y | |
for x:=(sizeX/2)-(SampleSize/2); x < (sizeX/2)+(SampleSize/2); x++ { | |
for y:=(sizeY/2)-(SampleSize/2); y < (sizeY/2)+(SampleSize/2); y++ { | |
colour := img.At(x,y) | |
r,b,g,_ := colour.RGBA() | |
if r > peakR { | |
peakR = r | |
} | |
if g > peakG { | |
peakG = g | |
} | |
if b > peakB { | |
peakB = b | |
} | |
sum := r+b+g | |
avg += sum | |
totalPixels += 1 | |
} | |
} | |
avg /= (totalPixels * 3) | |
// print result | |
fmt.Println("Max possible", 0xFFFF, "over", totalPixels, "pixels") | |
fmt.Println("Average:", avg) | |
fmt.Println("Peaks:", peakR, peakG, peakB) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment