Grayscale image: Difference between revisions

Content added Content deleted
(→‎{{header|REXX}}: added a section to show how a "color" may be expressed in other forms in REXX.)
Line 213: Line 213:
=={{header|Clojure|Clojure}}==
=={{header|Clojure|Clojure}}==
<lang clojure>
<lang clojure>
(import '[java.io File]
(ns rgb-to-gray.clj
'[javax.imageio ImageIO]
(:import [java.io File]
[javax.imageio ImageIO]
'[java.awt Color]
[java.awt Color]
'[java.awt.image BufferedImage]))
[java.awt.image BufferedImage]))


(defn rgb-to-gray [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)
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)))))))


(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]
(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)
(
do
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"

(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
(println
(write-matrix-to-image
(write-matrix-to-image
(rgb-to-gray
(rgb-to-gray
(ImageIO/read (new File "test.jpg"))
(ImageIO/read (new File "test.jpg")))
"test-gray-cloj.png"))
)
"test-gray-cloj.png")
)


</lang>
</lang>