Created
March 6, 2012 18:48
-
-
Save joeatwork/1988150 to your computer and use it in GitHub Desktop.
Quick and dirty grayscale image to incanter matrix round trip
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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