Last active
January 9, 2023 10:10
-
-
Save DennisWeidmann/7c4b4bb72062bd1a40c714aa5d95a0d7 to your computer and use it in GitHub Desktop.
Convert NSImage to CVPixelBuffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSImage { | |
func pixelBuffer() -> CVPixelBuffer? { | |
let width = self.size.width | |
let height = self.size.height | |
let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, | |
kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] as CFDictionary | |
var pixelBuffer: CVPixelBuffer? | |
let status = CVPixelBufferCreate(kCFAllocatorDefault, | |
Int(width), | |
Int(height), | |
kCVPixelFormatType_32ARGB, | |
attrs, | |
&pixelBuffer) | |
guard let resultPixelBuffer = pixelBuffer, status == kCVReturnSuccess else { | |
return nil | |
} | |
CVPixelBufferLockBaseAddress(resultPixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) | |
let pixelData = CVPixelBufferGetBaseAddress(resultPixelBuffer) | |
let rgbColorSpace = CGColorSpaceCreateDeviceRGB() | |
guard let context = CGContext(data: pixelData, | |
width: Int(width), | |
height: Int(height), | |
bitsPerComponent: 8, | |
bytesPerRow: CVPixelBufferGetBytesPerRow(resultPixelBuffer), | |
space: rgbColorSpace, | |
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue) else {return nil} | |
context.translateBy(x: 0, y: height) | |
context.scaleBy(x: 1.0, y: -1.0) | |
let graphicsContext = NSGraphicsContext(cgContext: context, flipped: false) | |
NSGraphicsContext.saveGraphicsState() | |
NSGraphicsContext.current = graphicsContext | |
draw(in: CGRect(x: 0, y: 0, width: width, height: height)) | |
NSGraphicsContext.restoreGraphicsState() | |
CVPixelBufferUnlockBaseAddress(resultPixelBuffer, CVPixelBufferLockFlags(rawValue: 0)) | |
return resultPixelBuffer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case someone else needs to convert NSImage to proper depthData, disparityData ,color and mask CVPixelBuffers that can be passed directly to a PhotogrammetrySample in ObjectCapture, I've modified the original code slightly to add the these functions:
It can also be found in this gist: https://gist.github.com/hradec/6f0dd29e1acfc90ad154588cac1918bd