I have an image, for example

img = Import["https://i.stack.imgur.com/fPZM7.jpg"]

I would like to save in a text file the pixel positions and their values. At first I tried to export the table:

Table[{i, j, PixelValue[img, {i, j}][[1]], PixelValue[img, {i, j}][[2]],
       PixelValue[img, {i, j}][[3]]}, {i, 1, ImageDimensions[img][[1]]},
      {j, 1, ImageDimensions[img][[2]]}]

that what it is doing is a table with 5 columns: the first two columns are the pixel position (x,y) and the three last columns are the RED, GREEN, BLUE channel pixel values. When I do that, it takes like forever.

I would like to ask if there is a more efficient way to do such extraction and export the pixel information as the table I described above.

Thanks in advance!!

  • 3
    $\begingroup$ Try this Flatten[MapIndexed[Join[#2, #1] &, ImageData[img], {2}], 1] $\endgroup$ – swish Mar 30 '18 at 21:59
  • $\begingroup$ Ooohhhh thanks dear @swish, it works perfectly and very quick :-) $\endgroup$ – user115376 Mar 31 '18 at 9:16
  • $\begingroup$ Try also Flatten[ Join[ Outer[List, Sequence @@ N[Range /@ Reverse@ImageDimensions[img]], 1], ImageData[img], 3 ], 1] $\endgroup$ – Henrik Schumacher Apr 1 '18 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.