Here are the step-by-step algorithms for every technique across all 10 experiments.

---

## SECTION 1: SINGLE-IMAGE ALGORITHMS

### Experiment 1: Image Enhancement & Filters

* **Q1: Minimum Filter Algorithm**
1. Define an odd-sized rectangular structuring element matrix $K$.
2. Slide $K$ across every pixel $(x, y)$ of the grayscale image.
3. Compute the local minimum pixel intensity within the spatial neighborhood covered by $K$.
4. Replace the target pixel at $(x, y)$ in the output image with this minimum intensity value.


* **Q2: Average (Mean) Filter Algorithm**
1. Define a sliding rectangular window kernel of size $M \times N$ with uniform weights $1/(M \cdot N)$.
2. Traverse every pixel $(x,y)$ of the input image.
3. Sum all pixel intensity values inside the window centered at $(x,y)$.
4. Divide the accumulated sum by the total pixel count $(M \cdot N)$ and write the mean value to the output image.


* **Q3: Contrast Stretching Algorithm**
1. Find the minimum ($I_{\min}$) and maximum ($I_{\max}$) intensity values across the input image.
2. Define the desired output target dynamic range $[O_{\min}, O_{\max}]$ (e.g., $[0, 255]$).
3. For each pixel with intensity $I(x,y)$, apply the linear scaling formula:

$$O(x,y) = \frac{I(x,y) - I_{\min}}{I_{\max} - I_{\min}} \times (O_{\max} - O_{\min}) + O_{\min}$$


4. Clip output intensities to valid image bounds and generate the stretched image.


* **Q4: Histogram Equalization Algorithm**
1. Calculate the intensity histogram $h(v)$ for all grey levels $v \in [0, 255]$.
2. Normalize $h(v)$ by dividing by total pixel count $N$ to compute Probability Density Function (PDF) $p(v)$.
3. Compute Cumulative Distribution Function (CDF): $cdf(v) = \sum_{i=0}^{v} p(i)$.
4. Map each original pixel intensity $v$ to equalized output intensity $v'$ using:

$$v' = \text{round}\left(\frac{cdf(v) - cdf_{\min}}{1 - cdf_{\min}} \times 255\right)$$




* **Q5: Comparative Analysis Algorithm**
1. Process input image in parallel using Minimum Filter, Average Filter, Contrast Stretching, and Histogram Equalization.
2. Plot spatial output images alongside corresponding intensity histograms.
3. Compare edge preservation, noise suppression, and contrast distribution metrics.



---

### Experiment 2: Noise Filtering & Edge Detection

* **Q1: Median Filter Algorithm**
1. Corrupt image with salt-and-pepper noise by randomly overriding pixels to $0$ or $255$.
2. Slide an $N \times N$ neighborhood window across each pixel $(x,y)$.
3. Extract all pixel intensities inside the window and sort them in ascending order.
4. Select the median element from the sorted array and assign it to output pixel $(x,y)$.


* **Q2: Summed Area Table (SAT) Box Filter Algorithm**
1. Compute Integral Image $I_{\text{sat}}(x,y) = \sum_{x' \le x, y' \le y} I(x',y')$ in a single pass.
2. For any target box region $(x_1, y_1)$ to $(x_2, y_2)$, extract submatrix sum $S$ in $O(1)$ constant time:

$$S = I_{\text{sat}}(x_2,y_2) - I_{\text{sat}}(x_1,y_2) - I_{\text{sat}}(x_2,y_1) + I_{\text{sat}}(x_1,y_1)$$


3. Divide region sum $S$ by region pixel area to obtain average intensity per pixel.


* **Q3: Sobel Edge Detection Algorithm**
1. Convolve grayscale image with horizontal Sobel kernel $G_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix}$.
2. Convolve image with vertical Sobel kernel $G_y = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ 1 & 2 & 1 \end{bmatrix}$.
3. Compute total gradient magnitude at each pixel: $G = \sqrt{G_x^2 + G_y^2}$ (or approximation $\vert{}G_x\vert{} + \vert{}G_y\vert{}$).


* **Q4: Canny Edge Detection Algorithm**
1. Smooth image using a Gaussian filter to reduce high-frequency noise.
2. Compute intensity gradients $G$ and gradient orientation angle $\theta = \arctan(G_y / G_x)$.
3. Apply Non-Maximum Suppression (NMS) along gradient directions to thin edge candidates down to 1-pixel widths.
4. Apply Hysteresis Thresholding using lower ($T_{\text{low}}$) and upper ($T_{\text{high}}$) bounds to retain strong edges and conditionally preserve weak edges connected to strong edges.



---

### Experiment 3: Morphological Operations & Distance Transform

* **Q1: Morphological Erosion Algorithm**
1. Place structuring element $B$ over binary image pixel $(x,y)$.
2. Output pixel is $1$ if and only if $B$ completely fits inside foreground pixels (Logical AND over neighborhood).
3. Otherwise, set output pixel to $0$.


* **Q2: Morphological Dilation Algorithm**
1. Place structuring element $B$ over binary image pixel $(x,y)$.
2. Output pixel is $1$ if at least one pixel in $B$ overlaps with foreground pixels (Logical OR over neighborhood).
3. Otherwise, set output pixel to $0$.


* **Q3: Morphological Opening & Closing Algorithm**
* **Opening (Noise Suppression):** Perform Erosion followed by Dilation ($A \circ B = (A \ominus B) \oplus B$). Removes isolated foreground noise points.
* **Closing (Gap Filling):** Perform Dilation followed by Erosion ($A \bullet B = (A \oplus B) \ominus B$). Fills small holes and bridges interior gaps.


* **Q4: Distance Transform Algorithm**
1. Convert image to binary mask where foreground objects are $1$ and background is $0$.
2. Initialize distance matrix: background pixels set to $0$, foreground pixels set to $\infty$.
3. Perform Two-Pass Raster Scan (Top-Left to Bottom-Right, then Bottom-Right to Top-Left) using metric metric distances ($L1$ Manhattan or $L2$ Euclidean) to compute distance from every pixel to its nearest zero-pixel.



---

### Experiment 4: Frequency Spectrum & Color Edges

* **Q1: 2D Fast Fourier Transform (FFT) Algorithm**
1. Convert 2D spatial image signal $f(x,y)$ to discrete frequency domain $F(u,v)$ via 2D DFT formula:

$$F(u,v) = \sum_{x=0}^{M-1} \sum_{y=0}^{N-1} f(x,y) e^{-j 2\pi \left(\frac{ux}{M} + \frac{vy}{N}\right)}$$


2. Apply `fftshift` to center low-frequency components at $(M/2, N/2)$.
3. Compute log-scaled magnitude spectrum: $S(u,v) = c \cdot \log(1 + \vert{}F(u,v)\vert{})$.



---

### Experiment 5: Advanced Color Image Segmentation

* **Q1: K-Means Clustering Algorithm**
1. Select $K$ random initial cluster centroids in $RGB$ color space.
2. Assign each pixel vector to its closest centroid using Euclidean color distance.
3. Recompute centroid locations by taking the average color vector of all pixels in each cluster.
4. Repeat assignment and update steps until centroid movement falls below threshold $\epsilon$.


* **Q2: Mean Shift Segmentation Algorithm**
1. Represent image pixels as combined spatial-range vectors $[x, y, R, G, B]$.
2. Define spatial radius $h_s$ and color range radius $h_r$.
3. Iteratively compute mean shift vector within bandwidth window and shift window center to local mode.
4. Merge modes that lie closer than spatial/range bandwidth thresholds and assign pixels to corresponding modes.


* **Q3: Spectral Clustering Algorithm**
1. Construct similarity graph $W$ using $k$-nearest neighbors across downsampled spatial-color pixel vectors.
2. Compute unnormalized or normalized Graph Laplacian matrix $L = D - W$.
3. Compute eigenvectors corresponding to the $K$ smallest eigenvalues of $L$.
4. Cluster rows of the reduced eigenvector matrix using K-Means to partition image pixels into regions.



---

### Experiment 6: Structural Features & Interest Points

* **Q1: Hough Transform Line Detection Algorithm**
1. Run Canny edge detection to extract thin binary edge map.
2. Parameterize lines using polar form: $\rho = x \cos\theta + y \sin\theta$.
3. Construct 2D accumulator array grid over $(\rho, \theta)$ domain.
4. For every edge pixel $(x,y)$, increment accumulator bins for all valid $\theta \in [0, 180^\circ)$.
5. Select $(\rho, \theta)$ accumulator peaks exceeding threshold $T$ as detected geometric lines.


* **Q2: Harris Corner Detection Algorithm**
1. Compute spatial image gradients $I_x$ and $I_y$ using Sobel operators.
2. Construct local Structure Tensor matrix $M$ over window $W$:

$$M = \sum_{W} \begin{bmatrix} I_x^2 & I_x I_y \\ I_x I_y & I_y^2 \end{bmatrix}$$


3. Calculate Corner Response score $R = \det(M) - k \cdot (\text{trace}(M))^2$.
4. Apply thresholding ($R > T$) followed by Non-Maximum Suppression to detect distinct corner points.



---

### Experiment 7 & 8: Feature Detection & Single-Image Object Detection

* **Q1: SIFT Keypoint Detection Algorithm**
1. Construct Scale-Space Pyramid using multi-scale Gaussian blur octaves.
2. Calculate Difference-of-Gaussians (DoG) images across adjacent scale levels.
3. Locate local extrema by comparing pixels with 26 spatial/scale neighbors.
4. Refine sub-pixel extrema locations and eliminate low-contrast/edge response points.
5. Assign dominant orientation angles to keypoints based on local gradient histograms.


* **Q2: Single-Image Deep Learning Object Detection (YOLO / Faster R-CNN) Algorithm**
1. Input preprocessed image frame into Convolutional Neural Network backbone.
2. Predict bounding box candidate coordinates $(x, y, w, h)$, objectness confidence scores, and class probability vectors.
3. Filter predictions using absolute confidence cutoff $T_{\text{conf}}$.
4. Run Non-Maximum Suppression (NMS) using Intersection over Union (IoU) overlap metric to remove redundant duplicate boxes.



---

### Experiment 10: Discrete-Time Kalman Filter

* **Q1: Linear Kalman Filtering Algorithm**
1. **Initialization:** Set initial state estimate $\hat{x}_0$ and error covariance matrix $P_0$.
2. **Predict Phase (Time Update):**
* Project state ahead: $\hat{x}_k^- = F \hat{x}_{k-1}$
* Project covariance ahead: $P_k^- = F P_{k-1} F^T + Q$


3. **Update Phase (Measurement Correction):**
* Compute Innovation Residual: $y_k = z_k - H \hat{x}_k^-$
* Compute Innovation Covariance: $S_k = H P_k^- H^T + R$
* Calculate Optimal Kalman Gain: $K_k = P_k^- H^T S_k^{-1}$
* Update State Estimate: $\hat{x}_k = \hat{x}_k^- + K_k y_k$
* Update Error Covariance: $P_k = (I - K_k H) P_k^-$





---

## SECTION 2: MULTI-IMAGE ALGORITHMS

### Experiment 7: Multi-Image Feature Matching

* **Q1: SIFT Feature Matching & Lowe's Ratio Test Algorithm**
1. Extract SIFT keypoints and $128$-dimensional descriptor vectors for Images $I_1$ and $I_2$.
2. For each descriptor $d_i \in I_1$, compute Euclidean distances to all descriptors in $I_2$ using Brute-Force Matcher.
3. Retrieve the two nearest neighbors ($m_1$ with distance $D_1$, and $m_2$ with distance $D_2$).
4. Apply Lowe's Ratio Test: Keep match $m_1$ if $D_1 < \text{ratio} \times D_2$ (e.g., $\text{ratio} = 0.75$).
5. Count valid matches; if count exceeds threshold $N_{\text{thresh}}$, confirm matching object presence.



---

### Experiment 8: Comparative Multi-Image Detection Benchmark

* **Q1: Comparative Performance Benchmark Algorithm**
1. Load duplicate instances of input test image frames.
2. Pass Image 1 through Faster R-CNN network pipeline; measure execution wall-clock time and total detected objects.
3. Pass Image 2 through YOLO network pipeline; measure execution wall-clock time and total detected objects.
4. Generate side-by-side composite comparison displays with overlaid bounding boxes and timing metrics.



---

### Experiment 9: 3D Reconstruction & Bundle Adjustment

* **Q1: Two-View 3D Reconstruction & Bundle Adjustment Algorithm**
1. **Correspondence Extraction:** Extract SIFT descriptors across Views $I_1, I_2$ and apply Lowe's Ratio Test to obtain matching 2D point pairs $(p_1, p_2)$.
2. **Essential Matrix Estimation:** Compute Essential Matrix $E$ using RANSAC to eliminate outlier matches:

$$p_2^T K^{-T} E K^{-1} p_1 = 0$$


3. **Camera Pose Recovery:** Decompose $E$ into relative rotation $R$ and translation $t$ using Singular Value Decomposition ($SVD$).
4. **Triangulation:** Solve $x \times (P X) = 0$ using Direct Linear Transform ($DLT$) on projection matrices $P_1 = K[I\vert{}0]$ and $P_2 = K[R\vert{}t]$ to compute initial 3D point cloud $X$.
5. **Filter Points:** Discard reconstructed points with negative depth values or depth exceeding $Z_{\max}$.
6. **Bundle Adjustment Optimization:** Refine joint camera parameters $[R, t]$ and 3D point positions $X$ by minimizing non-linear re-projection error via Levenberg-Marquardt optimization:

$$\arg\min_{R, t, X} \sum_{i} \left( \Vert{}p_{1,i} - \pi(P_1 X_i)\Vert{}^2 + \Vert{}p_{2,i} - \pi(P_2 X_i)\Vert{}^2 \right)$$