[英]Convert UIImage to cv::Mat issue in OpenCV
I am trying to convert an UIImage to cv::Mat so I can use the LineIterator OpenCV class on it. 我正在尝试将UIImage转换为cv :: Mat,以便可以在其上使用LineIterator OpenCV类。 I am using the code provided by the opencv documentation here, specifically the cvMatGrayFromUIImage found on that page. 我正在使用opencv文档提供的代码,特别是在该页面上找到的cvMatGrayFromUIImage。 I used this code in a function I wrote and then called it in my swift files. 我在编写的函数中使用了此代码,然后在swift文件中对其进行了调用。 However, when I try printing the cv::Mat image, the numbers in the array do not accurately reflect a grayscale of the input image. 但是,当我尝试打印cv :: Mat图像时,数组中的数字不能准确反映输入图像的灰度。 I put the array into Matlab and call the imagesc function to see if it is indeed grayscale. 我将数组放入Matlab中,并调用imagesc函数来查看它是否确实是灰度的。
Here is the code I am using in my OpenCVWrapper.mm 这是我在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 然后在我的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)
}
}
OpenCV provides some functions that allow you to convert UIImage to cv::Mat and vice versa. OpenCV提供了一些功能,使您可以将UIImage转换为cv :: Mat,反之亦然。
1. Import the libraries on your wrapper header : 1.在您的包装标头上导入库:
#import <opencv2/imgcodecs/ios.h>
2. You now have access to this functions : 2.您现在可以使用以下功能:
UIImageToMat(uiImage, imageMat);
UIImage* img = MatToUIImage(imageMat);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.