Programmatically determine the average greyscale

-hh hh at livecode.org
Fri Feb 19 12:48:57 EST 2016


BR and jacques,

it's kind of a 'LC-mania' of me to put a fully working
solution, if available, near the end of a thread.

Here's one I made for converting to grayLevel colours and
adapted to your case. Tell us your solution also, please.
The following is pretty fast, I wrote it after learning some
secrets of imageData from Bernd's "little stacks" and forum
posts. So praise him and LC's pointer arithmetic for the speed.

It takes here on a medium fast machine in average 16 ms for
your 20x20 px image segment
(incl. setting of the button's or field's adjusted textcolor)

=======

local ii="preview", bb= "bigBen" -- image's and button's name

## Function computes an average RGB-colour value for an image
## (or a rectangular segment of it).
## Divide below in each loop if image is *very* large
-- x = imageData 32bit ARGB of the full img ii
-- w = width of the full image ii
-- pixel rows = r1 to r1, pixel cols = c1 to c2
-- wr, wg, wb = weights for r, g, b
function weightedColorMean x,w,r1,r2,c1,c2,wr,wg,wb
  repeat with j=r1 to r2
    put (j-1)*w into j0
    repeat with i=c1 to c2
      add sum( \
            wr*byteToNum(byte 4*(j0+i)-2 of x), \
            wg*byteToNum(byte 4*(j0+i)-1 of x), \
            wb*byteToNum(byte 4*(j0+i)   of x) ) to s
    end repeat
  end repeat
  return s div (sum(wr,wg,wb)*(r2-r1+1)*(c2-c1+1))
end weightedColorMean

on mouseUp
  put the millisecs into m1
  put the width of img ii into w
  put the imageData of img ii into iData
  -- perception values:
  put weightedColorMean(iData,w,20,40,20,40,1,6,3) into M 
  -- usual luminance formula (wikipedia, cited by Jaques)
  -- put weightedColorMean(iData,w,20,40,20,40,3,10,1) into M 
  if M > 191 then set textcolor of btn bb to "51,51,51"
  else set textcolor of btn bb to "255,255,225"
  put M && the millisecs-m1 && "ms" into fld 1
end mouseUp

=======
Hermann

p.s. Jacques: There is no semicolon above in that post ;-)





More information about the Use-livecode mailing list