Convert Uiimage From Bgr To Rgb
As the title suggests, I'm having some trouble with some UIImage color space conversions. The TL;DR version is that I need a way to convert a UIIMage in BGR format to RGB. Here's
Solution 1:
I don't think there's a way to do it using CoreImage
or CoreGraphics
since iOS does not give you much leeway with regards to creating custom colorspaces. However, I found something that may help using OpenCV from this article: https://sriraghu.com/2017/06/04/computer-vision-in-ios-swiftopencv/. It requires a bit of Objective-C but with a bridging header, the code will be hidden away once it's written.
- Add a new file -> ‘Cocoa Touch Class’, name it ‘OpenCVWrapper’ and set language to Objective-C. Click Next and select Create. When it prompted to create bridging header click on the ‘Create Bridging Header’ button. Now you can observe that there are 3 files created with names: OpenCVWrapper.h, OpenCVWrapper.m, and -Bridging-Header.h. Open ‘-Bridging-Header.h’ and add the following line: #import “OpenCVWrapper.h”
- Go to ‘OpenCVWrapper.h’ file and add the following lines of code:
#import <Foundation/Foundation.h>#import <UIKit/UIKit.h>@interfaceOpenCVWrapper: NSObject
+ (UIImage *) rgbImageFromBGRImage: (UIImage *) image;
@end
- Rename OpenCVWrapper.m to “OpenCVWrapper.mm” for C++ support and add the following code:
#import "OpenCVWrapper.h"// import necessary headers#import <opencv2/core.hpp>#import <opencv2/imgcodecs/ios.h>#import <opencv2/imgproc/imgproc.hpp>
using namespace cv;
@implementationOpenCVWrapper
+ (UIImage *) rgbImageFromBGRImage: (UIImage *) image {
// Convert UIImage to cv::Mat
Mat inputImage; UIImageToMat(image, inputImage);
// If input image has only one channel, then return image.if (inputImage.channels() == 1) return image;
// Convert the default OpenCV's BGR format to RGB.
Mat outputImage; cvtColor(inputImage, outputImage, CV_BGR2RGB);
// Convert the BGR OpenCV Mat to UIImage and return it.return MatToUIImage(outputImage);
}
@end
The minor difference from the linked article is they are converting BGR to grayscale but we are converting BGR to RGB (good thing OpenCV has tons of conversions!).
Finally...
Now that there is a bridging header to this Objective-C class you can use OpenCVWrapper
in Swift:
// assume bgrImage is your image from the serverlet rgbImage = OpenCVWrapper.rgbImage(fromBGR: bgrImage)
// double check the syntax on this ^ I'm not 100% sure how the bridging header will convert it
Post a Comment for "Convert Uiimage From Bgr To Rgb"