16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIImageを様々なtypeのcv::Matへ変換したい時の単純な方法

Posted at

よくあるUIImageをOpenCVのcv::Matへ変換するときのコードは以下。

@interface UIImage(OpenCVUtility)
- (cv::Mat)cvMat;
@end
@implementation UIImage (OpenCVUtility)
-(cv::Mat)CVMat
{
    
    CGColorSpaceRef colorSpace = CGImageGetColorSpace(self.CGImage);
    CGFloat cols = self.size.width;
    CGFloat rows = self.size.height;
    
    cv::Mat cvMat(rows, cols, CV_8UC4); // 8 bits per component, 4 channels
    
    CGContextRef contextRef = CGBitmapContextCreate(cvMat.data,                 // Pointer to backing 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), self.CGImage);
    CGContextRelease(contextRef);
    
    return cvMat;
}
@end

これだと、CV_8UC4型のcv::Matしか扱えないのでここから任意の型のcv::Matを扱いたい時は以下のようにすれば面倒がない。

- (cv::Mat)cvMat32F:(cv::Mat)cvMat
{
    cv::Mat cvMat32F(cvMat.rows, cvMat.cols, CV_32F);
    cvMat.convertTo(cvMat32F, CV_32F);
    return cvMat32F;
}

効率は恐らくそんなに良くないけど手っ取り早く動かしたい時に。

16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?