CIFilter CIAreaMinMax gives incorrect result

Hi, I'm using filter CIAreaMinMax to get the brightest and darkest color information from an image.

Normally the filter should output an image with two pixels (brightest and darkest). However, when I implement this filter to an image which contains two similar colors, then the result will be incorrect. The symptom of the incorrect result is, the two pixels' red channel has been switched, but G and B value have no problem.

The test image I am using is, an png image only contains two color:
RGB(37,62,88), GRB(10,132,255).
After processed by the code, it will output an image which contains two pixels:
RGB(10,62,88), GRB(37,132,255).

In below is the test code for swift playground:
Code Block import Cocoa
import CoreImage
import CoreGraphics
func saveImage(_ image: NSImage, atUrl url: URL) {
    let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil)!
    let newRep = NSBitmapImageRep(cgImage: cgImage)
    newRep.size = image.size
    let pngData = newRep.representation(using: .png, properties: [:])!
    try! pngData.write(to: url)
}
var sourceImage = CIImage.init(contentsOf: URL.init(fileURLWithPath: "/Users/ABC/Downloads/test.png"))!
let filter = CIFilter(name: "CIAreaMinMax")!
filter.setValue(sourceImage, forKey: kCIInputImageKey)
let civ = CIVector.init(x: sourceImage.extent.minX, y: sourceImage.extent.minY, z: sourceImage.extent.width, w: sourceImage.extent.height)
filter.setValue(civ, forKey: kCIInputExtentKey)
var filteredImage = filter.outputImage!
let context = CIContext(options: [.workingColorSpace: kCFNull!])
let filteredCGImageRef = context.createCGImage(
    filteredImage,
    from: filteredImage.extent)
let output = NSImage(cgImage: filteredCGImageRef!, size: NSSize.init(width: filteredImage.extent.width, height: filteredImage.extent.height))
saveImage(output, atUrl: URL.init(fileURLWithPath: "/Users/ABC/Downloads/output.png"))


Just wanted to cross-reference StackOverflow here.

This filter has produced the correct result. It looks at each channel separately and then creates new colours that contain the results.

I assume that your two pixels are rgb(37,62,88), rgb(10,132,255) (I really don't know what you mean by GRB, unless it's a typo).

In which case, here is a summary of the min and max:

min(r) = 10, max(r) = 37
min(g) = 62, max(g) = 132
min(b) = 88, max(b) = 255

Putting all of this together into two pixels gives us

min(rgb) = (10,62,88)
max(rgb) = (37,132,255)

... which is exactly that CIAreaMinMax is producing.

CIFilter CIAreaMinMax gives incorrect result
 
 
Q