Lab - Linear Regression and Bi-Linear Interpolation

Computer Vision (CSCI 4220U)

Faisal Qureshi

Faculty of Science, UOIT

You are asked to complete two tasks in this lab: 1) you are asked to write a Python program that uses least square fitting to fit a line to 2D data, and 2) you are asked to write bi-linear interpolation routine that can be used to rotate an image by an angle \(\theta\).

For both tasks you are asked to not use built-in routines available in OpenCV or Scipy packages. You are only allowed to use basic vector/matrix routines available in numpy package.

Task 1: Fitting a straight line to 2D data.

The following code can be used to generated 2D data: a list of \((x,y)\) points. You are asked to fit a line (\(y=mx +c\)) to this data using least square regression. Recall that \(m\) and \(c\) are unknown. The goal is to find the values of \(m\) and \(c\) that correspond to the line that best describes this data. Once we have this information, we can easily find the value of \(y\) for any arbitrary \(x\). This is called regression, and it is widely used for all sort of prediction tasks.

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def data_gen(N=100, mu=0, sigma=.4, xstart=0, xend=1):
    x = np.linspace(xstart,xend,N)
    m, c = .5, 2    
    y = m * x + c + np.random.normal(mu, sigma, N)

    return x,y
x, y = data_gen(N=10, xstart=3, xend=8)


Task 2: Image Rotation

Complete the following routine.

def im_rotate(img, angle_in_degrees):
    # Should return the rotated image.

2D Rotations

You can use the following rotation matrix to perform 2D rotation in Euclidean space.

\[ R = \left[ \begin{array}{cc} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{array} \right] \]

Recall that \(\theta\) is specified in Radians.

You can use this matrix to determine where a pixel at location \((x,y)\) in the original image will end up in the rotated image. Specifically

\[ \left[ \begin{array}{c} x' \\ y' \end{array} \right] = \left[ \begin{array}{cc} \cos \theta & -\sin \theta \\ \sin \theta & \cos \theta \end{array} \right] \left[ \begin{array}{c} x \\ y \end{array} \right] \]

For the sake of this exercise we assume that the pixels locations \((x',y')\) in the rotated image that do not receive any value from the source image are colored black.

I suggest that first you try to do this without bi-linear interpolation. Add it once you are able to perform image rotation without using bi-linear interpolation. Does using bi-linear interpolation improves the visual quality of the rotated image? How can you tell if image A has a better quality than image B?

Learning outcomes (or things that you would need to do to complete this lab)

What to submit

Complete both tasks in a single Jupyter notebook, and submit this notebook.