Solving systems of linear equations (including under- and over-determined)
In this recipe, you will learn how to solve systems of linear equations using OpenCV. This functionality is a key building block of many computer vision and machine learning algorithms.
Getting ready
Before you proceed with this recipe, you need to install the OpenCV 3.3 (or greater) Python API package.
How to do it...
You need to complete the following steps:
- Import the modules:
import cv2 import numpy as np
- Generate a system of linear equations:
N = 10 A = np.random.randn(N,N) while np.linalg.matrix_rank(A) < N: A = np.random.randn(N,N) x = np.random.randn(N,1) b = A @ x
- Solve the system of linear equations:
ok, x_est = cv2.solve(A, b) print('Solved:', ok) if ok: print('Residual:', cv2.norm(b - A @ x_est)) print('Relative error:', cv2.norm(x_est - x) / cv2.norm(x))
- Construct an over-determined system of linear equations:
N = 10 A = np.random.randn(N*2,N) while np.linalg.matrix_rank(A) < N: A = np.random...