Вопрос

I have a question about OpenCV. I have a C++ example and I would to port this example in my iOS project. I have solved all compiler issues. I need to convert this c++ code:

char* filename;
    Mat input_image;

    //Check if user specify image to process
    if(argc >= 2 )
    {
        filename= argv[1];
        //load image  in gray level
        input_image=imread(filename,1);
    }else{
        printf("Use:\n\t%s image\n",argv[0]);
        return 0;
    } 

I have a UIImage an I would to obtain the corresponding Mat input_image. What'is the corresponding code of

//load image  in gray level
        input_image=imread(filename,1);?

I tried this but I have some problems and I not think that this is the correct code that correspond to imread(filename,1);

- (cv::Mat)cvMatFromUIImage:(UIImage *)image
{
  CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
  CGFloat cols = image.size.width;
  CGFloat rows = image.size.height;

  cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels (color channels + alpha)

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

  return cvMat;
}
Это было полезно?

Решение

The iOS code that you have added in your question is perfectly correct for converting UIImage to Mat(Without making it Grayscale)....

input_image=imread(filename,1);

The above line of code is used to load image from filename(It is path of image) and 1 is used to make it grayscale,

so for, loading image from filename, in ios we uses it as:

UIImage *image=[UIImage imagenamed:@"Hello.png"];

and pass this image to your method will do your work, now for making grayscale Mat, Make following changes in your code as:

Replace following lines:

CGColorSpaceRef colorSpace = CGImageGetColorSpace(image.CGImage);
cv::Mat cvMat(rows, cols, CV_8UC4);

With

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
cv::Mat cvMat = cv::Mat(rows, cols, CV_8UC1);

and add this line at end

CGColorSpaceRelease(colorSpace);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top