1 | import numpy as np
|
2 | import cv2
|
3 | from time import clock
|
4 |
|
5 |
|
6 | x, y = np.mgrid[-5:5, -5:5]
|
7 | z = np.ones_like(x)
|
8 | p3d_1 = np.float32(np.dstack([x, y, z*40]).reshape(-1, 3))
|
9 | p3d_2 = np.float32(np.dstack([x, y, z*50]).reshape(-1, 3))
|
10 | p3d = np.vstack([p3d_1, p3d_2])
|
11 |
|
12 |
|
13 | w, h = 640, 480
|
14 | f = 1280.0
|
15 | K = np.diag([f, f, 1.0])
|
16 | K[:2, 2] = 0.5*w, 0.5*h
|
17 |
|
18 |
|
19 | def render(p, color):
|
20 | img = np.zeros((h, w, 3), np.uint8)
|
21 | n = len(p)/2
|
22 | for (x1, y1), (x2, y2) in np.int32(zip(p[:n], p[n:])):
|
23 | cv2.line(img, (x1, y1), (x2, y2), color, 2, cv2.CV_AA)
|
24 | return img
|
25 |
|
26 |
|
27 | z3 = np.zeros(3)
|
28 | p1 = cv2.projectPoints(p3d, z3, z3, K, np.zeros(4))[0].reshape(-1, 2)
|
29 | cv2.imshow("camera1", render(p1, (0, 0, 255)))
|
30 |
|
31 | while True:
|
32 |
|
33 | t = clock()*0.5
|
34 | tvec = np.float64([np.cos(t), np.sin(t), 0.0])*2
|
35 | p2 = cv2.projectPoints(p3d, z3, tvec, K, np.zeros(4))[0].reshape(-1, 2)
|
36 | img2 = render(p2, (128, 128, 0))
|
37 |
|
38 |
|
39 | F, _ = cv2.findFundamentalMat(p1, p2, cv2.FM_8POINT)
|
40 | ret, H1, H2 = cv2.stereoRectifyUncalibrated(p1.reshape(1, -1, 2), p2.reshape(1, -1, 2), F, (w, h))
|
41 |
|
42 |
|
43 | p1t = cv2.perspectiveTransform(p1.reshape(1, -1, 2), H1).reshape(-1, 2)
|
44 | p2t = cv2.perspectiveTransform(p2.reshape(1, -1, 2), H2).reshape(-1, 2)
|
45 | img1t = render(p1t, (0, 0, 255))
|
46 | img2t = render(p2t, (128, 128, 0))
|
47 | rectified = cv2.addWeighted(img1t, 1.0, img2t, 1.0, 0.0)
|
48 |
|
49 | cv2.imshow("rectified", rectified)
|
50 | cv2.imshow("camera2", img2)
|
51 | ch = cv2.waitKey(10)
|
52 | if ch == 27:
|
53 | break
|