Skip to content

Instantly share code, notes, and snippets.

@dooman87
Created November 10, 2021 04:03
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 dooman87/b7cdd379785e286210af2c6de63e6ada to your computer and use it in GitHub Desktop.
Save dooman87/b7cdd379785e286210af2c6de63e6ada to your computer and use it in GitHub Desktop.
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