The following code reads all gray scale png images inside of a folder and then calculates the maximum intensity for each pixel and finally export the resulting image. This is until now the fastest code that can do that.

Please see also the answer from nikie in: Maximum brightness of two gray scale images

My question: can this code be compiled?


fNames = FileNames["*.png"];

numFiles = Length[fNames];

image = Import[fNames[[1]]];

newImage = ImageMultiply[image, 0];


  {d1, d2} = ImageData /@ {image, newImage};

  comp = UnitStep[d1 - d2];

  newImage = Image[comp*d1 + (1 - comp)*d2];

  image = Import[fNames[[i]]];

  , {i, 2, numFiles}


Export["f:\\images_dir\\analysis\\super.png", newImage, "png"],
  • 2
    $\begingroup$ Sadly, like many useful things, image related code can't be compiled $\endgroup$
    – M.R.
    Oct 15, 2016 at 4:37
  • $\begingroup$ This is really sad. I compared the solution from nike with the software ImageJ: if the system memory is not exceeded ImageJ (in Java) is for some reason "much" faster. Would it be helpful first to read all images in memory instead of doing it in the loop? $\endgroup$
    – mrz
    Oct 18, 2016 at 7:00
  • 3
    $\begingroup$ Did you try timing the individual parts? My guess would be that the arithmetic is as fast ImageJ, as it's done on packed arrays, but Import is much much slower. If so, compiling isn't the solution, replacing Import is... $\endgroup$ Oct 18, 2016 at 7:04
  • 2
    $\begingroup$ How about importing image data directly (once for all files, in the Main Evaluator, like Import[#, "Data"]&/@fNames) and then you can work on the raw data using a compiled version of the rest of your code. A custom ImageMultiply can be easily written that works directly on an integer array. Then you Export again on the ME. $\endgroup$ Oct 18, 2016 at 7:39


Browse other questions tagged or ask your own question.