Home > OS >  ImageMagick - get all color values in separate arrays
ImageMagick - get all color values in separate arrays

Time:04-08

I need to get all R,G,B values for each pixel in separate arrays.

This command:

convert image.png -depth 8 txt:

outputs multiple lines like this:

277,533: (158,167,146)  #9EA792  srgb(158,167,146)

I could separate the values of one line:

R_pixel=$(echo $test | cut -d "(" -f2 | cut -d "," -f1)
G_pixel=$(echo $test | cut -d "," -f3 | cut -d "," -f2)
B_pixel=$(echo $test | cut -d "," -f4 | cut -d ")" -f1)

Which gets me 158 for R_pixel, but not for all lines.

But there has to be a better way, possibly directly from ImageMagick, right?

This does not get their correct values for R, as it doesn't matter which channel I choose:

R_pixel_array=( $( convert image.png -format "%[fx:r]" -compress none  PGM:-) )

In the end, I need an R_array, which contains only R values for each pixel.

CodePudding user response:

You are very close. Would you please try the following:

R_pixel_array=( $(convert image.png -depth 8 -channel R -separate -compress none PGM:- | awk '!/^#/&&  c>=4') )
  • The -channel R and -separate options extract the red channel only.
  • The PGM: prefix converts to a gray scale (one channel per pixel) image.
  • The awk '!/^#/&& c>=4' command skips the header lines.

CodePudding user response:

Make a 4x3 starting image for testing:

magick -size 4x3 gradient:red-blue start.png

Enlarged

enter image description here

magick start.png -channel r -separate -crop 1x1 -format "%[fx:int(p{0,0}*255)]\n" info: 
255
255
255
255
127
127
127
127
0
0
0
0
  • Related