Merge pull request #23513 from komakai:fix_unrecognized_selector

Fix "unrecognized selector" issue in Objective-C/Swift bindings
pull/23541/head
Alexander Smorkalov 2 years ago committed by GitHub
commit a4a9f56c8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 39
      modules/core/misc/objc/common/Mat.h
  2. 55
      modules/core/misc/objc/common/Mat.mm
  3. 32
      modules/imgcodecs/misc/objc/ios/Mat+Converters.h
  4. 44
      modules/imgcodecs/misc/objc/ios/Mat+Converters.mm
  5. 32
      modules/imgcodecs/misc/objc/ios/MatConverters.h
  6. 40
      modules/imgcodecs/misc/objc/ios/MatConverters.mm
  7. 6
      modules/imgcodecs/misc/objc/ios/MatQuickLook.h
  8. 65
      modules/imgcodecs/misc/objc/ios/MatQuickLook.mm
  9. 32
      modules/imgcodecs/misc/objc/macosx/Mat+Converters.h
  10. 44
      modules/imgcodecs/misc/objc/macosx/Mat+Converters.mm
  11. 32
      modules/imgcodecs/misc/objc/macosx/MatConverters.h
  12. 40
      modules/imgcodecs/misc/objc/macosx/MatConverters.mm
  13. 6
      modules/imgcodecs/misc/objc/macosx/MatQuickLook.h
  14. 50
      modules/imgcodecs/misc/objc/macosx/MatQuickLook.mm
  15. 5
      modules/objc/generator/gen_objc.py
  16. 2
      modules/objc/generator/templates/cmakelists.template

@ -14,6 +14,14 @@
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>
#ifdef AVAILABLE_IMGCODECS
#if TARGET_OS_IPHONE
#import <UIKit/UIKit.h>
#elif TARGET_OS_MAC
#import <AppKit/AppKit.h>
#endif
#endif
@class Size2i; @class Size2i;
@class Scalar; @class Scalar;
@class Range; @class Range;
@ -181,6 +189,37 @@ CV_EXPORTS @interface Mat : NSObject
- (int)put:(NSArray<NSNumber*>*)indices count:(int)count intBuffer:(const int*)buffer NS_REFINED_FOR_SWIFT; - (int)put:(NSArray<NSNumber*>*)indices count:(int)count intBuffer:(const int*)buffer NS_REFINED_FOR_SWIFT;
- (int)put:(NSArray<NSNumber*>*)indices count:(int)count shortBuffer:(const short*)buffer NS_REFINED_FOR_SWIFT; - (int)put:(NSArray<NSNumber*>*)indices count:(int)count shortBuffer:(const short*)buffer NS_REFINED_FOR_SWIFT;
#pragma mark - Converters
#ifdef AVAILABLE_IMGCODECS
- (CGImageRef)toCGImage CF_RETURNS_RETAINED;
- (instancetype)initWithCGImage:(CGImageRef)image;
- (instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist;
#if TARGET_OS_IPHONE
- (UIImage*)toUIImage;
- (instancetype)initWithUIImage:(UIImage*)image;
- (instancetype)initWithUIImage:(UIImage*)image alphaExist:(BOOL)alphaExist;
#elif TARGET_OS_MAC
- (NSImage*)toNSImage;
- (instancetype)initWithNSImage:(NSImage*)image;
- (instancetype)initWithNSImage:(NSImage*)image alphaExist:(BOOL)alphaExist;
#endif
#endif
#pragma mark - QuickLook
#ifdef AVAILABLE_IMGCODECS
- (id)debugQuickLookObject;
#endif
@end @end

@ -13,6 +13,11 @@
#import "CvType.h" #import "CvType.h"
#import "CVObjcUtil.h" #import "CVObjcUtil.h"
#ifdef AVAILABLE_IMGCODECS
#import "MatConverters.h"
#import "MatQuickLook.h"
#endif
static int idx2Offset(cv::Mat* mat, std::vector<int>& indices) { static int idx2Offset(cv::Mat* mat, std::vector<int>& indices) {
int offset = indices[0]; int offset = indices[0];
for (int dim=1; dim < mat->dims; dim++) { for (int dim=1; dim < mat->dims; dim++) {
@ -932,4 +937,54 @@ template<typename T> int putData(NSArray<NSNumber*>* indices, cv::Mat* mat, int
return [self cols]; return [self cols];
} }
#ifdef AVAILABLE_IMGCODECS
-(CGImageRef)toCGImage {
return [MatConverters convertMatToCGImageRef:self];
}
-(instancetype)initWithCGImage:(CGImageRef)image {
return [MatConverters convertCGImageRefToMat:image];
}
-(instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist {
return [MatConverters convertCGImageRefToMat:image alphaExist:alphaExist];
}
#if TARGET_OS_IPHONE
-(UIImage*)toUIImage {
return [MatConverters converMatToUIImage:self];
}
-(instancetype)initWithUIImage:(UIImage*)image {
return [MatConverters convertUIImageToMat:image];
}
-(instancetype)initWithUIImage:(UIImage*)image alphaExist:(BOOL)alphaExist {
return [MatConverters convertUIImageToMat:image alphaExist:alphaExist];
}
#elif TARGET_OS_MAC
-(NSImage*)toNSImage {
return [MatConverters converMatToNSImage:self];
}
-(instancetype)initWithNSImage:(NSImage*)image {
return [MatConverters convertNSImageToMat:image];
}
-(instancetype)initWithNSImage:(NSImage*)image alphaExist:(BOOL)alphaExist {
return [MatConverters convertNSImageToMat:image alphaExist:alphaExist];
}
#endif
- (id)debugQuickLookObject {
return [MatQuickLook matDebugQuickLookObject:self];
}
#endif
@end @end

@ -1,32 +0,0 @@
//
// Mat+Converters.h
//
// Created by Giles Payne on 2020/03/03.
//
#pragma once
#ifdef __cplusplus
#import "opencv2/core.hpp"
#else
#define CV_EXPORTS
#endif
#import "Mat.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
CV_EXPORTS @interface Mat (Converters)
-(CGImageRef)toCGImage CF_RETURNS_RETAINED;
-(instancetype)initWithCGImage:(CGImageRef)image;
-(instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist;
-(UIImage*)toUIImage;
-(instancetype)initWithUIImage:(UIImage*)image;
-(instancetype)initWithUIImage:(UIImage*)image alphaExist:(BOOL)alphaExist;
@end
NS_ASSUME_NONNULL_END

@ -1,44 +0,0 @@
//
// Mat+Converters.mm
//
// Created by Giles Payne on 2020/03/03.
//
#import "Mat+Converters.h"
#import <opencv2/imgcodecs/ios.h>
@implementation Mat (Converters)
-(CGImageRef)toCGImage {
return MatToCGImage(self.nativeRef);
}
-(instancetype)initWithCGImage:(CGImageRef)image {
return [self initWithCGImage:image alphaExist:NO];
}
-(instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist {
self = [self init];
if (self) {
CGImageToMat(image, self.nativeRef, (bool)alphaExist);
}
return self;
}
-(UIImage*)toUIImage {
return MatToUIImage(self.nativeRef);
}
-(instancetype)initWithUIImage:(UIImage*)image {
return [self initWithUIImage:image alphaExist:NO];
}
-(instancetype)initWithUIImage:(UIImage*)image alphaExist:(BOOL)alphaExist {
self = [self init];
if (self) {
UIImageToMat(image, self.nativeRef, (bool)alphaExist);
}
return self;
}
@end

@ -0,0 +1,32 @@
//
// MatConverters.h
//
// Created by Giles Payne on 2020/03/03.
//
#pragma once
#ifdef __cplusplus
#import "opencv2/core.hpp"
#else
#define CV_EXPORTS
#endif
#import "Mat.h"
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
CV_EXPORTS @interface MatConverters : NSObject
+(CGImageRef)convertMatToCGImageRef:(Mat*)mat CF_RETURNS_RETAINED;
+(Mat*)convertCGImageRefToMat:(CGImageRef)image;
+(Mat*)convertCGImageRefToMat:(CGImageRef)image alphaExist:(BOOL)alphaExist;
+(UIImage*)converMatToUIImage:(Mat*)mat;
+(Mat*)convertUIImageToMat:(UIImage*)image;
+(Mat*)convertUIImageToMat:(UIImage*)image alphaExist:(BOOL)alphaExist;
@end
NS_ASSUME_NONNULL_END

@ -0,0 +1,40 @@
//
// MatConverters.mm
//
// Created by Giles Payne on 2020/03/03.
//
#import "MatConverters.h"
#import <opencv2/imgcodecs/ios.h>
@implementation MatConverters
+(CGImageRef)convertMatToCGImageRef:(Mat*)mat {
return MatToCGImage(mat.nativeRef);
}
+(Mat*)convertCGImageRefToMat:(CGImageRef)image {
return [MatConverters convertCGImageRefToMat:image alphaExist:NO];
}
+(Mat*)convertCGImageRefToMat:(CGImageRef)image alphaExist:(BOOL)alphaExist {
Mat* mat = [Mat new];
CGImageToMat(image, mat.nativeRef, (bool)alphaExist);
return mat;
}
+(UIImage*)converMatToUIImage:(Mat*)mat {
return MatToUIImage(mat.nativeRef);
}
+(Mat*)convertUIImageToMat:(UIImage*)image {
return [MatConverters convertUIImageToMat:image alphaExist:NO];
}
+(Mat*)convertUIImageToMat:(UIImage*)image alphaExist:(BOOL)alphaExist {
Mat* mat = [Mat new];
UIImageToMat(image, mat.nativeRef, (bool)alphaExist);
return mat;
}
@end

@ -1,5 +1,5 @@
// //
// Mat+QuickLook.h // MatQuickLook.h
// //
// Created by Giles Payne on 2021/07/18. // Created by Giles Payne on 2021/07/18.
// //
@ -18,9 +18,9 @@
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
CV_EXPORTS @interface Mat (QuickLook) CV_EXPORTS @interface MatQuickLook : NSObject
- (id)debugQuickLookObject; + (id)matDebugQuickLookObject:(Mat*)mat;
@end @end

@ -1,11 +1,10 @@
// //
// Mat+QuickLook.mm // MatQuickLook.mm
// //
// Created by Giles Payne on 2021/07/18. // Created by Giles Payne on 2021/07/18.
// //
#import "Mat+QuickLook.h" #import "MatQuickLook.h"
#import "Mat+Converters.h"
#import "Rect2i.h" #import "Rect2i.h"
#import "Core.h" #import "Core.h"
#import "Imgproc.h" #import "Imgproc.h"
@ -39,9 +38,9 @@ static UIFont* getSystemFont() {
typedef UIFont* (*FontGetter)(); typedef UIFont* (*FontGetter)();
@implementation Mat (QuickLook) @implementation MatQuickLook
- (NSString*)makeLabel:(BOOL)isIntType val:(NSNumber*)num { + (NSString*)makeLabel:(BOOL)isIntType val:(NSNumber*)num {
if (isIntType) { if (isIntType) {
return [NSString stringWithFormat:@"%d", num.intValue]; return [NSString stringWithFormat:@"%d", num.intValue];
} else { } else {
@ -56,31 +55,31 @@ typedef UIFont* (*FontGetter)();
} }
} }
- (void)relativeLine:(UIBezierPath*)path relX:(CGFloat)x relY:(CGFloat)y { + (void)relativeLine:(UIBezierPath*)path relX:(CGFloat)x relY:(CGFloat)y {
CGPoint curr = path.currentPoint; CGPoint curr = path.currentPoint;
[path addLineToPoint:CGPointMake(curr.x + x, curr.y + y)]; [path addLineToPoint:CGPointMake(curr.x + x, curr.y + y)];
} }
- (id)debugQuickLookObject { + (id)matDebugQuickLookObject:(Mat*)mat {
if ([self dims] == 2 && [self rows] <= 10 && [self cols] <= 10 && [self channels] == 1) { if ([mat dims] == 2 && [mat rows] <= 10 && [mat cols] <= 10 && [mat channels] == 1) {
FontGetter fontGetters[] = { getCMU, getBodoni72, getAnySerif, getSystemFont }; FontGetter fontGetters[] = { getCMU, getBodoni72, getAnySerif, getSystemFont };
UIFont* font = nil; UIFont* font = nil;
for (int fontGetterIndex = 0; font==nil && fontGetterIndex < (sizeof(fontGetters)) / (sizeof(fontGetters[0])); fontGetterIndex++) { for (int fontGetterIndex = 0; font==nil && fontGetterIndex < (sizeof(fontGetters)) / (sizeof(fontGetters[0])); fontGetterIndex++) {
font = fontGetters[fontGetterIndex](); font = fontGetters[fontGetterIndex]();
} }
int elements = [self rows] * [self cols]; int elements = [mat rows] * [mat cols];
NSDictionary<NSAttributedStringKey,id>* textFontAttributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.blackColor }; NSDictionary<NSAttributedStringKey,id>* textFontAttributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.blackColor };
NSMutableArray<NSNumber*>* rawData = [NSMutableArray new]; NSMutableArray<NSNumber*>* rawData = [NSMutableArray new];
for (int dataIndex = 0; dataIndex < elements; dataIndex++) { for (int dataIndex = 0; dataIndex < elements; dataIndex++) {
[rawData addObject:[NSNumber numberWithDouble:0]]; [rawData addObject:[NSNumber numberWithDouble:0]];
} }
[self get:0 col: 0 data: rawData]; [mat get:0 col: 0 data: rawData];
BOOL isIntType = [self depth] <= CV_32S; BOOL isIntType = [mat depth] <= CV_32S;
NSMutableArray<NSString*>* labels = [NSMutableArray new]; NSMutableArray<NSString*>* labels = [NSMutableArray new];
NSMutableDictionary<NSString*, NSValue*>* boundingRects = [NSMutableDictionary dictionaryWithCapacity:elements]; NSMutableDictionary<NSString*, NSValue*>* boundingRects = [NSMutableDictionary dictionaryWithCapacity:elements];
int maxWidth = 0, maxHeight = 0; int maxWidth = 0, maxHeight = 0;
for (NSNumber* number in rawData) { for (NSNumber* number in rawData) {
NSString* label = [self makeLabel:isIntType val:number]; NSString* label = [MatQuickLook makeLabel:isIntType val:number];
[labels addObject:label]; [labels addObject:label];
CGRect boundingRect = [label boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:textFontAttributes context:nil]; CGRect boundingRect = [label boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:textFontAttributes context:nil];
if (boundingRect.size.width > maxWidth) { if (boundingRect.size.width > maxWidth) {
@ -97,18 +96,18 @@ typedef UIFont* (*FontGetter)();
int borderGap = 8; int borderGap = 8;
int lineThickness = 3; int lineThickness = 3;
int lipWidth = 6; int lipWidth = 6;
int imageWidth = 2 * (borderGap + lipWidth) + maxWidth * [self cols] + colGap * ([self cols] - 1); int imageWidth = 2 * (borderGap + lipWidth) + maxWidth * [mat cols] + colGap * ([mat cols] - 1);
int imageHeight = 2 * (borderGap + lipWidth) + maxHeight * [self rows] + rowGap * ([self rows] - 1); int imageHeight = 2 * (borderGap + lipWidth) + maxHeight * [mat rows] + rowGap * ([mat rows] - 1);
UIBezierPath* leftBracket = [UIBezierPath new]; UIBezierPath* leftBracket = [UIBezierPath new];
[leftBracket moveToPoint:CGPointMake(borderGap, borderGap)]; [leftBracket moveToPoint:CGPointMake(borderGap, borderGap)];
[self relativeLine:leftBracket relX:0 relY:imageHeight - 2 * borderGap]; [MatQuickLook relativeLine:leftBracket relX:0 relY:imageHeight - 2 * borderGap];
[self relativeLine:leftBracket relX:lineThickness + lipWidth relY:0]; [MatQuickLook relativeLine:leftBracket relX:lineThickness + lipWidth relY:0];
[self relativeLine:leftBracket relX:0 relY:-lineThickness]; [MatQuickLook relativeLine:leftBracket relX:0 relY:-lineThickness];
[self relativeLine:leftBracket relX:-lipWidth relY:0]; [MatQuickLook relativeLine:leftBracket relX:-lipWidth relY:0];
[self relativeLine:leftBracket relX:0 relY:-(imageHeight - 2 * (borderGap + lineThickness))]; [MatQuickLook relativeLine:leftBracket relX:0 relY:-(imageHeight - 2 * (borderGap + lineThickness))];
[self relativeLine:leftBracket relX:lipWidth relY:0]; [MatQuickLook relativeLine:leftBracket relX:lipWidth relY:0];
[self relativeLine:leftBracket relX:0 relY:-lineThickness]; [MatQuickLook relativeLine:leftBracket relX:0 relY:-lineThickness];
[leftBracket closePath]; [leftBracket closePath];
CGAffineTransform reflect = CGAffineTransformConcat(CGAffineTransformMakeTranslation(-imageWidth, 0), CGAffineTransformMakeScale(-1, 1)); CGAffineTransform reflect = CGAffineTransformConcat(CGAffineTransformMakeTranslation(-imageWidth, 0), CGAffineTransformMakeScale(-1, 1));
UIBezierPath* rightBracket = [leftBracket copy]; UIBezierPath* rightBracket = [leftBracket copy];
@ -124,8 +123,8 @@ typedef UIFont* (*FontGetter)();
[labels enumerateObjectsUsingBlock:^(id label, NSUInteger index, BOOL *stop) [labels enumerateObjectsUsingBlock:^(id label, NSUInteger index, BOOL *stop)
{ {
CGRect boundingRect = boundingRects[label].CGRectValue; CGRect boundingRect = boundingRects[label].CGRectValue;
int row = (int)index / [self cols]; int row = (int)index / [mat cols];
int col = (int)index % [self cols]; int col = (int)index % [mat cols];
int x = borderGap + lipWidth + col * (maxWidth + colGap) + (maxWidth - boundingRect.size.width) / 2; int x = borderGap + lipWidth + col * (maxWidth + colGap) + (maxWidth - boundingRect.size.width) / 2;
int y = borderGap + lipWidth + row * (maxHeight + rowGap) + (maxHeight - boundingRect.size.height) / 2; int y = borderGap + lipWidth + row * (maxHeight + rowGap) + (maxHeight - boundingRect.size.height) / 2;
CGRect textRect = CGRectMake(x, y, boundingRect.size.width, boundingRect.size.height); CGRect textRect = CGRectMake(x, y, boundingRect.size.width, boundingRect.size.height);
@ -134,26 +133,26 @@ typedef UIFont* (*FontGetter)();
UIImage* image = UIGraphicsGetImageFromCurrentImageContext(); UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); UIGraphicsEndImageContext();
return image; return image;
} else if (([self dims] == 2) && ([self type] == CV_8U || [self type] == CV_8UC3 || [self type] == CV_8UC4)) { } else if (([mat dims] == 2) && ([mat type] == CV_8U || [mat type] == CV_8UC3 || [mat type] == CV_8UC4)) {
return [self toUIImage]; return [mat toUIImage];
} else if ([self dims] == 2 && [self channels] == 1) { } else if ([mat dims] == 2 && [mat channels] == 1) {
Mat* normalized = [Mat new]; Mat* normalized = [Mat new];
[Core normalize:self dst:normalized alpha:0 beta:255 norm_type:NORM_MINMAX dtype:CV_8U]; [Core normalize:mat dst:normalized alpha:0 beta:255 norm_type:NORM_MINMAX dtype:CV_8U];
Mat* normalizedKey = [[Mat alloc] initWithRows:[self rows] + 10 cols:[self cols] type:CV_8U]; Mat* normalizedKey = [[Mat alloc] initWithRows:[mat rows] + 10 cols:[mat cols] type:CV_8U];
std::vector<char> key; std::vector<char> key;
for (int index = 0; index < [self cols]; index++) { for (int index = 0; index < [mat cols]; index++) {
key.push_back((char)(index * 256 / [self cols])); key.push_back((char)(index * 256 / [mat cols]));
} }
for (int index = 0; index < 10; index++) { for (int index = 0; index < 10; index++) {
[normalizedKey put:@[[NSNumber numberWithInt:index], [NSNumber numberWithInt:0]] count:[self cols] byteBuffer:key.data()]; [normalizedKey put:@[[NSNumber numberWithInt:index], [NSNumber numberWithInt:0]] count:[mat cols] byteBuffer:key.data()];
} }
[normalized copyTo:[normalizedKey submatRoi:[[Rect2i alloc] initWithX:0 y:10 width:[self cols] height:[self rows]]]]; [normalized copyTo:[normalizedKey submatRoi:[[Rect2i alloc] initWithX:0 y:10 width:[mat cols] height:[mat rows]]]];
Mat* colorMap = [Mat new]; Mat* colorMap = [Mat new];
[Imgproc applyColorMap:normalizedKey dst:colorMap colormap:COLORMAP_JET]; [Imgproc applyColorMap:normalizedKey dst:colorMap colormap:COLORMAP_JET];
[Imgproc cvtColor:colorMap dst:colorMap code:COLOR_BGR2RGB]; [Imgproc cvtColor:colorMap dst:colorMap code:COLOR_BGR2RGB];
return [colorMap toUIImage]; return [colorMap toUIImage];
} }
return [self description]; return [mat description];
} }
@end @end

@ -1,32 +0,0 @@
//
// Mat+Converters.h
//
// Created by Masaya Tsuruta on 2020/10/08.
//
#pragma once
#ifdef __cplusplus
#import "opencv2/core.hpp"
#else
#define CV_EXPORTS
#endif
#import "Mat.h"
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
NS_ASSUME_NONNULL_BEGIN
CV_EXPORTS @interface Mat (Converters)
-(CGImageRef)toCGImage CF_RETURNS_RETAINED;
-(instancetype)initWithCGImage:(CGImageRef)image;
-(instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist;
-(NSImage*)toNSImage;
-(instancetype)initWithNSImage:(NSImage*)image;
-(instancetype)initWithNSImage:(NSImage*)image alphaExist:(BOOL)alphaExist;
@end
NS_ASSUME_NONNULL_END

@ -1,44 +0,0 @@
//
// Mat+Converters.mm
//
// Created by Masaya Tsuruta on 2020/10/08.
//
#import "Mat+Converters.h"
#import <opencv2/imgcodecs/macosx.h>
@implementation Mat (Converters)
-(CGImageRef)toCGImage {
return MatToCGImage(self.nativeRef);
}
-(instancetype)initWithCGImage:(CGImageRef)image {
return [self initWithCGImage:image alphaExist:NO];
}
-(instancetype)initWithCGImage:(CGImageRef)image alphaExist:(BOOL)alphaExist {
self = [self init];
if (self) {
CGImageToMat(image, self.nativeRef, (bool)alphaExist);
}
return self;
}
-(NSImage*)toNSImage {
return MatToNSImage(self.nativeRef);
}
-(instancetype)initWithNSImage:(NSImage*)image {
return [self initWithNSImage:image alphaExist:NO];
}
-(instancetype)initWithNSImage:(NSImage*)image alphaExist:(BOOL)alphaExist {
self = [self init];
if (self) {
NSImageToMat(image, self.nativeRef, (bool)alphaExist);
}
return self;
}
@end

@ -0,0 +1,32 @@
//
// Mat+Converters.h
//
// Created by Masaya Tsuruta on 2020/10/08.
//
#pragma once
#ifdef __cplusplus
#import "opencv2/core.hpp"
#else
#define CV_EXPORTS
#endif
#import "Mat.h"
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
NS_ASSUME_NONNULL_BEGIN
CV_EXPORTS @interface MatConverters : NSObject
+(CGImageRef)convertMatToCGImageRef:(Mat*)mat CF_RETURNS_RETAINED;
+(Mat*)convertCGImageRefToMat:(CGImageRef)image;
+(Mat*)convertCGImageRefToMat:(CGImageRef)image alphaExist:(BOOL)alphaExist;
+(NSImage*)converMatToNSImage:(Mat*)mat;
+(Mat*)convertNSImageToMat:(NSImage*)image;
+(Mat*)convertNSImageToMat:(NSImage*)image alphaExist:(BOOL)alphaExist;
@end
NS_ASSUME_NONNULL_END

@ -0,0 +1,40 @@
//
// MatConverters.mm
//
// Created by Masaya Tsuruta on 2020/10/08.
//
#import "MatConverters.h"
#import <opencv2/imgcodecs/macosx.h>
@implementation MatConverters
+(CGImageRef)convertMatToCGImageRef:(Mat*)mat {
return MatToCGImage(mat.nativeRef);
}
+(Mat*)convertCGImageRefToMat:(CGImageRef)image {
return [MatConverters convertCGImageRefToMat:image alphaExist:NO];
}
+(Mat*)convertCGImageRefToMat:(CGImageRef)image alphaExist:(BOOL)alphaExist {
Mat* mat = [Mat new];
CGImageToMat(image, mat.nativeRef, (bool)alphaExist);
return mat;
}
+(NSImage*)converMatToNSImage:(Mat*)mat {
return MatToNSImage(mat.nativeRef);
}
+(Mat*)convertNSImageToMat:(NSImage*)image {
return [MatConverters convertNSImageToMat:image alphaExist:NO];
}
+(Mat*)convertNSImageToMat:(NSImage*)image alphaExist:(BOOL)alphaExist {
Mat* mat = [Mat new];
NSImageToMat(image, mat.nativeRef, (bool)alphaExist);
return mat;
}
@end

@ -1,5 +1,5 @@
// //
// Mat+QuickLook.h // MatQuickLook.h
// //
// Created by Giles Payne on 2021/07/18. // Created by Giles Payne on 2021/07/18.
// //
@ -18,9 +18,9 @@
NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_BEGIN
CV_EXPORTS @interface Mat (QuickLook) CV_EXPORTS @interface MatQuickLook : NSObject
- (id)debugQuickLookObject; + (id)matDebugQuickLookObject:(Mat*)mat;
@end @end

@ -1,11 +1,11 @@
// //
// Mat+QuickLook.mm // MatQuickLook.mm
// //
// Created by Giles Payne on 2021/07/18. // Created by Giles Payne on 2021/07/18.
// //
#import "Mat+QuickLook.h" #import "MatQuickLook.h"
#import "Mat+Converters.h" #import "MatConverters.h"
#import "Rect2i.h" #import "Rect2i.h"
#import "Core.h" #import "Core.h"
#import "Imgproc.h" #import "Imgproc.h"
@ -39,9 +39,9 @@ static NSFont* getSystemFont() {
typedef NSFont* (*FontGetter)(); typedef NSFont* (*FontGetter)();
@implementation Mat (QuickLook) @implementation MatQuickLook
- (NSString*)makeLabel:(BOOL)isIntType val:(NSNumber*)num { + (NSString*)makeLabel:(BOOL)isIntType val:(NSNumber*)num {
if (isIntType) { if (isIntType) {
return [NSString stringWithFormat:@"%d", num.intValue]; return [NSString stringWithFormat:@"%d", num.intValue];
} else { } else {
@ -56,27 +56,27 @@ typedef NSFont* (*FontGetter)();
} }
} }
- (id)debugQuickLookObject { + (id)matDebugQuickLookObject:(Mat*)mat {
// for smallish Mat objects display as a matrix // for smallish Mat objects display as a matrix
if ([self dims] == 2 && [self rows] <= 10 && [self cols] <= 10 && [self channels] == 1) { if ([mat dims] == 2 && [mat rows] <= 10 && [mat cols] <= 10 && [mat channels] == 1) {
FontGetter fontGetters[] = { getCMU, getBodoni72, getAnySerif, getSystemFont }; FontGetter fontGetters[] = { getCMU, getBodoni72, getAnySerif, getSystemFont };
NSFont* font = nil; NSFont* font = nil;
for (int fontGetterIndex = 0; font==nil && fontGetterIndex < (sizeof(fontGetters)) / (sizeof(fontGetters[0])); fontGetterIndex++) { for (int fontGetterIndex = 0; font==nil && fontGetterIndex < (sizeof(fontGetters)) / (sizeof(fontGetters[0])); fontGetterIndex++) {
font = fontGetters[fontGetterIndex](); font = fontGetters[fontGetterIndex]();
} }
int elements = [self rows] * [self cols]; int elements = [mat rows] * [mat cols];
NSDictionary<NSAttributedStringKey,id>* textFontAttributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: NSColor.blackColor }; NSDictionary<NSAttributedStringKey,id>* textFontAttributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: NSColor.blackColor };
NSMutableArray<NSNumber*>* rawData = [NSMutableArray new]; NSMutableArray<NSNumber*>* rawData = [NSMutableArray new];
for (int dataIndex = 0; dataIndex < elements; dataIndex++) { for (int dataIndex = 0; dataIndex < elements; dataIndex++) {
[rawData addObject:[NSNumber numberWithDouble:0]]; [rawData addObject:[NSNumber numberWithDouble:0]];
} }
[self get:0 col: 0 data: rawData]; [mat get:0 col: 0 data: rawData];
BOOL isIntType = [self depth] <= CV_32S; BOOL isIntType = [mat depth] <= CV_32S;
NSMutableArray<NSString*>* labels = [NSMutableArray new]; NSMutableArray<NSString*>* labels = [NSMutableArray new];
NSMutableDictionary<NSString*, NSValue*>* boundingRects = [NSMutableDictionary dictionaryWithCapacity:elements]; NSMutableDictionary<NSString*, NSValue*>* boundingRects = [NSMutableDictionary dictionaryWithCapacity:elements];
int maxWidth = 0, maxHeight = 0; int maxWidth = 0, maxHeight = 0;
for (NSNumber* number in rawData) { for (NSNumber* number in rawData) {
NSString* label = [self makeLabel:isIntType val:number]; NSString* label = [MatQuickLook makeLabel:isIntType val:number];
[labels addObject:label]; [labels addObject:label];
NSRect boundingRect = [label boundingRectWithSize:NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:textFontAttributes]; NSRect boundingRect = [label boundingRectWithSize:NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:textFontAttributes];
if (boundingRect.size.width > maxWidth) { if (boundingRect.size.width > maxWidth) {
@ -93,8 +93,8 @@ typedef NSFont* (*FontGetter)();
int borderGap = 9; int borderGap = 9;
int lineThickness = 4; int lineThickness = 4;
int lipWidth = 8; int lipWidth = 8;
int imageWidth = 2 * (borderGap + lipWidth) + maxWidth * [self cols] + colGap * ([self cols] - 1); int imageWidth = 2 * (borderGap + lipWidth) + maxWidth * [mat cols] + colGap * ([mat cols] - 1);
int imageHeight = 2 * (borderGap + lipWidth) + maxHeight * [self rows] + rowGap * ([self rows] - 1); int imageHeight = 2 * (borderGap + lipWidth) + maxHeight * [mat rows] + rowGap * ([mat rows] - 1);
NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(imageWidth, imageHeight)]; NSImage* image = [[NSImage alloc] initWithSize:NSMakeSize(imageWidth, imageHeight)];
NSBezierPath* leftBracket = [NSBezierPath new]; NSBezierPath* leftBracket = [NSBezierPath new];
[leftBracket moveToPoint:NSMakePoint(borderGap, borderGap)]; [leftBracket moveToPoint:NSMakePoint(borderGap, borderGap)];
@ -121,8 +121,8 @@ typedef NSFont* (*FontGetter)();
[labels enumerateObjectsUsingBlock:^(id label, NSUInteger index, BOOL *stop) [labels enumerateObjectsUsingBlock:^(id label, NSUInteger index, BOOL *stop)
{ {
NSRect boundingRect = boundingRects[label].rectValue; NSRect boundingRect = boundingRects[label].rectValue;
int row = [self rows] - 1 - ((int)index / [self cols]); int row = [mat rows] - 1 - ((int)index / [mat cols]);
int col = (int)index % [self cols]; int col = (int)index % [mat cols];
int x = borderGap + lipWidth + col * (maxWidth + colGap) + (maxWidth - boundingRect.size.width) / 2; int x = borderGap + lipWidth + col * (maxWidth + colGap) + (maxWidth - boundingRect.size.width) / 2;
int y = borderGap + lipWidth + row * (maxHeight + rowGap) + (maxHeight - boundingRect.size.height) / 2; int y = borderGap + lipWidth + row * (maxHeight + rowGap) + (maxHeight - boundingRect.size.height) / 2;
NSRect textRect = NSMakeRect(x, y, boundingRect.size.width, boundingRect.size.height); NSRect textRect = NSMakeRect(x, y, boundingRect.size.width, boundingRect.size.height);
@ -130,29 +130,29 @@ typedef NSFont* (*FontGetter)();
}]; }];
[image unlockFocus]; [image unlockFocus];
return image; return image;
} else if (([self dims] == 2) && ([self type] == CV_8U || [self type] == CV_8UC3 || [self type] == CV_8UC4)) { } else if (([mat dims] == 2) && ([mat type] == CV_8U || [mat type] == CV_8UC3 || [mat type] == CV_8UC4)) {
// convert to NSImage if the Mats has 2 dimensions and a type and number of channels consistent with it being a image // convert to NSImage if the Mats has 2 dimensions and a type and number of channels consistent with it being a image
return [self toNSImage]; return [mat toNSImage];
} else if ([self dims] == 2 && [self channels] == 1) { } else if ([mat dims] == 2 && [mat channels] == 1) {
// for other Mats with 2 dimensions and one channel - generate heat map // for other Mats with 2 dimensions and one channel - generate heat map
Mat* normalized = [Mat new]; Mat* normalized = [Mat new];
[Core normalize:self dst:normalized alpha:0 beta:255 norm_type:NORM_MINMAX dtype:CV_8U]; [Core normalize:mat dst:normalized alpha:0 beta:255 norm_type:NORM_MINMAX dtype:CV_8U];
Mat* normalizedKey = [[Mat alloc] initWithRows:[self rows] + 10 cols:[self cols] type:CV_8U]; Mat* normalizedKey = [[Mat alloc] initWithRows:[mat rows] + 10 cols:[mat cols] type:CV_8U];
std::vector<char> key; std::vector<char> key;
for (int index = 0; index < [self cols]; index++) { for (int index = 0; index < [mat cols]; index++) {
key.push_back((char)(index * 256 / [self cols])); key.push_back((char)(index * 256 / [mat cols]));
} }
for (int index = 0; index < 10; index++) { for (int index = 0; index < 10; index++) {
[normalizedKey put:@[[NSNumber numberWithInt:index], [NSNumber numberWithInt:0]] count:[self cols] byteBuffer:key.data()]; [normalizedKey put:@[[NSNumber numberWithInt:index], [NSNumber numberWithInt:0]] count:[mat cols] byteBuffer:key.data()];
} }
[normalized copyTo:[normalizedKey submatRoi:[[Rect2i alloc] initWithX:0 y:10 width:[self cols] height:[self rows]]]]; [normalized copyTo:[normalizedKey submatRoi:[[Rect2i alloc] initWithX:0 y:10 width:[mat cols] height:[mat rows]]]];
Mat* colorMap = [Mat new]; Mat* colorMap = [Mat new];
[Imgproc applyColorMap:normalizedKey dst:colorMap colormap:COLORMAP_JET]; [Imgproc applyColorMap:normalizedKey dst:colorMap colormap:COLORMAP_JET];
[Imgproc cvtColor:colorMap dst:colorMap code:COLOR_BGR2RGB]; [Imgproc cvtColor:colorMap dst:colorMap code:COLOR_BGR2RGB];
return [colorMap toNSImage]; return [colorMap toNSImage];
} }
//everything just return the Mat description //everything just return the Mat description
return [self description]; return [mat description];
} }
@end @end

@ -1438,6 +1438,8 @@ typedef NS_ENUM(int, {1}) {{
opencv_header = "#import <Foundation/Foundation.h>\n\n" opencv_header = "#import <Foundation/Foundation.h>\n\n"
opencv_header += "// ! Project version number\nFOUNDATION_EXPORT double " + framework_name + "VersionNumber;\n\n" opencv_header += "// ! Project version number\nFOUNDATION_EXPORT double " + framework_name + "VersionNumber;\n\n"
opencv_header += "// ! Project version string\nFOUNDATION_EXPORT const unsigned char " + framework_name + "VersionString[];\n\n" opencv_header += "// ! Project version string\nFOUNDATION_EXPORT const unsigned char " + framework_name + "VersionString[];\n\n"
opencv_header += "\n".join(["#define AVAILABLE_" + m['name'].upper() for m in config['modules']])
opencv_header += "\n\n"
opencv_header += "\n".join(["#import <" + framework_name + "/%s>" % os.path.basename(f) for f in self.header_files]) opencv_header += "\n".join(["#import <" + framework_name + "/%s>" % os.path.basename(f) for f in self.header_files])
self.save(opencv_header_file, opencv_header) self.save(opencv_header_file, opencv_header)
opencv_modulemap_file = os.path.join(output_objc_path, framework_name + ".modulemap") opencv_modulemap_file = os.path.join(output_objc_path, framework_name + ".modulemap")
@ -1446,8 +1448,9 @@ typedef NS_ENUM(int, {1}) {{
opencv_modulemap += "\n".join([" header \"%s\"" % os.path.basename(f) for f in self.header_files]) opencv_modulemap += "\n".join([" header \"%s\"" % os.path.basename(f) for f in self.header_files])
opencv_modulemap += "\n export *\n module * {export *}\n}\n" opencv_modulemap += "\n export *\n module * {export *}\n}\n"
self.save(opencv_modulemap_file, opencv_modulemap) self.save(opencv_modulemap_file, opencv_modulemap)
available_modules = " ".join(["-DAVAILABLE_" + m['name'].upper() for m in config['modules']])
cmakelist_template = read_contents(os.path.join(SCRIPT_DIR, 'templates/cmakelists.template')) cmakelist_template = read_contents(os.path.join(SCRIPT_DIR, 'templates/cmakelists.template'))
cmakelist = Template(cmakelist_template).substitute(modules = ";".join(modules), framework = framework_name, objc_target=objc_target) cmakelist = Template(cmakelist_template).substitute(modules = ";".join(modules), framework = framework_name, objc_target=objc_target, module_availability_defines=available_modules)
self.save(os.path.join(dstdir, "CMakeLists.txt"), cmakelist) self.save(os.path.join(dstdir, "CMakeLists.txt"), cmakelist)
mkdir_p(os.path.join(output_objc_build_path, "framework_build")) mkdir_p(os.path.join(output_objc_build_path, "framework_build"))
mkdir_p(os.path.join(output_objc_build_path, "test_build")) mkdir_p(os.path.join(output_objc_build_path, "test_build"))

@ -8,7 +8,7 @@ set(MODULES "$modules")
set (CMAKE_CXX_STANDARD 11) set (CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_STANDARD_REQUIRED TRUE) set (CMAKE_CXX_STANDARD_REQUIRED TRUE)
set (OBJC_COMPILE_FLAGS "-fobjc-arc -fobjc-weak -fvisibility=hidden -fPIC -D__OPENCV_BUILD=1") set (OBJC_COMPILE_FLAGS "-fobjc-arc -fobjc-weak -fvisibility=hidden -fPIC -D__OPENCV_BUILD=1 $module_availability_defines")
set (SUPPRESS_WARNINGS_FLAGS "-Wno-incomplete-umbrella") set (SUPPRESS_WARNINGS_FLAGS "-Wno-incomplete-umbrella")
set (CMAKE_CXX_FLAGS "$${CMAKE_CXX_FLAGS} $${OBJC_COMPILE_FLAGS} $${SUPPRESS_WARNINGS_FLAGS}") set (CMAKE_CXX_FLAGS "$${CMAKE_CXX_FLAGS} $${OBJC_COMPILE_FLAGS} $${SUPPRESS_WARNINGS_FLAGS}")

Loading…
Cancel
Save