2017-07-19 127 views
2

我想將一個UIImage轉換爲cv :: Mat,這樣我就可以在其上使用LineIterator OpenCV類。我在這裏使用opencv文檔提供的代碼,特別是在該頁面上找到的cvMatGrayFromUIImage。我在我寫的函數中使用了這段代碼,然後在我的swift文件中調用它。但是,當我嘗試打印cv :: Mat圖像時,數組中的數字不能準確反映輸入圖像的灰度。我把數組放到Matlab中,調用imagesc函數來查看它是否確實是灰度。在OpenCV中將UIImage轉換爲cv :: Mat問題

這裏是我用我的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; 
} 

然後在我的Viewcontroller.swift代碼

我這樣調用

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) 
     } 
} 

回答

3

OpenCV的功能提供了一些功能它允許你將UIImage轉換爲cv :: Mat,反之亦然。
導入你的包裝頭的庫:

#import <opencv2/imgcodecs/ios.h> 


2.您現在可以使用此功能:

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