Message Boards Message Boards

How to convert results from DominantColors function over multiple images?

Hi there, I'm trying to map the function DominantColors to several images in the same folder. I think I got that part sorted out.

(*Set the folder path*)
folderPath = 
  "/myfolder";

(*Get a list of file names for all the images in the folder*)
fileNames = FileNames["*.png"];

(*Iterate over the list of file names*)
For[i = 1, i <= Length[fileNames], 
 i++,(*Import the image and find the dominant color*)
 img = Import[fileNames[[i]]];
 dominantColor = DominantColors[img, 5, "NearestHTMLColor"];
 (*Print the file name and the dominant color*)
 results = Print[fileNames[[i]] <> ": " <> ToString[dominantColor]]]




Dendrobium macropodum .png: {Black, Khaki, DarkKhaki, LemonChiffon, Sienna}

Dendrobium pachyphyllum  .png: {Black, Gainsboro, Thistle, DimGray, DarkKhaki}

Dendrobium sociale .png: {Black, DarkGray, Sienna, DarkMagenta, Plum}

How do I turn the results into csv form, with headings of the file name and each of the dominant colors in separate column?

3 Replies

Hi Nik,

There are much better alternatives to For and Print. E.g.

colors = {FileNameTake@#, 
Splice@DominantColors[Import@#, 5, "NearestHTMLColor"]} & /@ fileNames

padded = PadRight[#, 6, ""] & /@ colors
columnNames = ("Color " <> ToString@#) & /@ Range@5 // Prepend["File"]

results = padded // Prepend@columnNames
Export["dominant colors.csv", results]
POSTED BY: Rohit Namjoshi

Hi Rohit,

Thank you very much for this, so the final code looks something like this

SetDirectory[NotebookDirectory[]];
fileNames = FileNames["*.png"]
colors = {FileNameTake@#, 
    Splice@DominantColors[Import@#, 5, "NearestHTMLColor"]} & /@ 
  fileNames
padded = PadRight[#, 6, ""] & /@ colors
columnNames = ("Color " <> ToString@#) & /@ Range@5 // Prepend["File"]

results = padded // Prepend@columnNames
Export["dominant colors11.csv", results]

and the output looks like this (as attached). Again, you really saved me from copying and pasting hundreds of data to excel. Thanks man!

Attachment

Attachments:

Hi Nik,

You are welcome. It might look cleaner if "File" was changed to "Species" and the ".png" was removed. To do the latter, replace FileNameTake with FileBaseName.

POSTED BY: Rohit Namjoshi
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract