Skip to content

Region Growing ​

Region Growing示例。 栅格 regiongrowing MapTiler

在地图上点击一个区域,计算出的区域将显示为红色。

本示例使用 ol/source/Raster 基于另一个数据源生成数据。栅格数据源可以接受任意数量的输入数据源(基于瓦片或图像),并对输入数据运行一系列操作流水线。最后一个操作的返回值将用作输出数据源的数据。

在本例中,使用单个影像数据瓦片源作为输入。区域计算在一个 "image" 操作中完成,使用用户点击地图提供的 "seed"(种子)像素。"threshold"(阈值)值决定某个相邻像素是否属于 "region"(区域)——候选像素的 RGB 值与种子值之差必须小于阈值。

本示例还展示了如何让额外的函数在操作中可用。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import ImageLayer from 'ol/layer/Image.js';
import TileLayer from 'ol/layer/Tile.js';
import {fromLonLat} from 'ol/proj.js';
import ImageTile from 'ol/source/ImageTile.js';
import RasterSource from 'ol/source/Raster.js';

function growRegion(inputs, data) {
  const image = inputs[0];
  let seed = data.pixel;
  const delta = parseInt(data.delta);
  if (!seed) {
    return image;
  }

  seed = seed.map(Math.round);
  const width = image.width;
  const height = image.height;
  const inputData = image.data;
  const outputData = new Uint8ClampedArray(inputData);
  const seedIdx = (seed[1] * width + seed[0]) * 4;
  const seedR = inputData[seedIdx];
  const seedG = inputData[seedIdx + 1];
  const seedB = inputData[seedIdx + 2];
  let edge = [seed];
  while (edge.length) {
    const newedge = [];
    for (let i = 0, ii = edge.length; i < ii; i++) {
      // 正如栅格数据源构造函数中所述,此函数通过
      // `lib` 选项提供。其他函数若未通过 `lib` 选项提供,
      // 则不可见。
      const next = next4Edges(edge[i]);
      for (let j = 0, jj = next.length; j < jj; j++) {
        const s = next[j][0];
        const t = next[j][1];
        if (s >= 0 && s < width && t >= 0 && t < height) {
          const ci = (t * width + s) * 4;
          const cr = inputData[ci];
          const cg = inputData[ci + 1];
          const cb = inputData[ci + 2];
          const ca = inputData[ci + 3];
          // 如果 alpha 为零,则跳过
          if (ca === 0) {
            continue;
          }
          if (
            Math.abs(seedR - cr) < delta &&
            Math.abs(seedG - cg) < delta &&
            Math.abs(seedB - cb) < delta
          ) {
            outputData[ci] = 255;
            outputData[ci + 1] = 0;
            outputData[ci + 2] = 0;
            outputData[ci + 3] = 255;
            newedge.push([s, t]);
          }
          // 标记为已访问
          inputData[ci + 3] = 0;
        }
      }
    }
    edge = newedge;
  }
  return {data: outputData, width: width, height: height};
}

function next4Edges(edge) {
  const x = edge[0];
  const y = edge[1];
  return [
    [x + 1, y],
    [x - 1, y],
    [x, y + 1],
    [x, y - 1],
  ];
}

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 imagery = new TileLayer({
  source: new ImageTile({
    attributions: attributions,
    url: 'https://api.maptiler.com/maps/satellite/{z}/{x}/{y}.jpg?key=' + key,
    tileSize: 512,
    maxZoom: 20,
  }),
});

const raster = new RasterSource({
  sources: [imagery.getSource()],
  operationType: 'image',
  operation: growRegion,
  // `lib` 对象中的函数将对在
  // web worker 中运行的操作可用。
  lib: {
    next4Edges: next4Edges,
  },
});

const rasterImage = new ImageLayer({
  opacity: 0.7,
  source: raster,
});

const map = new Map({
  layers: [imagery, rasterImage],
  target: 'map',
  view: new View({
    center: fromLonLat([-119.07, 47.65]),
    zoom: 11,
  }),
});

let coordinate;

map.on('click', function (event) {
  coordinate = event.coordinate;
  raster.changed();
});

const thresholdControl = document.getElementById('threshold');

raster.on('beforeoperations', function (event) {
  // event.data 对象将被传递给操作
  const data = event.data;
  data.delta = thresholdControl.value;
  if (coordinate) {
    data.pixel = map.getPixelFromCoordinate(coordinate);
  }
});

function updateControlValue() {
  document.getElementById('threshold-value').innerText = thresholdControl.value;
}
updateControlValue();

thresholdControl.addEventListener('input', function () {
  updateControlValue();
  raster.changed();
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>区域生长</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      .map {
        cursor: pointer;
      }
      #threshold {
        margin: 0 0.6em;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <div>
      <label class="input-group">
        阈值:
        <input id="threshold" type="range" min="1" max="50" value="20">
        <span id="threshold-value"></span>
      </label>
    </div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "region-growing",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}