I'm using the filter CIAreaMinMax to get the brightest and darkest colour 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 that contains two similar colours, 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 has no problem.
The test image I am using is here, an png image only contains two colors:
RGB(37,62,88), GRB(10,132,255).
After processed by the code, it will output a png image that contains two pixels:
RGB(10,62,88), GRB(37,132,255).
In below is the test code for the swift playground:
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"))