|
| 1 | +;; # Background Removal with SVD |
| 2 | + |
| 3 | +;; [original Fast.ai notebook](https://nbviewer.org/github/fastai/numerical-linear-algebra-v2/blob/master/nbs/02-Background-Removal-with-SVD.ipynb) |
| 4 | + |
| 5 | +(ns svd |
| 6 | + (:require [tablecloth.api :as tc] |
| 7 | + [com.phronemophobic.clj-media :as clj-media] |
| 8 | + [com.phronemophobic.clj-media.model :as clj-media.model] |
| 9 | + [tech.v3.datatype :as dtype] |
| 10 | + [tech.v3.tensor :as tensor] |
| 11 | + [tech.v3.libs.buffered-image :as bufimg] |
| 12 | + [scicloj.kindly.v4.kind :as kind] |
| 13 | + [fastmath.matrix :as mat]) |
| 14 | + (:import (org.apache.commons.math3.linear |
| 15 | + SingularValueDecomposition))) |
| 16 | + |
| 17 | +(def video-path |
| 18 | + "notebooks/movie/Video_003.mp4") |
| 19 | + |
| 20 | +(kind/video |
| 21 | + {:src video-path}) |
| 22 | + |
| 23 | +(clj-media/probe video-path) |
| 24 | + |
| 25 | + |
| 26 | +(def first-image |
| 27 | + (reduce (fn [_ frame] (clj-media.model/image |
| 28 | + frame)) |
| 29 | + nil |
| 30 | + (clj-media/frames |
| 31 | + (clj-media/file video-path) |
| 32 | + :video |
| 33 | + {:format (clj-media/video-format |
| 34 | + {:pixel-format |
| 35 | + :pixel-format/rgba})}))) |
| 36 | + |
| 37 | + |
| 38 | +first-image |
| 39 | + |
| 40 | +(def first-tensor |
| 41 | + (bufimg/as-ubyte-tensor |
| 42 | + first-image)) |
| 43 | + |
| 44 | +first-tensor |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +(def images |
| 49 | + (time |
| 50 | + (into [] |
| 51 | + (map clj-media.model/image) |
| 52 | + (clj-media/frames |
| 53 | + (clj-media/file video-path) |
| 54 | + :video |
| 55 | + {:format (clj-media/video-format |
| 56 | + {:pixel-format |
| 57 | + :pixel-format/rgba})})))) |
| 58 | + |
| 59 | +(count images) |
| 60 | + |
| 61 | + |
| 62 | +(def tensors |
| 63 | + (mapv bufimg/as-ubyte-tensor images)) |
| 64 | + |
| 65 | + |
| 66 | +(count tensors) |
| 67 | + |
| 68 | + |
| 69 | +(def all-frames-as-one-rectangular-tensor |
| 70 | + (let [row-size (->> tensors |
| 71 | + first |
| 72 | + dtype/shape |
| 73 | + (apply *))] |
| 74 | + (tensor/compute-tensor [row-size |
| 75 | + (count tensors)] |
| 76 | + (fn [j i] |
| 77 | + (-> (tensors i) |
| 78 | + (tensor/reshape [row-size]) |
| 79 | + (get j))) |
| 80 | + :uint8))) |
| 81 | + |
| 82 | + |
| 83 | +(def all-frames-as-one-image |
| 84 | + (time |
| 85 | + (bufimg/tensor->image |
| 86 | + all-frames-as-one-rectangular-tensor))) |
| 87 | + |
| 88 | + |
| 89 | +all-frames-as-one-image |
| 90 | + |
| 91 | + |
| 92 | +(def all-frames-as-one-matrix |
| 93 | + (->> all-frames-as-one-rectangular-tensor |
| 94 | + (take 10000) |
| 95 | + (map double-array) |
| 96 | + (mat/rows->RealMatrix))) |
| 97 | +;; 10000x350 |
| 98 | + |
| 99 | + |
| 100 | +(def svd |
| 101 | + (SingularValueDecomposition. |
| 102 | + all-frames-as-one-matrix)) |
| 103 | + |
| 104 | +(.getSingularValues svd) |
0 commit comments