返回介绍

栅格资源

发布于 2022-11-30 23:36:05 字数 9192 浏览 0 评论 0 收藏 0

本示例演示栅格资源的像素级操作。

本示例演示使用 ol/source/Raster 来基于其他资源生产数据。 栅格资源可以接受任意数量的输入资源(基于瓦片或者图像),并且在输入像素上运行一系列操作。 最后操作的返回值作用于输出资源的数据。

在本示例中,使用单一瓦片图像的资源作为输入。 对于每个像素,根据输入像素计算植被绿色指数(VGI)。 第二个操作基于阈值为这些像素着色(阈值以上的值为绿色,阈值以下的值为透明)。

main.js

import 'ol/ol.css';
import Map from 'ol/Map';
import RasterSource from 'ol/source/Raster';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ';
import {Image as ImageLayer, Tile as TileLayer} from 'ol/layer';

const minVgi = 0;
const maxVgi = 0.5;
const bins = 10;

/**
 * Calculate the Vegetation Greenness Index (VGI) from an input pixel.  This
 * is a rough estimate assuming that pixel values correspond to reflectance.
 * @param {Array<number>} pixel An array of [R, G, B, A] values.
 * @return {number} The VGI value for the given pixel.
 */
function vgi(pixel) {
  const r = pixel[0] / 255;
  const g = pixel[1] / 255;
  const b = pixel[2] / 255;
  return (2 * g - r - b) / (2 * g + r + b);
}

/**
 * Summarize values for a histogram.
 * @param {numver} value A VGI value.
 * @param {Object} counts An object for keeping track of VGI counts.
 */
function summarize(value, counts) {
  const min = counts.min;
  const max = counts.max;
  const num = counts.values.length;
  if (value < min) {
    // do nothing
  } else if (value >= max) {
    counts.values[num - 1] += 1;
  } else {
    const index = Math.floor((value - min) / counts.delta);
    counts.values[index] += 1;
  }
}

/**
 * Use aerial imagery as the input data for the raster source.
 */

const key = 'Get your own API key at https://www.maptiler.com/cloud/';
const attributions =
  '<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ' +
  '<a href="https://www.openstreetmap.org/copyright" target="_blank">&copy; OpenStreetMap contributors</a>';

const aerial = new XYZ({
  attributions: attributions,
  url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
  maxZoom: 20,
  crossOrigin: '',
});

/**
 * Create a raster source where pixels with VGI values above a threshold will
 * be colored green.
 */
const raster = new RasterSource({
  sources: [aerial],
  /**
   * Run calculations on pixel data.
   * @param {Array} pixels List of pixels (one per source).
   * @param {Object} data User data object.
   * @return {Array} The output pixel.
   */
  operation: function (pixels, data) {
    const pixel = pixels[0];
    const value = vgi(pixel);
    summarize(value, data.counts);
    if (value >= data.threshold) {
      pixel[0] = 0;
      pixel[1] = 255;
      pixel[2] = 0;
      pixel[3] = 128;
    } else {
      pixel[3] = 0;
    }
    return pixel;
  },
  lib: {
    vgi: vgi,
    summarize: summarize,
  },
});
raster.set('threshold', 0.25);

function createCounts(min, max, num) {
  const values = new Array(num);
  for (let i = 0; i < num; ++i) {
    values[i] = 0;
  }
  return {
    min: min,
    max: max,
    values: values,
    delta: (max - min) / num,
  };
}

raster.on('beforeoperations', function (event) {
  event.data.counts = createCounts(minVgi, maxVgi, bins);
  event.data.threshold = raster.get('threshold');
});

raster.on('afteroperations', function (event) {
  schedulePlot(event.resolution, event.data.counts, event.data.threshold);
});

const map = new Map({
  layers: [
    new TileLayer({
      source: aerial,
    }),
    new ImageLayer({
      source: raster,
    }),
  ],
  target: 'map',
  view: new View({
    center: [-9651695, 4937351],
    zoom: 13,
    minZoom: 12,
    maxZoom: 19,
  }),
});

let timer = null;
function schedulePlot(resolution, counts, threshold) {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  timer = setTimeout(plot.bind(null, resolution, counts, threshold), 1000 / 60);
}

const barWidth = 15;
const plotHeight = 150;
const chart = d3
  .select('#plot')
  .append('svg')
  .attr('width', barWidth * bins)
  .attr('height', plotHeight);

const chartRect = chart.node().getBoundingClientRect();

const tip = d3.select(document.body).append('div').attr('class', 'tip');

function plot(resolution, counts, threshold) {
  const yScale = d3
    .scaleLinear()
    .domain([0, d3.max(counts.values)])
    .range([0, plotHeight]);

  const bar = chart.selectAll('rect').data(counts.values);

  bar.enter().append('rect');

  bar
    .attr('class', function (count, index) {
      const value = counts.min + index * counts.delta;
      return 'bar' + (value >= threshold ? ' selected' : '');
    })
    .attr('width', barWidth - 2);

  bar
    .transition()
    .attr('transform', function (value, index) {
      return (
        'translate(' +
        index * barWidth +
        ', ' +
        (plotHeight - yScale(value)) +
        ')'
      );
    })
    .attr('height', yScale);

  bar.on('mousemove', function () {
    const index = bar.nodes().indexOf(this);
    const threshold = counts.min + index * counts.delta;
    if (raster.get('threshold') !== threshold) {
      raster.set('threshold', threshold);
      raster.changed();
    }
  });

  bar.on('mouseover', function (event) {
    const index = bar.nodes().indexOf(this);
    let area = 0;
    for (let i = counts.values.length - 1; i >= index; --i) {
      area += resolution * resolution * counts.values[i];
    }
    tip.html(message(counts.min + index * counts.delta, area));
    tip.style('display', 'block');
    tip
      .transition()
      .style('left', chartRect.left + index * barWidth + barWidth / 2 + 'px')
      .style('top', event.y - 60 + 'px')
      .style('opacity', 1);
  });

  bar.on('mouseout', function () {
    tip
      .transition()
      .style('opacity', 0)
      .on('end', function () {
        tip.style('display', 'none');
      });
  });
}

function message(value, area) {
  const acres = (area / 4046.86)
    .toFixed(0)
    .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  return acres + ' acres at<br>' + value.toFixed(2) + ' VGI or above';
}

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Raster Source</title>
    <!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
    <script src="https://unpkg.com/elm-pep"></script>
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="./resources/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL,TextDecoder,Number.isInteger"></script>
    <script src="https://unpkg.com/d3@6.7.0/dist/d3.min.js"></script>
    <style>
      .map {
        width: 100%;
        height:400px;
      }
      .rel {
        position: relative
      }

      #plot {
        pointer-events: none;
        position: absolute;
        bottom: 10px;
        left: 10px;
      }

      .bar {
        pointer-events: auto;
        fill: #AFAFB9;
      }

      .bar.selected {
        fill: green;
      }

      .tip {
        position: absolute;
        background: black;
        color: white;
        padding: 6px;
        font-size: 12px;
        border-radius: 4px;
        margin-bottom: 10px;
        display: none;
        opacity: 0;
      }
    </style>
  </head>
  <body>
    <div class="rel">
      <div id="map" class="map"></div>
      <div id="plot"></div>
    </div>
    <script src="main.js"></script>
  </body>
</html>

package.json

{
  "name": "raster",
  "dependencies": {
    "ol": "7.1.0"
  },
  "devDependencies": {
    "parcel": "^2.0.0-beta.1"
  },
  "scripts": {
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文