[英]Ease data in array to smooth a curve in PHP
我正在使用API獲取GPX點的高程數據,並嘗試為其創建圖形表示。 我的問題是,API中的每個點之間相隔90米,而我的GPX點之間相距5米,導致連續幾個點具有相同的高度,然后突然更改為新的高度。
基本上,我得到一個像這樣的數組:
[0,0,0,0,0,10,10,10,10,10,15,15,15,15,15,15 ...]
在緩和曲線時,如何將其繪制為海拔的PNG圖像表示形式? 我需要能夠更改輸出圖片的大小。
我正在嘗試將數組更改為類似的格式,但是我不確定該怎么做以及這是否是最佳解決方案:
[0、0、0、0、5、5、10、10、10、12、13、15、15、15、15 ...]
感謝您的提示,我不習慣處理圖片和數據緩動。
這是在“平均”的基礎上平滑點的基本方法:
<?php
$points = [0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15];
$refined = [];
foreach($points as $index => $point) {
// make sure we don't divide by 0
$prev = isset($points[$index - 1]) ? $points[$index - 1] : false;
$next = isset($points[$index + 1]) ? $points[$index + 1] : false;
if($point > 0 || ($prev && $prev > 0) || ($next && $next > 0)) {
$total = $point;
if($prev) {
$total += $prev;
$total = $total / 2;
}
if($next) {
$total += $next;
$total = $total / 2;
}
$refined[] = round($total, 0);
} else {
$refined[] = $point;
}
}
echo implode(" ", $points);
echo "<hr>";
echo implode(" ", $refined);
結果是:
0 0 0 0 0 10 10 10 10 10 15 15 15 15 15
---------------------------------------
0 0 0 0 5 10 10 10 10 13 14 15 15 15 15
為了增加平滑度,您將需要一種更復雜的方法,該方法具有先行,后向和大量采樣的功能……您可能還可以在點之間進行插值,但我在上面的示例中不進行插值。 要進行插值,可以執行以下操作:
<?php
$points = [0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15];
$refined = [];
foreach($points as $index => $point) {
$prev = isset($points[$index - 1]) ? $points[$index - 1] : false;
$next = isset($points[$index + 1]) ? $points[$index + 1] : false;
if($point > 0 || ($prev && $prev > 0) || ($next && $next > 0)) {
$refined[] = $point;
while($next && $point < $next) {
$point++;
$refined[] = $point;
}
} else {
$refined[] = $point;
}
}
echo implode(" ", $points);
echo "<hr>";
echo implode(" ", $refined);
這將產生:
0 0 0 0 0 10 10 10 10 10 15 15 15 15 15
---------------------------------------------------------------------------
0 0 0 0 0 1 2 3 4 5 6 7 8 9 10 10 10 10 10 10 11 12 13 14 15 15 15 15 15 15
要繪制圖像,我們需要更多信息。 數組中的點不是2D ...意味着沒有X或Y,除非我們假設每個點都將X軸增加一個像素? 如果是這樣,這是一個大概的鏡頭:
$width = count($refined);
$height = max($refined);
$gd = imagecreatetruecolor($width, $height);
// Allocate a color
$red = imagecolorallocate($gd, 255, 0, 0);
foreach($refined as $x => $y) {
imagesetpixel($gd, $x, $height-$y, $red);
}
header('Content-Type: image/png');
imagepng($gd);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.