Ask Your Question
0

imread in iOS

asked 2013-05-14 13:25:33 -0500

Costantino gravatar image

updated 2013-05-15 01:59:29 -0500

Hi all, I'm working with OpenCV 2.4.3 in iOS. I want to read an image, so I use imread() function, but result Mat image is always empty.

    NSString *nsFileName = [destPath stringByAppendingPathComponent:imgSVMList[i]];
    std::string fileName = std::string([nsFileName UTF8String]);
    img = imread(fileName,CV_LOAD_IMAGE_GRAYSCALE);
    if (!img.data) {
        NSLog(@"Errore nella lettura dell'immagine");
    } else {
        NSLog(@"Rows: %i; Cols: %i",img.rows,img.cols);
    }

destPath is a Documets subfolder (/Documents/ImgSVM/) and imgSVMLista[] is a vector with images filename. So, nsFileName is, for example, <...>/Documents/ImgSVM/Img1.jpg. Well, img is alway empty.

image description

image description

As you can see rows and cols are 0 (The screenshot of the log was taken after the reading of the image). This is an example of image I want to read:

image description

Any suggestion? Costantino

edit retag flag offensive close merge delete

3 answers

Sort by ยป oldest newest most voted
1

answered 2013-05-15 04:52:44 -0500

AlexanderShishkov gravatar image

There are two ways:

1) Read images using iOS functions and convert UIImage to cv::Mat later.

NSString* filePath = [[NSBundle mainBundle]
                          pathForResource:@"demo" ofType:@"png"];
UIImage* resImage = [UIImage imageWithContentsOfFile:filePath];
cv::Mat cvImage;
UIImageToMat(resImage, cvImage);

2) Use imdecode() function

//create file handle
NSFileHandle* handle = [NSFileHandle fileHandleForReadingAtPath:fileName];
//read contents of the file
NSData *data = [handle readDataToEndOfFile];
//read image from the data buffer
cv::Mat cvImage = cv::imdecode(cv::Mat(1, [data length], CV_8UC1, (void*)data.bytes), CV_LOAD_IMAGE_UNCHANGED);
edit flag offensive delete link more

Comments

I had not thought to read the image using UIImage. It works, thanks.

Costantino gravatar imageCostantino ( 2013-05-15 11:42:26 -0500 )edit
0

answered 2017-04-07 15:14:24 -0500

Yuugi gravatar image

There's an native function for this.

#import <opencv2/imgcodecs/ios.h>

// t and m are UIImage* instances.
// transparentImage and maskImage are destination Mat.
// true/false is alpha condition.

UIImageToMat(t, transparentImage, true);
UIImageToMat(m, maskImage, true);
edit flag offensive delete link more
0

answered 2013-05-15 04:32:30 -0500

thomket gravatar image
edit flag offensive delete link more
Login/Signup to Answer

Question Tools

1 follower

Stats

Asked: 2013-05-14 13:25:33 -0500

Seen: 3,951 times

Last updated: May 15 '13