Count colors in image: `NSCountedSet` and `colorAtX` are very slow

后端 未结 1 1580
盖世英雄少女心
盖世英雄少女心 2021-01-26 13:21

I\'m making an OS X app which creates a color scheme from the main colors of an image.

As a first step, I\'m using NSCountedSet and colorAtX to

相关标签:
1条回答
  • 2021-01-26 14:10

    The fastest alternative to colorAtX() would be iterating over the raw bytes of the image using let bitmapBytes = imageRep.bitmapData and composing the colour yourself from that information, which should be really simple if it's just RGBA data. Instead of your for x/y loop, do something like this...

    let bitmapBytes = imageRep.bitmapData
    var colors = Dictionary<UInt32, Int>()
    
    var index = 0
    for _ in 0..<(width * height) {
        let r = UInt32(bitmapBytes[index++])
        let g = UInt32(bitmapBytes[index++])
        let b = UInt32(bitmapBytes[index++])
        let a = UInt32(bitmapBytes[index++])
        let finalColor = (r << 24) + (g << 16) + (b << 8) + a   
    
        if colors[finalColor] == nil {
            colors[finalColor] = 1
        } else {
            colors[finalColor]!++
        }
    }
    

    You will have to check the order of the RGBA values though, I just guessed!

    The quickest way to maintain a count might just be a [Int, Int] dictionary of pixel values to counts, doing something like colors[color]++. Later on if you need to you can convert that to a NSColor using NSColor(calibratedRed red: CGFloat, green green: CGFloat, blue blue: CGFloat, alpha alpha: CGFloat)

    0 讨论(0)
提交回复
热议问题