I wanted to learn OpenCV Perspective Transform. Tutorials that I found on the internet bit complex for me to really understand what it is all about. I have to read few tutorials before really understand it.
In layman term, perspective transform is taking a rectangle area from original image and re-project the cut rectangle to our defined size canvas.
To do this, you just need 4 corner pixel points and perspective transform will do all other pixels calculation automatically based on those 4 pixels points.
The Required Pixel Points
The corner pixels points must follow the order as shown in below image.
source pixels positions order
This is considered the source pixel points.
The destination points are where you want to re-project those source points into new plane.
The size of destination plane is:
width: 1000 pixels
height: 200 pixels
I just take the source rectangle width and height.
Image Used for the Perspective Transform
I used below image to do the perspective transform.
Factory pattern is a well known creator pattern. Problem with factory pattern is whenever there is a new concrete class that will be instantiate by the creator class (that have factory method), you have to add new ‘case’ in a switch or if / else.
So this violate the Open Close Principle which states open for extensions but close for modifications.
Code below using typescript, but the concept is same for other programming language.
Factory Pattern with Switch or If Else
Factory pattern with switch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
publicstaticcreate(shape:string):Shape{
switch(type){
case'circle':
returnnewCircle();
case'rectangle':
returnnewRectangle();
case'triangle':
returnnewTriangle()
default:
throwError(`Shape isnotsupported`);
}
}
If you want to add Square shape, we need to add another case in the factory.
factory pattern - another case
1
2
case'square':
returnnewSquare()
The concept is the same with If Else
So I need to open my factory class every time there is a new shape to be add in.
Factory Pattern without Switch & If / Else
There are 3 main classes
1) Factory class
– it will import the shape class files in the folder /shapes
– instantiate the object based on shape type
2) Shape abstract class
– abstract method of getType()
3) Shape concrete class
– implement the getType() to tell what type is the shape e.g round
– located in /shapes folder
The concrete class Shape will implement a function to tell it is what kind of Shape.
Factory pattern - class shape
1
2
3
4
5
6
7
8
9
classabstractShape{
publicabstractgetType():string;
}
classRoundextendsShape{
publicgetType():string{
return'round'
}
}
The factory class will import all the shape file path and instantiate the object when call by user class.
factory pattern - dynamic without if else or switch