The following procedure will extract the
saturation channel and return the mean value.
(define (get-saturation layer)
(let* ((image (car (gimp-item-get-image layer)))
(sat-image (car (plug-in-decompose RUN-NONINTERACTIVE
image
layer
"Saturation"
FALSE )))
(sat-layer (car (gimp-image-get-active-layer sat-image)))
(saturation (car (gimp-histogram sat-layer
HISTOGRAM-VALUE
0
255 ))) )
(gimp-image-delete sat-image)
saturation ))
The following procedure will return the difference between the darkest pixel and the brightest (the traditional definition of contrast, though other methodologies may be more suitable in some situations).
Note: rather than do a brute force to find the extremes, which could take as many as 256 calls to gimp-histogram, I use a binary search (worst case, 16 calls to gimp-histogram).
(define (get-contrast layer)
(define (darkest drawable channel)
(define (avg a b)
(inexact->exact (truncate (/ (+ a b) 2))) )
(let ((lower (let loop ((lower 1))
(if (zero? (car (cddddr (gimp-histogram drawable channel 0 (pred lower)))))
(loop (* 2 lower))
(inexact->exact (truncate (/ lower 2))) ))))
; binary search for largest zero count
(let loop ((lower (max 1 lower))
(upper (* 2 lower))
(value (avg lower (* 2 lower)))
(last 0) )
(if (= last value)
value
(if (zero? (car (cddddr (gimp-histogram drawable channel 0 (pred value)))))
(loop value
upper
(avg value upper)
value )
(loop lower
value
(avg lower value)
value ))))))
(define (brightest drawable channel)
(define (avg a b)
(inexact->exact (truncate (/ (+ a b) 2))) )
(let ((upper (let loop ((upper 256))
(if (zero? (car (cddddr (gimp-histogram drawable channel (pred upper) 255))))
(loop (/ upper 2))
(* upper 2) ))))
; binary search for largest non-zero count
(if (> upper 256)
255
(let loop ((lower (max 1 (/ upper 2)))
(upper upper)
(value (avg (/ upper 2) upper))
(last 256) )
(if (= last value)
(pred value)
(if (zero? (car (cddddr (gimp-histogram drawable channel (pred value) 255))))
(loop lower
value
(avg lower value)
value )
(loop value
upper
(avg value upper)
value )))))))
(- (brightest layer HISTOGRAM-VALUE) (darkest layer HISTOGRAM-VALUE)) )