我正在查看我的应用程序中使用视觉检测文本的内存泄漏。
我得到一个内存泄漏,当使用树指向这一行时:

try imageRequestHandler.perform([self.textDetectionRequest])

我不知道为什么,希望有人能帮忙。
下面是完整的代码。
private func performVisionRequest(image: CGImage, orientation: CGImagePropertyOrientation) {

    DispatchQueue.global(qos: .userInitiated).async {
        do {
            var imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
            try imageRequestHandler.perform([self.textDetectionRequest])
        } catch let error as NSError {
            print("Failed to perform vision request: \(error)")

        }
    }
}

这是全班同学:
import UIKit
import Vision

var noText: Bool!
var imageNo: UIImage!

internal class Slicer {

private var image = UIImage()
private var sliceCompletion: ((_ slices: [UIImage]) -> Void) = { _ in }

private lazy var textDetectionRequest: VNDetectTextRectanglesRequest = {

    return VNDetectTextRectanglesRequest(completionHandler: self.handleDetectedText)
}()

internal func slice(image: UIImage, completion: @escaping ((_: [UIImage]) -> Void)) {
    self.image = image
    self.sliceCompletion = completion
    self.performVisionRequest(image: image.cgImage!, orientation: .up)
}

// MARK: - Vision

private func performVisionRequest(image: CGImage, orientation: CGImagePropertyOrientation) {

    DispatchQueue.global(qos: .userInitiated).async {
        do {
            let imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
            try imageRequestHandler.perform([self.textDetectionRequest])
        } catch let error as NSError {
            self.sliceCompletion([UIImage]())
            print("Failed to perform vision request: \(error)")

        }
    }
}

private func handleDetectedText(request: VNRequest?, error: Error?) {
    if let err = error as NSError? {
        print("Failed during detection: \(err.localizedDescription)")
        return
    }
    guard let results = request?.results as? [VNTextObservation], !results.isEmpty else {

        noText = true
        print("Tony no text found")
        var slices = [imageNo]
        self.sliceCompletion(slices as! [UIImage])
        slices = []
        return }

    noText = false
    self.sliceImage(text: results, onImageWithBounds: CGRect(x: 0, y: 0, width: self.image.cgImage!.width, height: self.image.cgImage!.height))
}

private func sliceImage(text: [VNTextObservation], onImageWithBounds bounds: CGRect) {
    CATransaction.begin()

    var slices = [UIImage]()

    for wordObservation in text {
        let wordBox = boundingBox(forRegionOfInterest: wordObservation.boundingBox, withinImageBounds: bounds)

        if !wordBox.isNull {
            guard let slice = self.image.cgImage?.cropping(to: wordBox) else { continue }
            slices.append(UIImage(cgImage: slice))
        }
    }

    self.sliceCompletion(slices)

    CATransaction.commit()
}

private func boundingBox(forRegionOfInterest: CGRect, withinImageBounds bounds: CGRect) -> CGRect {

    let imageWidth = bounds.width
    let imageHeight = bounds.height

    // Begin with input rect.
    var rect = forRegionOfInterest

    // Reposition origin.
    rect.origin.x *= imageWidth
    rect.origin.y = ((1 - rect.origin.y) * imageHeight) - (forRegionOfInterest.height * imageHeight)

    // Rescale normalized coordinates. Tony adde + 30 to increase the size of rect
    rect.size.width *= imageWidth + 30
    rect.size.height *= imageHeight + 30

    return rect
}
}

ios - 内存泄漏,在do-catch块中。 iOS,Swift-LMLPHP

最佳答案

其他人告诉你的都是对的。您有两个引用self(切片器)实例的闭包,需要在这两个闭包中中断retain循环。我认为这句话是个巨大的错误:

private lazy var textDetectionRequest: VNDetectTextRectanglesRequest = {
    return VNDetectTextRectanglesRequest(completionHandler: self.handleDetectedText)
}()

你从中什么也得不到,除了保留周期。删除那些行!相反,只要在需要的时候创建匿名函数。替换为:
try imageRequestHandler.perform([self.textDetectionRequest])

有了这个:
try imageRequestHandler.perform(
    [VNDetectTextRectanglesRequest(completionHandler:{ req, err in
        self.handleDetectedText(request:req, error:err)
    })]
)

如果仍有泄漏(我怀疑),则将其更改为
try imageRequestHandler.perform(
    [VNDetectTextRectanglesRequest(completionHandler:{ [weak self] req, err in
        self?.handleDetectedText(request:req, error:err)
    })]
)

关于ios - 内存泄漏,在do-catch块中。 iOS,Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51560767/

10-10 08:19
查看更多