Skip to content

Instantly share code, notes, and snippets.

@iomonad
Created April 13, 2024 10:26
Show Gist options
  • Save iomonad/03518cc21fd3a311a1272f3bff9c9c32 to your computer and use it in GitHub Desktop.
Save iomonad/03518cc21fd3a311a1272f3bff9c9c32 to your computer and use it in GitHub Desktop.
Convert Monochrome PNG image to boolean Matrix in Clojure
(ns user
(:require [clojure.java.io :as io]
[clojure.core.match :as m])
(:import java.awt.Color
java.awt.image.BufferedImage
javax.imageio.ImageIO))
(defn interpolate-colors
[^Color color & {:keys [lint?] :or {lint? true}}]
(m/match [(.getRed color) (.getGreen color) (.getBlue color)]
[0 0 0] 1
[255 255 255] 0
:else (if lint? 0 1)))
(defn monochrome->matrix
[^BufferedImage image interpolate-fn]
(let [x (.getWidth image)
y (.getHeight image)]
(for [ix (range x)]
(for [iy (range y)]
(interpolate-fn (Color. (.getRGB image ix iy)))))))
(comment
(def image (ImageIO/read (io/file "/home/iomonad/5MT29BP.")))
(monochrome->matrix image interpolate-colors))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment