注意:我用的 jpg 图片
UIImage*image1 = [UIImageimageNamed:@"image1"];
UIImage*image2 = [UIImageimageNamed:@"image2"];
cv::Matcv_image1 = [selfcvMatFromUIImage:image1];
cv::Matcv_image2 = [selfcvMatFromUIImage:image2];
//转换为灰度图片
// cv::Mat greyMat;
// cv::cvtColor(cv_image2, greyMat, cv::COLOR_BGR2GRAY);
// UIImage *image3= [self UIImageFromCVMat:greyMat];
- (cv::Mat)cvMatFromUIImage:(UIImage*)image
{
CGColorSpaceRefcolorSpace =CGImageGetColorSpace(image.CGImage);
CGFloatcols = image.size.width;
CGFloatrows = image.size.height;
cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels (color channels + alpha)
CGContextRefcontextRef =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);
returncvMat;
}
-(UIImage *)UIImageFromCVMat:(cv::Mat)cvMat
{
NSData*data = [NSDatadataWithBytes:cvMat.datalength:cvMat.elemSize()*cvMat.total()];
CGColorSpaceRef colorSpace;
if(cvMat.elemSize() ==1) {
colorSpace =CGColorSpaceCreateDeviceGray();
}else{
colorSpace =CGColorSpaceCreateDeviceRGB();
}
CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data);
// Creating CGImage from cv::Mat
CGImageRefimageRef =CGImageCreate(cvMat.cols, //width
cvMat.rows, //height
8, //bits per component
8* cvMat.elemSize(), //bits per pixel
cvMat.step[0], //bytesPerRow
colorSpace, //colorspace
kCGImageAlphaNone|kCGBitmapByteOrderDefault,// bitmap info
provider, //CGDataProviderRef
NULL, //decode
false, //should interpolate
kCGRenderingIntentDefault //intent
);
// Getting UIImage from CGImage
UIImage*finalImage = [UIImageimageWithCGImage:imageRef];
CGImageRelease(imageRef);
CGDataProviderRelease(provider);
CGColorSpaceRelease(colorSpace);
returnfinalImage;
}
网友评论