   (Imgproc/cvtColor m gray-mat Imgproc/COLOR_BGR2GRAY)
   gray-mat)
 
-(defn update-corners! [gray-mat corners]
-  (let [max-corners MAX-CORNERS
-        quality-level 0.01
-        min-dist 5.0
-        mask BLANK-MASK
-        block-size 3
-        use-harris-detector false
-        k 0.04
-        pts (MatOfPoint.)]
-    (Imgproc/goodFeaturesToTrack gray-mat pts max-corners quality-level min-dist mask block-size use-harris-detector k)
-    (.convertTo pts corners CvType/CV_32FC2)
-    #_(Imgproc/cornerSubPix gray-mat corners WIN-SIZE NEG-ONE-SIZE TERM-CRITERIA)
-    corners))
+(defn update-corners!
+  ([gray-mat]
+     (let [corners (MatOfPoint2f.)]
+       (update-corners! gray-mat corners)))
+  ([gray-mat corners]
+     (let [max-corners MAX-CORNERS
+           quality-level 0.01
+           min-dist 5.0
+           mask BLANK-MASK
+           block-size 3
+           use-harris-detector false
+           k 0.04
+           pts (MatOfPoint.)]
+       (Imgproc/goodFeaturesToTrack gray-mat pts max-corners quality-level min-dist mask block-size use-harris-detector k)
+       (.convertTo pts corners CvType/CV_32FC2)
+       #_(Imgproc/cornerSubPix gray-mat corners WIN-SIZE NEG-ONE-SIZE TERM-CRITERIA)
+       corners)))
+
+(defn valid-pts [pts pt-status]
+  (let [p-s (filter (fn [[_ s]] (= 1 s))
+                    (map vector pts pt-status))]
+    (doall
+     (map (fn [[p _]] p) p-s))))
+
+(defn refresh-corners! [gray-mat lk-status remaining-corners old-corners]
+  (let [valid-remaining (valid-pts (.toList remaining-corners)
+                                   (.toList lk-status))
+        new-corners (.toList (update-corners! gray-mat))
+        union (vec
+               (cset/union (set valid-remaining) (set new-corners)))]
+    (.fromList old-corners (take MAX-CORNERS union))))
 
 (defn init-gray-mat [{:keys [frame-mat old-gray-mat] :as state}]
   (if (nil? old-gray-mat)

      (dorun
       (map #(draw-pt % [0 0 255 60]) old-pts)))
    (when (< 0 (count pts))
      (let [status (.toList lk-status)
            z (filter (fn [[_ s]] (= 1 s))
                      (map vector pts status))]
        (dorun
         (map (fn [[p _]] (draw-pt p))
              z))))))

(defn draw [state]
  (let [{:keys [p-image]} state]

      (-> state
          (assoc-in [:old-gray-mat] old-gray-mat)
          (assoc-in [:old-corners] (update-corners! old-gray-mat (MatOfPoint2f.)))))
    (let [{:keys [old-gray-mat old-corners new-gray-mat new-corners lk-status]} state]
      (.copyTo new-gray-mat old-gray-mat)
      (if (= 0 (mod (q/frame-count) RESET-FRAMES))
        (do
          ;; Reuse existing valid corners (still detected):
          (refresh-corners! new-gray-mat lk-status new-corners old-corners)

          ;; Brute-Force reset of corners:
          #_(update-corners! new-gray-mat old-corners))
        (do
          (.copyTo new-corners old-corners)))
      state))) 

(defn update-optical-flow [state]
