Message Boards Message Boards


Best way to repeatedly evaluate code lines?

Posted 2 months ago
2 Replies
1 Total Likes

I have a couple of images (.tif file) on which I want to perform the following commands:

  1. Import the image: img = Import["path/to/file/image01.tif"]

  2. Remove the alpha channel: img=RemoveAlphaChannel[ColorConvert[img, "Grayscale"]]

  3. Convert the imported image to data: rawImg=ImageData[img]

  4. Finally, plot the mean of the image values in the vertical direction: ListPlot[Mean[grayRaw]]

As you can see, I am not asking for help about how to those manipulations on my image file. Let's say I have a bunch of 10 such images, and I am looking for the most promising ListPlot of those.

One way I can do this is to get these 4 commands into one cell, and just change the image file name (image01.tif, image02.tif etc.).

But I would like to ask whether any one here in the community can give me a more systematic way of doing the manipulations above with a Wolfram Package file (.wl file). I read that this is the "more" correct way for developing Mathematica code (other than .nb files).

What about writing a function for doing these manipulations? Is that a good idea?

Thanks a lot!

2 Replies
Posted 2 months ago

Hi Ehud,

Writing a function is the best way to do that. Something like

meanGrayPlot[imageFileName_String] := 
  Import[imageFileName] // ColorConvert[#, "Grayscale"] & // RemoveAlphaChannel // 
  ImageData // Mean // 
  ListPlot[#, PlotLabel -> FileNameTake[imageFileName], ImageSize -> 300] &

Then map it over a list of filenames. I ran it on a directory with some PNG images I had. Change *.png to *.tif and dir to the name of the directory with your images.

FileNames["*.png", dir] // Map[meanGrayPlot] // 
  Partition[#, UpTo[3]] & // Grid[#, Frame -> All] & // 
  Labeled[#, "Mean Graylevel Plots", Top] &

enter image description here

Posted 2 months ago

That's a great answer. Thanks a lot!

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
or Discard

Group Abstract Group Abstract