Convert UIImage to cv::Mat issue in OpenCV

2.4k Views Asked by At

I am trying to convert an UIImage to cv::Mat so I can use the LineIterator OpenCV class on it. I am using the code provided by the opencv documentation here, specifically the cvMatGrayFromUIImage found on that page. I used this code in a function I wrote and then called it in my swift files. However, when I try printing the cv::Mat image, the numbers in the array do not accurately reflect a grayscale of the input image. I put the array into Matlab and call the imagesc function to see if it is indeed grayscale.

Here is the code I am using in my OpenCVWrapper.mm

-(void) getPixelIntensity: (UIImage *)image
{

    //Transform UIImage to cv::Mat
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
    CGFloat cols = image.size.width;
    CGFloat rows = image.size.height;
    cv::Mat cvMat(rows, cols, CV_8UC1); // 8 bits per component, 1 channels
    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,                 // Pointer to 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), image.CGImage);
        CGContextRelease(contextRef);

//Print image matrix
cout << cvMat;
}

Then in my Viewcontroller.swift

I call the function like this

import UIKit

class ViewController: UIViewController{

    //MARK: Properties
    @IBOutlet weak var photoImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func getCoordinates(_ sender: UIButton) {
let opencvwrapper = OpenCVWrapper()
opencvwrapper.getPixelIntensity(photoImageView.image)
       }
}
1

There are 1 best solutions below

0
On

OpenCV provides some functions that allow you to convert UIImage to cv::Mat and vice versa.
1. Import the libraries on your wrapper header :

#import <opencv2/imgcodecs/ios.h>


2. You now have access to this functions :

UIImageToMat(uiImage, imageMat);
UIImage* img = MatToUIImage(imageMat);