Skip to content

Instantly share code, notes, and snippets.

@maycuatroi
Last active March 27, 2024 12:17
Show Gist options
  • Save maycuatroi/f60e0a4b93b82c24be5fd1753b814609 to your computer and use it in GitHub Desktop.
Save maycuatroi/f60e0a4b93b82c24be5fd1753b814609 to your computer and use it in GitHub Desktop.
Ứng dụng của toán trong đời sống săn sale
import numpy as np
def compute_perspective_transform_matrix(src_points, dst_points):
assert src_points.shape == dst_points.shape == (4, 2), "Cần có 4 điểm trong mỗi mảng"
# Xây dựng ma trận A
A = []
for i in range(4):
x, y = src_points[i][0], src_points[i][1]
x_prime, y_prime = dst_points[i][0], dst_points[i][1]
A.append([x, y, 1, 0, 0, 0, -x_prime * x, -x_prime * y, -x_prime])
A.append([0, 0, 0, x, y, 1, -y_prime * x, -y_prime * y, -y_prime])
A = np.array(A)
# Giải phương trình AX = B
U, S, Vh = np.linalg.svd(A)
M = Vh[-1, :].reshape(3, 3)
return M
def warp_perspective_point(point, M):
point_homogeneous = np.array([point[0], point[1], 1]).reshape(-1, 1)
transformed_point_homogeneous = np.dot(M, point_homogeneous)
transformed_point = transformed_point_homogeneous / transformed_point_homogeneous[2]
x_prime, y_prime = transformed_point[0, 0], transformed_point[1, 0]
return x_prime, y_prime
# Download from: https://www.omelet.tech/content/images/2024/03/image-13.png
path = r"tiktok_screen.png"
rects = [[213, 640], [1037, 594], [1109, 780], [185, 860]]
src_points = np.array(rects, dtype=np.float32)
length_x = 45
length_y = 14.3
x, y = 0, 0
d_point_1 = [x, y, 1]
d_point_2 = [x + length_x, y, 1]
d_point_3 = [x + length_x, y + length_y, 1]
d_point_4 = [x, y + length_y, 1]
points = np.array([d_point_1, d_point_2, d_point_3, d_point_4], dtype=np.float32)
dst_points = np.array(points, dtype=np.float32)
M = compute_perspective_transform_matrix(src_points, dst_points)
start_point_before = [544, 591]
end_point_before = [563, 1688]
start_point = np.array([start_point_before[0], start_point_before[1], 1])
end_point = np.array([end_point_before[0], end_point_before[1], 1])
start_point = warp_perspective_point(start_point, M)
end_point = warp_perspective_point(end_point, M)
print(start_point)
print(end_point)
res = np.linalg.norm(np.array(start_point) - np.array(end_point))
print(res, 'cm')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment