Skip to content

Instantly share code, notes, and snippets.

@lqez
Last active June 10, 2019 06:55
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 lqez/6bed9863012bb3494b3a5729793fbb73 to your computer and use it in GitHub Desktop.
Save lqez/6bed9863012bb3494b3a5729793fbb73 to your computer and use it in GitHub Desktop.
Find almost 'white' images in the working directory
package main
import (
"os"
"fmt"
"image"
"log"
"path/filepath"
"sync"
_ "image/png"
)
var percent_threshold = 95.0
var white_threshold = uint32(0xfa)
var alpha_threshold = uint32(0xaf)
func test(filename string, wg *sync.WaitGroup) {
defer wg.Done()
reader, err := os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer reader.Close()
image, _, err := image.Decode(reader)
if err != nil {
log.Fatal(err)
}
bounds := image.Bounds()
var whitepixels = 0
var totalpixels = (bounds.Max.X - bounds.Min.X) * (bounds.Max.Y - bounds.Min.Y)
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
r, g, b, a := image.At(x, y).RGBA()
// RGBA() returns pre-multiplied color values, so make them back to non-multiplied values
if (a > 0) {
r = r * 0xff / a
g = g * 0xff / a
b = b * 0xff / a
}
a = a >> 8
if (a <= alpha_threshold) {
totalpixels--
} else {
if (r >= white_threshold && g >= white_threshold && b >= white_threshold) {
whitepixels++
}
}
}
}
var percent = float64(whitepixels) / float64(totalpixels) * 100
if percent_threshold < percent {
fmt.Printf("%-36s %6.2f%% (%d/%d)\n", filename, percent, whitepixels, totalpixels)
}
}
func main() {
wg := &sync.WaitGroup{}
files, err := filepath.Glob("*.png")
if err != nil {
log.Fatal(err)
}
for _, filename := range files {
wg.Add(1)
go test(filename, wg)
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment