text_detection_impl_mac.mm 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "services/shape_detection/text_detection_impl_mac.h"
  5. #include "base/mac/scoped_cftyperef.h"
  6. #include "base/strings/sys_string_conversions.h"
  7. #include "mojo/public/cpp/bindings/pending_receiver.h"
  8. #include "mojo/public/cpp/bindings/self_owned_receiver.h"
  9. #include "services/shape_detection/detection_utils_mac.h"
  10. #include "services/shape_detection/text_detection_impl.h"
  11. namespace shape_detection {
  12. // static
  13. void TextDetectionImpl::Create(
  14. mojo::PendingReceiver<mojom::TextDetection> receiver) {
  15. mojo::MakeSelfOwnedReceiver(std::make_unique<TextDetectionImplMac>(),
  16. std::move(receiver));
  17. }
  18. TextDetectionImplMac::TextDetectionImplMac() {
  19. NSDictionary* const opts = @{CIDetectorAccuracy : CIDetectorAccuracyHigh};
  20. detector_.reset(
  21. [[CIDetector detectorOfType:CIDetectorTypeText context:nil options:opts]
  22. retain]);
  23. }
  24. TextDetectionImplMac::~TextDetectionImplMac() {}
  25. void TextDetectionImplMac::Detect(const SkBitmap& bitmap,
  26. DetectCallback callback) {
  27. base::scoped_nsobject<CIImage> ci_image = CreateCIImageFromSkBitmap(bitmap);
  28. if (!ci_image) {
  29. std::move(callback).Run({});
  30. return;
  31. }
  32. NSArray* const features = [detector_ featuresInImage:ci_image];
  33. const int height = bitmap.height();
  34. std::vector<mojom::TextDetectionResultPtr> results;
  35. for (CIRectangleFeature* const f in features) {
  36. // CIRectangleFeature only has bounding box information.
  37. auto result = mojom::TextDetectionResult::New();
  38. result->bounding_box = ConvertCGToGfxCoordinates(f.bounds, height);
  39. // Enumerate corner points starting from top-left in clockwise fashion:
  40. // https://wicg.github.io/shape-detection-api/text.html#dom-detectedtext-cornerpoints
  41. result->corner_points.emplace_back(f.topLeft.x, height - f.topLeft.y);
  42. result->corner_points.emplace_back(f.topRight.x, height - f.topRight.y);
  43. result->corner_points.emplace_back(f.bottomRight.x,
  44. height - f.bottomRight.y);
  45. result->corner_points.emplace_back(f.bottomLeft.x, height - f.bottomLeft.y);
  46. results.push_back(std::move(result));
  47. }
  48. std::move(callback).Run(std::move(results));
  49. }
  50. } // namespace shape_detection