Created
August 20, 2023 09:02
-
-
Save ZJUGuoShuai/a8ba4182ec6163da640e6a83e9634751 to your computer and use it in GitHub Desktop.
Display a OpenCV Mat using a UIImageView.
This file contains hidden or 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
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; | |
}); | |
} |
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
CAVEAT: it displays grayscale 8-bit (0-255 per pixel) images. For other pixel formats, you should change it accordingly.