Skip to content

Instantly share code, notes, and snippets.

@otmb
Last active February 19, 2023 10:18
Show Gist options
  • Save otmb/d4df9818d4f0bb70f2d14c2b1b688e2e to your computer and use it in GitHub Desktop.
Save otmb/d4df9818d4f0bb70f2d14c2b1b688e2e to your computer and use it in GitHub Desktop.
When you can't set `-all_load` to Other Linker Flags
// https://github.com/opencv/opencv/blob/master/modules/imgcodecs/src/ios_conversions.mm
// https://github.com/opencv/opencv/blob/master/modules/imgcodecs/src/apple_conversions.mm
func MatToCGImage(image:Mat) -> CGImage? {
let data = Data(bytes: image.dataPointer(), count: image.step1() * Int(image.rows()))
let colorSpace = image.elemSize() == 1 ? CGColorSpaceCreateDeviceGray() : CGColorSpaceCreateDeviceRGB()
let provider = CGDataProvider(data: data as CFData);
let alpha = image.channels() == 4;
let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: (alpha ? CGImageAlphaInfo.last : CGImageAlphaInfo.none).rawValue | CGBitmapInfo.byteOrderDefault.rawValue)
let cgImage = CGImage(width: Int(image.cols()),
height: Int(image.rows()),
bitsPerComponent: 8 * image.elemSize1(),
bitsPerPixel: 8 * image.elemSize(),
bytesPerRow: image.step1(),
space: colorSpace,
bitmapInfo: bitmapInfo,
provider: provider!,
decode: nil,
shouldInterpolate: false,
intent: CGColorRenderingIntent.defaultIntent
)
return cgImage
}
func MatToUIImage(image:Mat) -> UIImage {
let cgImage = MatToCGImage(image: image)
return UIImage(cgImage: cgImage!)
}
func CGImageToMat(image: CGImage, alphaExist: Bool = false) -> Mat {
var m = Mat()
var colorSpace = image.colorSpace!
let cols = CGFloat(image.width), rows = CGFloat(image.height)
let context: CGContext?
var bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
if (colorSpace.model == CGColorSpaceModel.monochrome)
{
m.create(rows: Int32(rows), cols: Int32(cols), type: CvType.CV_8UC1) // 8 bits per component, 1 channel
bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
if (alphaExist){
// m = Scalar(0)
}
}
else {
if (colorSpace.model == CGColorSpaceModel.indexed)
{
// CGBitmapContextCreate() does not support indexed color spaces.
colorSpace = CGColorSpaceCreateDeviceRGB();
}
m.create(rows: Int32(rows), cols: Int32(cols), type: CvType.CV_8UC4) // 8 bits per component, 4 channels
if (!alphaExist){
bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue | CGBitmapInfo.byteOrderDefault.rawValue )
} else {
// m = Scalar(0)
}
}
context = CGContext(data: m.dataPointer(), width: Int(m.cols()), height: Int(m.rows()),
bitsPerComponent: 8,
bytesPerRow: m.step1(), space: colorSpace,
bitmapInfo: bitmapInfo.rawValue)
context?.draw(image, in: CGRect(x: 0, y: 0, width: cols, height: rows))
return m
}
func UIImageToMat(image: UIImage, alphaExist: Bool = false) -> Mat {
return CGImageToMat(image: image.cgImage!, alphaExist: alphaExist)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment