Mat+QuickLook.mm 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. //
  2. // Mat+QuickLook.mm
  3. //
  4. // Created by Giles Payne on 2021/07/18.
  5. //
  6. #import "Mat+QuickLook.h"
  7. #import "Mat+Converters.h"
  8. #import "Rect2i.h"
  9. #import "Core.h"
  10. #import "Imgproc.h"
  11. #import <opencv2/imgcodecs/ios.h>
  12. #define SIZE 20
  13. static UIFont* getCMU() {
  14. return [UIFont fontWithName:@"CMU Serif" size:SIZE];
  15. }
  16. static UIFont* getBodoni72() {
  17. return [UIFont fontWithName:@"Bodoni 72" size:SIZE];
  18. }
  19. static UIFont* getAnySerif() {
  20. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  21. if (@available(iOS 13.0, *)) {
  22. return [UIFont fontWithDescriptor:[[UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleBody] fontDescriptorWithDesign:UIFontDescriptorSystemDesignSerif] size:SIZE];
  23. } else {
  24. return nil;
  25. }
  26. #else
  27. return nil;
  28. #endif
  29. }
  30. static UIFont* getSystemFont() {
  31. return [UIFont systemFontOfSize:SIZE];
  32. }
  33. typedef UIFont* (*FontGetter)();
  34. @implementation Mat (QuickLook)
  35. - (NSString*)makeLabel:(BOOL)isIntType val:(NSNumber*)num {
  36. if (isIntType) {
  37. return [NSString stringWithFormat:@"%d", num.intValue];
  38. } else {
  39. int exponent = 1 + (int)log10(abs(num.doubleValue));
  40. if (num.doubleValue == (double)num.intValue && num.doubleValue < 10000 && num.doubleValue > -10000) {
  41. return [NSString stringWithFormat:@"%d", num.intValue];;
  42. } else if (exponent <= 5 && exponent >= -1) {
  43. return [NSString stringWithFormat:[NSString stringWithFormat:@"%%%d.%df", 6, MIN(5 - exponent, 4)], num.doubleValue];
  44. } else {
  45. return [[[NSString stringWithFormat:@"%.2e", num.doubleValue] stringByReplacingOccurrencesOfString:@"e+0" withString:@"e"] stringByReplacingOccurrencesOfString:@"e-0" withString:@"e-"];
  46. }
  47. }
  48. }
  49. - (void)relativeLine:(UIBezierPath*)path relX:(CGFloat)x relY:(CGFloat)y {
  50. CGPoint curr = path.currentPoint;
  51. [path addLineToPoint:CGPointMake(curr.x + x, curr.y + y)];
  52. }
  53. - (id)debugQuickLookObject {
  54. if ([self dims] == 2 && [self rows] <= 10 && [self cols] <= 10) {
  55. FontGetter fontGetters[] = { getCMU, getBodoni72, getAnySerif, getSystemFont };
  56. UIFont* font = nil;
  57. for (int fontGetterIndex = 0; font==nil && fontGetterIndex < (sizeof(fontGetters)) / (sizeof(fontGetters[0])); fontGetterIndex++) {
  58. font = fontGetters[fontGetterIndex]();
  59. }
  60. int elements = [self rows] * [self cols];
  61. NSDictionary<NSAttributedStringKey,id>* textFontAttributes = @{ NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.blackColor };
  62. NSMutableArray<NSNumber*>* rawData = [NSMutableArray new];
  63. for (int dataIndex = 0; dataIndex < elements; dataIndex++) {
  64. [rawData addObject:[NSNumber numberWithDouble:0]];
  65. }
  66. [self get:0 col: 0 data: rawData];
  67. BOOL isIntType = [self depth] <= CV_32S;
  68. NSMutableArray<NSString*>* labels = [NSMutableArray new];
  69. NSMutableDictionary<NSString*, NSValue*>* boundingRects = [NSMutableDictionary dictionaryWithCapacity:elements];
  70. int maxWidth = 0, maxHeight = 0;
  71. for (NSNumber* number in rawData) {
  72. NSString* label = [self makeLabel:isIntType val:number];
  73. [labels addObject:label];
  74. CGRect boundingRect = [label boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:textFontAttributes context:nil];
  75. if (boundingRect.size.width > maxWidth) {
  76. maxWidth = boundingRect.size.width;
  77. }
  78. if (boundingRect.size.height > maxHeight) {
  79. maxHeight = boundingRect.size.height;
  80. }
  81. boundingRects[label] = [NSValue valueWithCGRect:boundingRect];
  82. }
  83. int rowGap = 6;
  84. int colGap = 6;
  85. int borderGap = 8;
  86. int lineThickness = 3;
  87. int lipWidth = 6;
  88. int imageWidth = 2 * (borderGap + lipWidth) + maxWidth * [self cols] + colGap * ([self cols] - 1);
  89. int imageHeight = 2 * (borderGap + lipWidth) + maxHeight * [self rows] + rowGap * ([self rows] - 1);
  90. UIBezierPath* leftBracket = [UIBezierPath new];
  91. [leftBracket moveToPoint:CGPointMake(borderGap, borderGap)];
  92. [self relativeLine:leftBracket relX:0 relY:imageHeight - 2 * borderGap];
  93. [self relativeLine:leftBracket relX:lineThickness + lipWidth relY:0];
  94. [self relativeLine:leftBracket relX:0 relY:-lineThickness];
  95. [self relativeLine:leftBracket relX:-lipWidth relY:0];
  96. [self relativeLine:leftBracket relX:0 relY:-(imageHeight - 2 * (borderGap + lineThickness))];
  97. [self relativeLine:leftBracket relX:lipWidth relY:0];
  98. [self relativeLine:leftBracket relX:0 relY:-lineThickness];
  99. [leftBracket closePath];
  100. CGAffineTransform reflect = CGAffineTransformConcat(CGAffineTransformMakeTranslation(-imageWidth, 0), CGAffineTransformMakeScale(-1, 1));
  101. UIBezierPath* rightBracket = [leftBracket copy];
  102. [rightBracket applyTransform:reflect];
  103. CGRect rect = CGRectMake(0, 0, imageWidth, imageHeight);
  104. UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0);
  105. [UIColor.whiteColor setFill];
  106. UIRectFill(rect);
  107. [UIColor.blackColor setFill];
  108. [leftBracket fill];
  109. [rightBracket fill];
  110. [labels enumerateObjectsUsingBlock:^(id label, NSUInteger index, BOOL *stop)
  111. {
  112. CGRect boundingRect = boundingRects[label].CGRectValue;
  113. int row = (int)index / [self cols];
  114. int col = (int)index % [self cols];
  115. int x = borderGap + lipWidth + col * (maxWidth + colGap) + (maxWidth - boundingRect.size.width) / 2;
  116. int y = borderGap + lipWidth + row * (maxHeight + rowGap) + (maxHeight - boundingRect.size.height) / 2;
  117. CGRect textRect = CGRectMake(x, y, boundingRect.size.width, boundingRect.size.height);
  118. [label drawInRect:textRect withAttributes:textFontAttributes];
  119. }];
  120. UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
  121. UIGraphicsEndImageContext();
  122. return image;
  123. } else if (([self dims] == 2) && ([self type] == CV_8U || [self type] == CV_8UC3 || [self type] == CV_8UC4)) {
  124. return [self toUIImage];
  125. } else if ([self dims] == 2 && [self channels] == 1) {
  126. Mat* normalized = [Mat new];
  127. [Core normalize:self dst:normalized alpha:0 beta:255 norm_type:NORM_MINMAX dtype:CV_8U];
  128. Mat* normalizedKey = [[Mat alloc] initWithRows:[self rows] + 10 cols:[self cols] type:CV_8U];
  129. std::vector<char> key;
  130. for (int index = 0; index < [self cols]; index++) {
  131. key.push_back((char)(index * 256 / [self cols]));
  132. }
  133. for (int index = 0; index < 10; index++) {
  134. [normalizedKey put:@[[NSNumber numberWithInt:index], [NSNumber numberWithInt:0]] count:[self cols] byteBuffer:key.data()];
  135. }
  136. [normalized copyTo:[normalizedKey submatRoi:[[Rect2i alloc] initWithX:0 y:10 width:[self cols] height:[self rows]]]];
  137. Mat* colorMap = [Mat new];
  138. [Imgproc applyColorMap:normalizedKey dst:colorMap colormap:COLORMAP_JET];
  139. [Imgproc cvtColor:colorMap dst:colorMap code:COLOR_BGR2RGB];
  140. return [colorMap toUIImage];
  141. }
  142. return [self description];
  143. }
  144. @end