gst-test-perspective.py: add an example about a rotation transform
[experiments/gstreamer.git] / python / gst-test-perspective.py
1 #!/usr/bin/env python
2
3 # test program for the "perspective" geometric transform element
4
5 import cv2
6 import numpy as np
7 from math import cos, sin, radians
8
9 import gi
10 gi.require_version('Gst', '1.0')
11 from gi.repository import Gst
12 Gst.init(None)
13
14 from gi.repository import GObject
15 GObject.threads_init()
16
17
18 def calc_matrix():
19     top_x_shift = 200
20
21     width, height = 800, 480
22     corners = np.array([(0, 0), (width, 0), (width, height), (0, height)], dtype=np.float32)
23     target = np.array([(top_x_shift, 0), (width - top_x_shift, 0), (width, height), (0, height)], dtype=np.float32)
24
25     mat = cv2.getPerspectiveTransform(corners, target)
26     ret, inv_mat = cv2.invert(mat)
27
28     return inv_mat.flatten()
29
30
31 def calc_rotation_matrix():
32     width, height = 800, 480
33
34     pivot = (width / 2, height / 2)
35     angle = 10
36     theta = radians(angle)
37
38     # The dimensions of the bounding box of the rotated rectangle
39     W = width * abs(cos(theta)) + height * abs(sin(theta))
40     H = width * abs(sin(theta)) + height * abs(cos(theta))
41
42     scale_factor = 1 / min(width / W, height / H)
43
44     mat = cv2.getRotationMatrix2D(pivot, angle, scale_factor)
45     mat = np.vstack([mat, [0, 0, 1]])
46
47     return mat.flatten()
48
49
50 def main():
51     pipeline = Gst.ElementFactory.make('pipeline', None)
52
53     videosrc = Gst.ElementFactory.make('videotestsrc', None)
54     pipeline.add(videosrc)
55
56     # Test the perspective element
57     perspective = Gst.ElementFactory.make("perspective", None)
58     pipeline.add(perspective)
59
60     print perspective.get_property("matrix")
61
62     M = calc_rotation_matrix()
63     perspective.set_property("matrix", M)
64     print perspective.get_property("matrix")
65
66     # This should fail!
67     perspective.set_property("matrix", [0])
68     print perspective.get_property("matrix")
69
70     videoconvert = Gst.ElementFactory.make("autovideoconvert", None)
71     pipeline.add(videoconvert)
72
73     videosink = Gst.ElementFactory.make("autovideosink", None)
74     pipeline.add(videosink)
75
76     caps = Gst.caps_from_string(
77         "video/x-raw,format=\"AYUV\",width=800,height=480")
78
79     videosrc.link_filtered(perspective, caps)
80     perspective.link(videoconvert)
81     videoconvert.link(videosink)
82
83     pipeline.set_state(Gst.State.PLAYING)
84
85     loop = GObject.MainLoop()
86     loop.run()
87
88
89 if __name__ == '__main__':
90     main()