Skip to content

Instantly share code, notes, and snippets.

@AtomicVar
Created August 20, 2023 09:02
Show Gist options
  • Save AtomicVar/a8ba4182ec6163da640e6a83e9634751 to your computer and use it in GitHub Desktop.
Save AtomicVar/a8ba4182ec6163da640e6a83e9634751 to your computer and use it in GitHub Desktop.
Display a OpenCV Mat using a UIImageView.
void showOpenCVMat(cv::Mat img, UIImageView* imageView) {
cv::Mat converted;
img.convertTo(converted, CV_8U);
// convert the cv::Mat to UIImage
NSData *data = [NSData dataWithBytes:converted.data length:converted.elemSize() * converted.total()];
CGColorSpaceRef colorSpace =
CGColorSpaceCreateDeviceGray(); // CGColorSpaceCreateDeviceRGB();
CGDataProviderRef provider =
CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
CGImageRef imageRef = CGImageCreate(
converted.cols, converted.rows, 8, 8, converted.cols, colorSpace,
kCGBitmapByteOrderDefault | kCGImageAlphaNone, provider, NULL, false,
kCGRenderingIntentDefault);
UIImage *image = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
// show the UIImage on the UIImageView
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = image;
});
}
@AtomicVar
Copy link
Author

In your ViewController's viewDidLoad method:

- (void)viewDidLoad {
  [super viewDidLoad];

  UIImageView *imageView = [UIImageView new];
  imageView.frame        = self.view.bounds;
  [self.view addSubview:imageView];

  // ...
  showOpenCVMat(img, imageView);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment