Reducing Memory Usage in ImageTools
Introduction
Options
Examples
Because an image is stored as an rtable with datatype = float[8], each pixel in each layer requires eight bytes of memory. The memory allocated for large images can be significant. To reduce memory usage, many of the commands in ImageTools have the options inplace and output that permit reusing previously allocated memory. This help page shows how they can be used.
inplace = truefalse
Specifies whether the operation is performed in-place. The default is false.
output = Image
Specifies a data structure into which the output is written. The size and number of layers must match that of the input. The output image is redimensioned so that its row and column indices match the input. The default is NULL.
with⁡ImageTools:
imgfile≔cat⁡kernelopts⁡datadir,/images/fjords.jpg:
img≔Read⁡imgfile:
Embed⁡img
The memory usage for this 480 x 640 x 3 layer image is
size≔length⁡img⁢kernelopts⁡wordsize⁢Unit⁡bit:
evalf2⁡convert⁡size,units,mebibyte
7.0⁢mebibyte
Assume that we want to adjust the gamma of layers 2 and 3 of img. The Gamma command works on all layers, so to do this we need to extract a layer, make the adjustment, and insert the modified layer back into the image. To reduce memory usage we can allocate a temporary grayscale image that is the size of one layer of the image and then reuse it as needed. To determine the effect of these options, we compare the memory usage with that when the options are not used. Assign a procedure that returns the memory allocated by the kernel.
memalloc≔↦evalf2⁡convert⁡kernelopts⁡bytesalloc⋅Unit⁡byte,units,mebibyte:
Save the current memory usage.
mem≔memalloc⁡
mem≔84.⁢mebibyte
Create the temporary image.
tmp≔Create⁡Height⁡img,Width⁡img:memalloc⁡
86.⁢mebibyte
Extract layer 2, increase its gamma, then reinsert it, inplace, into the original image.
layer≔2:
GetLayer⁡img,layer,output=tmp:memalloc⁡
Gamma⁡tmp,1.2,inplace:memalloc⁡
SetLayer⁡img,tmp,layer,inplace:memalloc⁡
Do the same with layer 3, but decrease its gamma.
layer≔3:
Gamma⁡tmp,0.8,inplace:memalloc⁡
Compute the additional memory allocated.
memalloc⁡−mem
2.⁢mebibyte
Repeat the computation (actually, do its inverse), but use assignment statements rather than inplace and output to assign tmp and img.
mem≔86.⁢mebibyte
tmp≔GetLayer⁡img,layer:memalloc⁡
88.⁢mebibyte
tmp≔Gamma⁡tmp,11.2:memalloc⁡
91.⁢mebibyte
img≔SetLayer⁡img,tmp,layer:memalloc⁡
98.⁢mebibyte
100.⁢mebibyte
tmp≔Gamma⁡tmp,10.8:memalloc⁡
95.⁢mebibyte
9.⁢mebibyte
The additional memory allocated is about three times that of the previous method, which used the inplace and output options.
See Also
ImageTools
ImageTools[ImageTypes]
Download Help Document