I have an odd problem. I am rendering an image from the video camera, then later on I am trying to read the color of a pixel from the image.
Most of the time I don't have a problem. But there are times when my project tries to read the pixel data, I get a segmentation fault error and everything crashes. I think it is happening in the moments when that system is updating the UIImage/Buffer and it is between frames.
Since, it is not necessary for me to have the exact color every time I call getPixelColor(), I figured I could put in a guard statement and just return UIColor.Black. But since a lot of the extension function is using Structs/Primary/Unsafe types, and I get a error from the compiler saying I cannot unwrap those in Swift.
Is there a way to graceful way to catch this segmentation fault, or do I have to do something else?
This is the function that captures the image.
func renderImageFromColorCameraSampleBuffer( _ sampleBuffer: CMSampleBuffer ) {
if let cvPixels = CMSampleBufferGetImageBuffer( sampleBuffer ) {
let coreImage = CIImage( cvPixelBuffer: cvPixels )
let context = CIContext()
let rect = CGRect(
x: 0,
y: 0,
width: CGFloat( CVPixelBufferGetWidth(cvPixels) ),
height: CGFloat( CVPixelBufferGetHeight(cvPixels) )
)
let cgImage = context.createCGImage( coreImage, from: rect )
// What to use for the system
self.currentColorImage = UIImage( cgImage: cgImage! )
// Let the View Controller Know there is a new image to display.
SRLNotifications.postDisplayCamera(image: self.currentColorImage!)
}
}
This is what I am using to read the pixel data. [From a post on StackOver https://stackoverflow.com/a/25956283/2011541 ]
extension UIImage {
func getPixelColor(pos: CGPoint) -> UIColor {
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x) ) * 4
let r = CGFloat( data[pixelInfo] ) / CGFloat(255.0)
let g = CGFloat( data[pixelInfo+1] ) / CGFloat(255.0)
let b = CGFloat( data[pixelInfo+2] ) / CGFloat(255.0)
let a = CGFloat( data[pixelInfo+3] ) / CGFloat(255.0)
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}