Код: Выделить всё
func recongizeText()
{
// Create a new image-request handler.
let cgImage = self.nsImage!.cgImage(forProposedRect: nil, context: nil, hints: nil)
let requestHandler = VNImageRequestHandler(cgImage: cgImage!)
// Create a new request to recognize text.
let request = VNRecognizeTextRequest(completionHandler: recognizeTextHandler)
do {
// Perform the text-recognition request.
try requestHandler.perform([request])
} catch {
print("Unable to perform the requests: \(error).")
}
}
func recognizeTextHandler(request: VNRequest, error: Error?) {
guard let observations =
request.results as? [VNRecognizedTextObservation] else {
return
}
let recognizedStrings = observations.compactMap { observation in
// Return the string of the top VNRecognizedText instance.
return observation.topCandidates(1).first?.string
}
let boundingRects: [CGRect] = observations.compactMap { observation in
// Find the top observation.
guard let candidate = observation.topCandidates(1).first else { return .zero }
// Find the bounding-box observation for the string range.
let stringRange = candidate.string.startIndex..
Для части пользовательского интерфейса я только что добавил простое наложение: < /p>
struct BoundingBoxView: View {
var nsImage: NSImage // The NSImage to display
var normalizedBoundingBoxes: [CGRect] // Array of normalized bounding boxes
var body: some View {
Image(nsImage: nsImage)
.resizable()
.aspectRatio(contentMode: .fit)
.overlay(
GeometryReader { geometry in
// Draw normalized bounding boxes
ForEach(normalizedBoundingBoxes.indices, id: \.self) { index in
let normalizedBox = normalizedBoundingBoxes[index]
Rectangle()
.stroke(Color.red, lineWidth: 2)
.frame(width: normalizedBox.size.width, height: normalizedBox.size.height)
.position(x: normalizedBox.midX, y: normalizedBox.midY)
}
}
) }
Подробнее здесь: https://stackoverflow.com/questions/783 ... oordinates