iOS Question [B4X] TextRecognition and SelfieSegmentation based on MLKit with memory leak in iOS

b4x-de

Active Member
Licensed User
Longtime User
The code in the following examples causes a problem in iOS that leads to a memory leak:

[B4X] TextRecognition based on MLKit

[B4X] SelfieSegmentation with ML Kit

In the ImageToMLImage function, “alloc” is used to reserve memory space to create an MLKitVisionImage from the transferred bitmap. This memory space is not released again afterwards. This code crashes when a large number of images are processed or when very large images are used.

B4X:
image = image.Initialize("MLKVisionImage").RunMethod("alloc", Null).RunMethod("initWithImage:", Array(bmp))

When using the function on iOS, it would be better to ensure that the caller has a reference to the generated MLImage so that it can be explicitly released after processing. For example:
B4X:
    Dim imgML As NativeObject
    imgML = ImageToMLImage(bmp).As(NativeObject)
    recognizer.RunMethod("processImage:completion:", Array(imgML, Me.as(NativeObject).RunMethod("createBlock", Null)))
    Wait For Process_Result(Success As Boolean, MLKText As Object)
    imgML.RunMethod("release", Null)
    imgML = Null
 

b4x-de

Active Member
Licensed User
Longtime User
Thank you for having a look on this. You are right with Objective C memory management. It should release the memory allocated from heap automatically when the last reference to it is removed from stack.

But as far es I can tell from the example here where I have run ML Kit Barcode detection on thousands of preview frames it crashed depending on the image resolution after 4000 frames. The app allocated in total 2 GB of memory at the time of the crash.


Just you want to investigate further it seems that the memory on the heap is not automatically released when using alloc with MLImage manually. I don't know what is happening in the Code of the MLKit library, but may be there is done some old fashioned Memory Management (MRC) instead of Automatic Reference Counting.

Nevertheless my issue was solved after manually releasing the memory.
 
Upvote 0
Top