Created
November 10, 2021 04:03
-
-
Save dooman87/b7cdd379785e286210af2c6de63e6ada to your computer and use it in GitHub Desktop.
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
func isIllustration(img []byte) (bool, error) { | |
mw := imagick.NewMagickWand() | |
err := mw.ReadImageBlob(img) | |
if err != nil { | |
return false, err | |
} | |
colorsCnt, colors = mw.GetImageHistogram() | |
// Sorting colors by number of occurrences. | |
colorsCounts := make([]int, colorsCnt) | |
for i, c := range colors { | |
colorsCounts[i] = int(c.GetColorCount()) | |
} | |
sort.Sort(sort.Reverse(sort.IntSlice(colorsCounts))) | |
var ( | |
colorIdx int | |
count int | |
imageWidth = mw.GetImageWidth() | |
imageHeight = mw.GetImageHeight() | |
pixelsCount = 0 | |
totalPixelsCount = float32(imageHeight * imageWidth) | |
fiftyPercent = int(totalPixelsCount * 0.5) | |
) | |
// Going through colors until reach 50% of all pixels | |
for colorIdx, count = range colorsCounts { | |
if pixelsCount > fiftyPercent { | |
break | |
} | |
pixelsCount += count | |
} | |
colorsCntIn50Pct := colorIdx + 1 | |
// Calculate ratio between number of colors used for 50% of the image and | |
// make a decision based on that. | |
return (float32(colorsCntIn50Pct)/float32(colorsCnt)) <= 0.02, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment