I have 50000 grayscale images with 56*56 pixels each one. I need to flatten images and stakck it in the same array with dimensions 50000*3136 after that export the file as .CSV. I am doing this code which load all images in the memory which can cause a problem if we have not enough memory space.
imagesToArray[pathsrc_, pathdes_] := Module[{filesList, data}, (
(* pathsrc_ : list of images path *)
(* pathdes_ : CSV file path*)
filesList = FileNames["*.png", pathsrc];
Print["Number of images :", Length@filesList];
data =
Table[Flatten[ImageData[Import[filesList[[i]]]]], {i, 1,
Length@filesList}];
Export[pathdes, data];
data
)]
Is there any alternative to do it faster without memory problem?
Answer
You can combine @nikie's approach above with the use of a faster built-in import function.
If you can forgo all the behind-the-scene checking that Import
does, you can try using the built-in function that Import
ultimately calls to read in a PNG file, which is Image`ImportExportDump`ImageReadPNG
. I found that out by using Trace@Import[somePNGfile]
and wading through quite a lot of output. Incidentally, the counterpart to this function also exists, i.e. ImageWritePNG
, but it requires multiple arguments and I haven't figured that one out yet; however, Export
is already quite a bit zippier than Import
at least for PNG files, so the need is less pronounced there.
It returns a list containing the image imported. To get each image, you can use e.g.
First@Image`ImportExportDump`ImageReadPNG[pathToImage]
It is at least 10x faster than using Import
, and quite possibly more.
For instance, let's generate 200 small PNGs of the kind you are working with:
MapIndexed[
Export["images\\" <> ToString[First@#2] <> ".png", #1] &,
Image /@ RandomReal[{0, 1}, {200, 56, 56}]
];
Now let's compare timings:
First@Image`ImportExportDump`ImageReadPNG["images\\" <> ToString[#] <> ".png"] & /@
Range[1, 200]; // AbsoluteTiming
Import["images\\" <> ToString[#] <> ".png"] & /@ Range[1, 200]; // AbsoluteTiming
(* Out:
{0.221601, Null}
{15.5932, Null}
*)
That's a 70x speedup!
Comments
Post a Comment