Skip to content

Instantly share code, notes, and snippets.

@joeatwork
Created March 6, 2012 18:48
Show Gist options
  • Save joeatwork/1988150 to your computer and use it in GitHub Desktop.
Save joeatwork/1988150 to your computer and use it in GitHub Desktop.
Quick and dirty grayscale image to incanter matrix round trip
(import [javax.imageio ImageIO]
[java.awt.image BufferedImage])
(require 'clojure.java.io)
(require 'incanter.core)
(defn read-image-matrix [imagefile]
(let [imagefile (clojure.java.io/as-file imagefile)
raster (.. (. ImageIO read imagefile) getData)
left (. raster getMinX)
width (. raster getWidth)
right (+ left width)
top (. raster getMinY)
height (. raster getHeight)
bottom (+ top height)
xrange (range left right)
yrange (range top bottom)]
(incanter.core/matrix
(for [i xrange j yrange]
(let [pixel (. raster getPixel i j nil)]
(aget pixel 0))) width)))
(defn write-image-matrix [imagefile M]
(let [width (incanter.core/ncol M)
height (incanter.core/nrow M)
image (BufferedImage. width height BufferedImage/TYPE_BYTE_GRAY)
raster (. image getRaster)]
(doseq [i (range width) j (range height)]
(. raster setPixel i j (float-array (incanter.core/sel M i j))))
(. ImageIO write image "png" imagefile)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment