這可能是一個奇怪的,但我有一個像這樣的三角形圖形:

在測量平臺中,每當單擊此圖形中的某個點時,都會像這樣記錄以像素為單位的 x,y 坐標(x,y 的原點來自影像的左上角)
注意:只允許在綠色三角形內點擊。

有沒有辦法將這些坐標轉換為相對于二維單純形(這個三角形)的重心坐標(x,y,z)?
如果是這樣,考慮到我們有 x,y 以像素為單位的適當方程是什么。
它們是像素還是仍然被認為是笛卡爾坐標有關系嗎?
謝謝!
uj5u.com熱心網友回復:
所以你知道三角形三個頂點的坐標
A: {ax, ay}
B: {bx, by}
C: {cx, cy}
你想取任意一點
P: {px, py}
并找到三個重心坐標w_A, w_B,w_C使得
px = w_A * ax w_B * bx w_C * cx
py = w_A * ay w_B * by w_C * cy
1 = w_A w_B w_C
把它變成一個線性代數問題
| px | | ax bx cx | | w_A |
| py | = | ay by cy | | w_B |
| 1 | | 1 1 1 | | w_C |
待解決{w_A,w_B,w_C}
使用下面的示例代碼,我測驗了以下結果
Triangle A: <5, 0>
Triangle B: <2.5, 5>
Triangle C: <0, 0>
Random Point: <3.169941, 0.417091>
Barycentric: (0.5922791,0.08341819,0.3243028)
Target Point: <3.169941, 0.417091>
三角形.cs
using System.Numerics;
namespace ConsoleApp2
{
public class Triangle
{
public Triangle(Vector2 a, Vector2 b, Vector2 c)
{
A = a;
B = b;
C = c;
}
public Vector2 A { get; set; }
public Vector2 B { get; set; }
public Vector2 C { get; set; }
public Vector2 GetPoint(float w_A, float w_B, float w_C) => GetPoint((w_A, w_B, w_C));
public Vector2 GetPoint((float w_A, float w_B, float w_C) coord)
{
return coord.w_A * A coord.w_B * B coord.w_C * C;
}
public (float w_A, float w_B, float w_C) GetBarycentric(Vector2 P)
{
float D = A.X * (B.Y - C.X) A.Y * (B.X - C.X) B.X * C.Y - B.Y * C.X;
float w_A = ((B.Y - C.Y) * P.X (C.X - B.X) * P.Y (B.X * C.Y - B.Y * C.X)) / D;
float w_B = ((C.Y - A.Y) * P.X (A.X - C.X) * P.Y (C.X * A.Y - C.Y * A.X)) / D;
float w_C = ((A.Y - B.Y) * P.X (B.X - A.X) * P.Y (A.X * B.Y - A.Y * B.X)) / D;
return (w_A, w_B, w_C);
}
public bool Contains(Vector2 point)
{
var (w_A, w_B, w_C) = GetBarycentric(point);
return w_A>=0 && w_A<=1
&& w_B>=0 && w_B<=1
&& w_C>=0 && w_C<=1;
}
}
}
程式.cs
using System;
using System.Numerics;
namespace ConsoleApp2
{
public static class Program
{
static readonly Random rng = new Random();
static Vector2 RandomVector(float minValue = 0, float maxValue = 1)
{
return new Vector2(
minValue (maxValue - minValue) * (float)rng.NextDouble(),
minValue (maxValue - minValue) * (float)rng.NextDouble());
}
static void Main(string[] args)
{
Vector2 A = new Vector2(5f,0f);
Vector2 B = new Vector2(2.5f,5f);
Vector2 C = new Vector2(0f,0f);
var triangle = new Triangle(A, B, C);
Console.WriteLine($"Triangle A: {A}");
Console.WriteLine($"Triangle B: {B}");
Console.WriteLine($"Triangle C: {C}");
Vector2 P = RandomVector(0f, 5f);
Console.WriteLine($"Random Point: {P}");
var (w_A, w_B, w_C) = triangle.GetBarycentric(P);
Console.WriteLine($"Barycentric: ({w_A},{w_B},{w_C})");
Vector2 T = triangle.GetPoint(w_A, w_B, w_C);
Console.WriteLine($"Target Point: {T}");
}
}
}
uj5u.com熱心網友回復:
像素只是特定的單位,這個三角形表示仍然是笛卡爾坐標,所以你只需應用相同的公式,即(如注釋中指定)這個
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441738.html
上一篇:如何使用javascript在React中限制將數字的最大小數位設定為8位小數
下一篇:N個自然數列中的特殊對
