我正在查看使用视觉检测文本的应用程序中的内存泄漏。
我遇到了内存泄漏,当使用树时,该泄漏指向此行:
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
}
}
答案 0 :(得分:1)
其他人都告诉你的是正确的。您有两个引用SearchProfile
(Slicer)实例的闭包,并且您需要打破这两个实例的保留周期。我认为这行是一个巨大的错误:
self
除保留周期外,您一无所获。删除这些行!相反,只需在需要时创建匿名函数。替换为:
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)
})]
)
答案 1 :(得分:0)
在textDetectionRequest
闭包中使用capture list:
lazy var textDetectionRequest: VNDetectTextRectanglesRequest =
{ [weak self] in
return VNDetectTextRectanglesRequest(completionHandler: self?.handleDetectedText)
}()
答案 2 :(得分:0)
我认为应该是这样的:
DispatchQueue.global(qos: .userInitiated).async { [weak self] _ in
do {
var imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
try imageRequestHandler.perform([self?.textDetectionRequest])
} catch let error as Error {
print("Failed to perform vision request: \(error)")
}
}
答案 3 :(得分:0)
self.textDetectionRequest
是lazy var
,它将捕获handleDetectedText
,而closure
是[unowned self]
,因此您应使用[weak self]
或 private lazy var textDetectionRequest: VNDetectTextRectanglesRequest = { [unowned self] in
return VNDetectTextRectanglesRequest(completionHandler: self.handleDetectedText)
}()
之类的捕获列表避免保留周期。
VNRequest
另外,您可以将performVisionRequest
数组作为依赖项传递给 internal func slice(image: UIImage, completion: @escaping ((_: [UIImage]) -> Void)) {
self.image = image
self.sliceCompletion = completion
let requests = self.textDetectionRequest
self.performVisionRequest(image: image.cgImage!, orientation: .up, requests: [requests])
}
// MARK: - Vision
private func performVisionRequest(image: CGImage, orientation: CGImagePropertyOrientation, requests: [VNRequest]) {
DispatchQueue.global(qos: .userInitiated).async {
do {
let imageRequestHandler = VNImageRequestHandler(cgImage: image, orientation: orientation, options: [:])
try imageRequestHandler.perform(requests)
} catch let error as NSError {
self.sliceCompletion([UIImage]())
print("Failed to perform vision request: \(error)")
}
}
}
函数,以简化代码
name