Grayscale image: Difference between revisions

(→‎{{header|REXX}}: added a section to show how a "color" may be expressed in other forms in REXX.)
Line 213:
=={{header|Clojure|Clojure}}==
<lang clojure>
(:import '[java.io File]
(ns rgb-to-gray.clj
'[javax.imageio ImageIO]
(:import [java.io File]
'[javaxjava.imageioawt ImageIOColor]
'[java.awt.image ColorBufferedImage]))
[java.awt.image BufferedImage]))
 
(nsdefn rgb-to-gray.clj [color-image]
(let [width (.getWidth color-image)]
(partition width
(for [x (range width)
y (range (.getHeight color-image))]
(let [rgb (.getRGB color-image x y) rgb-object (new Color rgb) ]
rgb-object (new Color rgb) (
r (.getRed rgb-object)
g (.getGreen rgb-object)
b (.getBlue rgb-object) (
a (.getAlpha fn [xrgb-object)]
;Compute the grayscale value an return it: L = 0.2126·R + 0.7152·G + 0.0722·B
(+ (* r 0.2126) (* g 0.7152) (* b 0.0722)))))))
 
(defn rgb-to-gray [color-image] (map
(fn [y] (
map
(
fn [x]
(
let [rgb (.getRGB color-image x y) rgb-object (new Color rgb) ]
(
let [r (.getRed rgb-object) g (.getGreen rgb-object) b (.getBlue rgb-object) a (.getAlpha rgb-object)]
(
;Compute the grayscale value an return it: L = 0.2126·R + 0.7152·G + 0.0722·B
+ (* r 0.2126) (* g 0.7152) (* b 0.0722)
)
 
)
)
 
)
 
(
range
(
.getWidth color-image
)
)
)
)
 
(
range
(
.getHeight color-image
)
)
 
 
)
)
 
(defn write-matrix-to-image [matrix filename]
(ImageIO/write
(ImageIO/write (let [height (count matrix) width (count (first matrix)) output-image (new BufferedImage width height BufferedImage/TYPE_BYTE_GRAY)]
(let [height (count matrix)
(
width (count (first matrix)) do
(ImageIO/write (let [height (count matrix) width (count (first matrix)) output-image (new BufferedImage width height BufferedImage/TYPE_BYTE_GRAY)]
(spit "/dev/null" ( ;This is the only way I could find to force evaluation so that side-effects are applied. spit just writes to null file
(doseq [row-index (range height)
map
column-index (range width)] (
(.setRGB output-image column-index row-index (.intValue (nth (nth matrix row-index) column-index))))
fn [row-index] (
output-image)
 
"png"
 
"png" (new File filename)))
map (fn [column-index]
(
.setRGB output-image column-index row-index (.intValue (nth (nth matrix row-index) column-index))
)
)
(range width)
 
 
)
)
(range height)
)
)
output-image
)
)
"png" (new File filename))
)
 
(println
(write-matrix-to-image
(rgb-to-gray
(ImageIO/read (new File "test.jpg")))
"test-gray-cloj.png"))
)
"test-gray-cloj.png")
)
 
</lang>
Anonymous user