Last active
June 10, 2019 06:55
-
-
Save lqez/6bed9863012bb3494b3a5729793fbb73 to your computer and use it in GitHub Desktop.
Find almost 'white' images in the working directory
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 ( | |
"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