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

;;;; Test cases for computer vision

(deftest perception
  "Edges of an image dark on the left and bright on the right: the gradient"
  "and the Laplacian are zero inside the halves, large along the boundary."
  ((setq step-image (image-from-rows '((0 0 0 9 9 9) (0 0 0 9 9 9)
                                       (0 0 0 9 9 9) (0 0 0 9 9 9)))))
  ((setq edges (gradient-edge-detector step-image)))
  ((list (aref edges 1 0) (aref edges 1 2) (aref edges 1 3) (aref edges 1 5))
   '(0.0 36.0 36.0 0.0))
  ((edge-pixels edges 10)
   '((0 2) (0 3) (1 2) (1 3) (2 2) (2 3) (3 2) (3 3)))
  ((image-rows (laplacian-edge-detector step-image))
   '((0 0 9 9 0 0) (0 0 9 9 0 0) (0 0 9 9 0 0) (0 0 9 9 0 0)))
  "Optical flow: the second frame is the first moved 1 row down and 2"
  "columns right; the sum of squared differences finds the displacement."
  ((setq frame1 (map-image #'(lambda (i j) (+ (* 8 i) j)) (make-array '(8 8)))))
  ((setq frame2 (map-image #'(lambda (i j) (aref frame1 (mod (- i 1) 8) (mod (- j 2) 8)))
                           frame1)))
  ((multiple-value-list (sum-squared-difference frame1 frame2)) '((1 2) 0))
  ((multiple-value-list (sum-squared-difference frame1 frame1)) '((0 0) 0))
  "Segmentation of a dark and a bright region by clustering the intensities."
  ((setq two-regions (image-from-rows '((10 12 200 205) (11 13 198 202) (9 10 201 199)))))
  ((multiple-value-list (group-contour-detection two-regions 2))
   (destructuring-bind (regions centers) *
     (and (equal (image-rows regions) '((0 0 1 1) (0 0 1 1) (0 0 1 1)))
          (equal centers '(65/6 1205/6)))))
  ((image-to-graph (image-from-rows '((0 10) (20 30))))
   '(((0 0) ((1 0) . 235) ((0 1) . 245)) ((0 1) ((1 1) . 235))
     ((1 0) ((1 1) . 245)) ((1 1))))
  "Region-of-interest pooling of a 4 x 4 feature map."
  ((setq feature-map (map-image #'(lambda (i j) (+ (* 4 i) j)) (make-array '(4 4)))))
  ((pool-roi feature-map '(0 0 1 1) 2 2) '((5 7) (13 15)))
  ((pool-roi feature-map '(0.5 0 1 0.5) 1 1) '((13)))
  ((pool-rois feature-map '((0 0 1 1) (0 0 0.5 0.5)) 1 1) '(((15)) ((5))))
  "Histograms of oriented gradients of intensity ramps: one block of 2 x 2"
  "cells, whose gradients all fall in the bin of 0 degrees (a ramp along the"
  "columns) or of 80-100 degrees (along the rows)."
  ((hog (map-image #'(lambda (i j) (declare (ignore i)) j) (make-array '(8 8)))
        :cell-size 4)
   (approximately-equal * (loop for k from 0 below 36 collect (if (= (mod k 9) 0) 0.5 0))
                        1e-6))
  ((hog (map-image #'(lambda (i j) (declare (ignore j)) i) (make-array '(8 8)))
        :cell-size 4)
   (approximately-equal * (loop for k from 0 below 36 collect (if (= (mod k 9) 4) 0.5 0))
                        1e-6))
  )
