【问题标题】:IOS OCR tesseract not release the memory after being nil and using ACRIOS OCR tesseract 为 nil 并使用 ACR 后不释放内存
【发布时间】:2026-02-21 10:20:02
【问题描述】:

我花了超过 24 小时调试和解决 tesseract 中的问题,我为多个图像循环下面的函数的问题,每次我跟踪内存,我发现每次调用时内存都会增加下线

Tesseract* tesseract = [[Tesseract alloc] initWithLanguage:@"eng+ita"];

它不受下面一行的影响

tesseract = nil;

下面是调用的完整函数

    -(void)recognizeImageWithTesseract:(UIImage *)img
    {

     UIImage *testb = [img blackAndWhite];

       Tesseract* tesseract = [[Tesseract alloc] initWithLanguage:@"eng+ita"];

       tesseract.delegate = self;
         [tesseract setVariableValue:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-/*._=':!)(" forKey:@"tessedit_char_whitelist"]; //limit search
        [tesseract setImage:testb];
        [tesseract recognize];
         recognizedText = [tesseract recognizedText];
        tesseract = nil; //deallocate and free all memory
}

更新 1:

经过深度排查,我发现setimage的tesseract代码是原因,代码如下,我需要知道我必须更新哪些代码才能解决这个问题

- (void)setImage:(UIImage *)image {

    if (image == nil || image.size.width <= 0 || image.size.height <= 0) {
        NSLog(@"WARNING: Image has not size!");
        return;
    }

    self.imageSize = image.size; //self.imageSize used in the characterBoxes method
    int width = self.imageSize.width;
    int height = self.imageSize.height;

    CGImage *cgImage = image.CGImage;
    CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
    _pixels = CFDataGetBytePtr(data);

    size_t bitsPerComponent = CGImageGetBitsPerComponent(cgImage);
    size_t bitsPerPixel = CGImageGetBitsPerPixel(cgImage);
    size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);

    tesseract::ImageThresholder *imageThresholder = new tesseract::ImageThresholder();

    assert(bytesPerRow < MAX_INT32);
    {
        imageThresholder->SetImage(_pixels,width,height,(int)(bitsPerPixel/bitsPerComponent),(int)bytesPerRow);
        _tesseract->SetImage(imageThresholder->GetPixRect());
    }

    imageThresholder->Clear();
    CFRelease(data);
    delete imageThresholder;
    imageThresholder = nil;
}

请支持我解决这个问题

非常感谢

【问题讨论】:

  • 您使用的是 ARC 还是 MRC?
  • 那么不需要将tesseract设置为nil。使用仪器,看看问题出在哪里。你可能有一个参考周期。
  • 我现在测试了同样的问题

标签: ios memory-leaks ocr tesseract


【解决方案1】:

您在一个紧密的循环中执行此操作,并且在每个应用程序运行循环后都会释放内存。你需要做的是

// your loop here 
for (int i = 0; i < n; i++) {
    @autoreleasepool {
        // perform memory intensive task here;
    }
}

因此,每次完成繁重的任务后,内存自动释放池都会耗尽。

阅读此处了解更多详情:

Objective-C: Why is autorelease (@autoreleasepool) still needed with ARC?

【讨论】:

  • 经过测试,我发现内存增加的步数变低了(每个循环大约5M),但是对于长循环,它会导致应用程序崩溃,请支持认为这个答案是最好的答案跨度>
  • 然后其他部分出错了,这应该是一个单独的问题。您的循环内存释放问题解决方案就是@autoreleasepool。