;;; -*- Mode: Lisp; Syntax: Common-Lisp; -*- File: perception/algorithms/vision.lisp

;;;; Computer Vision (Chapter 25): Edges, Optical Flow, Segmentation,
;;;; Region-of-Interest Pooling and Histograms of Oriented Gradients

;;; A gray-scale image is a 2-D array of intensities, indexed by row and
;;; column.  Outside the image, a pixel has the value of the nearest pixel
;;; of the border.

(defun image-from-rows (rows)
  "The image whose rows are the lists ROWS."
  (make-array (list (length rows) (length (first rows))) :initial-contents rows))

(defun image-rows (image)
  "The list of the rows of IMAGE."
  (loop for i from 0 below (array-dimension image 0)
        collect (loop for j from 0 below (array-dimension image 1)
                      collect (aref image i j))))

(defun pixel (image i j)
  "The intensity at row I and column J, clamped to the border."
  (aref image
        (max 0 (min i (- (array-dimension image 0) 1)))
        (max 0 (min j (- (array-dimension image 1) 1)))))

(defun map-image (function image)
  "The image of (FUNCTION i j) for every pixel (i, j) of IMAGE."
  (let ((result (make-array (array-dimensions image))))
    (dotimes (i (array-dimension image 0) result)
      (dotimes (j (array-dimension image 1))
        (setf (aref result i j) (funcall function i j))))))

(defun filter-image (image kernel)
  "The correlation of IMAGE with KERNEL, a square list of rows of odd size,
  centered on each pixel."
  (let ((r (floor (length kernel) 2)))
    (map-image #'(lambda (i j)
                   (loop for row in kernel
                         for di from (- r)
                         sum (loop for k in row
                                   for dj from (- r)
                                   sum (* k (pixel image (+ i di) (+ j dj))))))
               image)))

;;;; Edge Detection (Section 25.3.1)

(defparameter *sobel-x* '((-1 0 1) (-2 0 2) (-1 0 1))
  "The Sobel kernel of the derivative along the columns (x).")

(defparameter *sobel-y* '((-1 -2 -1) (0 0 0) (1 2 1))
  "The Sobel kernel of the derivative along the rows (y).")

(defun gradient-edge-detector (image)
  "The magnitude of the intensity gradient at each pixel, from the Sobel
  derivatives (a smoothed derivative): edges are where it is large."
  (let ((gx (filter-image image *sobel-x*))
        (gy (filter-image image *sobel-y*)))
    (map-image #'(lambda (i j) (sqrt (+ (square (aref gx i j)) (square (aref gy i j)))))
               image)))

(defun laplacian-edge-detector (image)
  "The absolute value of the Laplacian (second derivative) of IMAGE."
  (let ((laplacian (filter-image image '((0 -1 0) (-1 4 -1) (0 -1 0)))))
    (map-image #'(lambda (i j) (abs (aref laplacian i j))) image)))

(defun edge-pixels (edge-image threshold)
  "The (i j) pixels of EDGE-IMAGE above THRESHOLD."
  (let ((pixels nil))
    (dotimes (i (array-dimension edge-image 0) (nreverse pixels))
      (dotimes (j (array-dimension edge-image 1))
        (when (> (aref edge-image i j) threshold)
          (push (list i j) pixels))))))

;;;; Optical Flow (Section 25.3.3)

(defun sum-squared-difference (image1 image2 &key (max-shift 3))
  "The displacement (di dj) of the content of IMAGE1 in IMAGE2, up to
  MAX-SHIFT pixels in each direction: the one with the smallest sum of
  squared differences between the pixel (i, j) of IMAGE1 and the pixel
  (i + di, j + dj) of IMAGE2 (cyclically).  Returns the displacement and
  its sum of squared differences."
  (let ((rows (array-dimension image1 0))
        (columns (array-dimension image1 1))
        (best nil)
        (best-ssd nil))
    (loop for di from (- max-shift) to max-shift
          do (loop for dj from (- max-shift) to max-shift
                   do (let ((ssd 0))
                        (dotimes (i rows)
                          (dotimes (j columns)
                            (incf ssd (square (- (aref image1 i j)
                                                 (aref image2 (mod (+ i di) rows)
                                                       (mod (+ j dj) columns)))))))
                        (when (or (null best-ssd) (< ssd best-ssd))
                          (setf best (list di dj) best-ssd ssd)))))
    (values best best-ssd)))

;;;; Segmentation (Section 25.3.4)

(defun group-contour-detection (image k &key (iterations 20))
  "Segment IMAGE into K regions of similar intensity, by k-means clustering
  of the intensities (the centers start evenly spread between the darkest
  and the brightest pixel).  Returns the image of the region numbers, 0 to
  K - 1, and the list of the mean intensities of the regions."
  (let* ((intensities (loop for i from 0 below (array-total-size image)
                            collect (row-major-aref image i)))
         (low (reduce #'min intensities))
         (high (reduce #'max intensities))
         (centers (loop for c from 0 below k
                        collect (if (= k 1)
                                    low
                                  (+ low (/ (* c (- high low)) (- k 1))))))
         (labels-of nil))
    (flet ((nearest (x)
             (let ((best 0))
               (loop for center in centers
                     for c from 0
                     when (< (abs (- x center)) (abs (- x (nth best centers))))
                       do (setf best c))
               best)))
      (dotimes (iteration iterations)
        (setf labels-of (mapcar #'nearest intensities)
              centers (loop for center in centers
                            for c from 0
                            collect (let ((members (loop for x in intensities
                                                         for l in labels-of
                                                         when (= l c) collect x)))
                                      (if members (average members) center))))))
    (let ((regions (make-array (array-dimensions image))))
      (loop for l in labels-of
            for i from 0
            do (setf (row-major-aref regions i) l))
      (values regions centers))))

(defun image-to-graph (image)
  "The graph of the pixels of IMAGE, each linked to its neighbors below
  and to the right, with the weight 255 - |difference of intensity| (as
  used by the min-cut segmentation of Section 25.3.4): an alist that maps
  each pixel (i j) to the list of (neighbor . weight)."
  (let ((rows (array-dimension image 0))
        (columns (array-dimension image 1))
        (graph nil))
    (dotimes (i rows (nreverse graph))
      (dotimes (j columns)
        (push (cons (list i j)
                    (loop for (ni nj) in (list (list (+ i 1) j) (list i (+ j 1)))
                          when (and (< ni rows) (< nj columns))
                            collect (cons (list ni nj)
                                          (- 255 (abs (- (aref image i j)
                                                         (aref image ni nj)))))))
              graph)))))

;;;; Region-of-Interest Pooling (Section 25.5)

(defun pool-roi (feature-map roi pooled-height pooled-width)
  "Max-pool the region of interest ROI of the 2-D FEATURE-MAP into a
  POOLED-HEIGHT x POOLED-WIDTH grid.  ROI is (y-min x-min y-max x-max), as
  fractions of the height and width of the map; the region is divided into
  equal areas, the last row and column of areas taking the remainder.
  Returns the pooled values as a list of rows."
  (let* ((height (array-dimension feature-map 0))
         (width (array-dimension feature-map 1))
         (h-start (floor (* height (first roi))))
         (w-start (floor (* width (second roi))))
         (h-end (floor (* height (third roi))))
         (w-end (floor (* width (fourth roi))))
         (h-step (floor (- h-end h-start) pooled-height))
         (w-step (floor (- w-end w-start) pooled-width)))
    (loop for a from 0 below pooled-height
          collect (loop for b from 0 below pooled-width
                        collect (let ((top (+ h-start (* a h-step)))
                                      (bottom (if (< (+ a 1) pooled-height)
                                                  (+ h-start (* (+ a 1) h-step))
                                                h-end))
                                      (left (+ w-start (* b w-step)))
                                      (right (if (< (+ b 1) pooled-width)
                                                 (+ w-start (* (+ b 1) w-step))
                                               w-end)))
                                  (loop for i from top below bottom
                                        maximize (loop for j from left below right
                                                       maximize (aref feature-map i j))))))))

(defun pool-rois (feature-map rois pooled-height pooled-width)
  "The ROI pooling of each of the regions of interest ROIS."
  (mapcar #'(lambda (roi) (pool-roi feature-map roi pooled-height pooled-width))
          rois))

;;;; Histograms of Oriented Gradients (Dalal and Triggs, 2005)

(defun image-gradient (image)
  "The derivatives of IMAGE along the rows and along the columns: central
  differences inside the image, one-sided differences on its border."
  (let ((rows (array-dimension image 0))
        (columns (array-dimension image 1)))
    (flet ((derivative (n index value)
             (cond ((= n 1) 0)
                   ((= index 0) (- (funcall value 1) (funcall value 0)))
                   ((= index (- n 1)) (- (funcall value index) (funcall value (- index 1))))
                   (t (/ (- (funcall value (+ index 1)) (funcall value (- index 1))) 2)))))
      (values (map-image #'(lambda (i j)
                             (derivative rows i #'(lambda (k) (aref image k j))))
                         image)
              (map-image #'(lambda (i j)
                             (derivative columns j #'(lambda (k) (aref image i k))))
                         image)))))

(defun hog (image &key (cell-size 8) (bins 9) (block-size 2))
  "The histogram of oriented gradients descriptor of IMAGE: for each cell
  of CELL-SIZE x CELL-SIZE pixels, a histogram of the unsigned orientations
  of the gradient (0 to 180 degrees, in BINS bins) weighted by its
  magnitude; then the histograms of each block of BLOCK-SIZE x BLOCK-SIZE
  cells, normalized to unit length, are concatenated into one list."
  (multiple-value-bind (gy gx) (image-gradient image)
    (let* ((cells-y (floor (array-dimension image 0) cell-size))
           (cells-x (floor (array-dimension image 1) cell-size))
           (bin-width (/ 180.0 bins))
           (histograms (make-array (list cells-y cells-x bins) :initial-element 0)))
      (dotimes (i (* cells-y cell-size))
        (dotimes (j (* cells-x cell-size))
          (let* ((dy (aref gy i j))
                 (dx (aref gx i j))
                 (magnitude (sqrt (+ (* dx dx) (* dy dy))))
                 (angle (if (zerop magnitude)
                            0
                          (mod (* (/ 180 pi) (atan dy dx)) 180)))
                 (bin (mod (floor angle bin-width) bins)))
            (incf (aref histograms (floor i cell-size) (floor j cell-size) bin)
                  magnitude))))
      (loop for block-y from 0 to (- cells-y block-size)
            nconc (loop for block-x from 0 to (- cells-x block-size)
                        nconc (let* ((cells (loop for cy from block-y below (+ block-y block-size)
                                                  nconc (loop for cx from block-x below (+ block-x block-size)
                                                              nconc (loop for k from 0 below bins
                                                                          collect (aref histograms cy cx k)))))
                                     (norm (sqrt (+ (sum cells #'square) 1e-10))))
                                (mapcar #'(lambda (v) (/ v norm)) cells)))))))
