Question: I have a UIImage which is a pic captured from an iPhone Camera now I want the UIImage to be converted to cv::Mat (OpenCV). I am using the following lines of code to accomplish this :

```
-(cv::Mat)CVMat
{

CGColorSpaceRef colorSpace = CGImageGetColorSpace(self.CGImage);
CGFloat cols = self.size.width;
CGFloat rows = self.size.height;

cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels

CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,                 // Pointer to backing data
                                                cols,                      // Width of bitmap
                                                rows,                     // Height of bitmap
                                                8,                          // Bits per component
                                                cvMat.step[0],              // Bytes per row
                                                colorSpace,                 // Colorspace
                                                kCGImageAlphaNoneSkipLast |
                                                kCGBitmapByteOrderDefault); // Bitmap info flags

CGContextDrawImage(contextRef, CGRectMake(0, 0, cols, rows), self.CGImage);
CGContextRelease(contextRef);

return cvMat;
}

```

This Code works fine for the UIImage in Landscape mode but when I use the same code with Images taken from Portrait mode the images gets rotated by 90 degrees towards the right.

I am a newbie in iOS and Objective C and hence I am not able to figure out what is wrong.

Can somebody tell me what is wrong with the code or am I missing out something.

Answer: 
You should consider using native OpenCV functions to convert forth and back :

```
#import <opencv2/imgcodecs/ios.h>
...
UIImage* MatToUIImage(const cv::Mat& image);
void UIImageToMat(const UIImage* image,
                         cv::Mat& m, bool alphaExist = false);

```

Note: if your UIImage comes from the camera, you should 'normalize' it ( iOS UIImagePickerController result image orientation after upload) before converting to `cv::Mat` since OpenCV does not take into account Exif data. If you don't do that the result should be misoriented.
I was trying to convert a portrait `UIImage` to `Mat` and back, but I had problems with both approaches of this post.

* The native approach with `MatToUIImage` and `UIImageToMat` resulted in a rotated image.
* The custom approach with `CGContext` ended up in a strange color bug (not only RGB / BGR swap). Red was red, blue was pink, green was yellow.

I ended up using the native `OpenCV` with a rotation:

```
#import <opencv2/imgcodecs/ios.h>

- (cv::Mat)convertUIImageToCVMat:(UIImage *)image
{
    cv::Mat imageMat;
    UIImageToMat(image, imageMat);
    cv::rotate(imageMat, imageMat, cv::ROTATE_90_CLOCKWISE);
    return imageMat;
}

- (UIImage *)convertCVMatToUIImage:(cv::Mat)cvMat
{
    UIImage *image = MatToUIImage(cvMat);
    return image;
}

```