Объявление : Все некоммерческие проекты, зарегистрированные для использования Earth Engine до
15 апреля 2025 года, должны
подтвердить право на некоммерческое использование для сохранения доступа. Если вы не подтвердите право до 26 сентября 2025 года, ваш доступ может быть приостановлен.
ee.Image.sample
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Выбирает пиксели изображения, возвращая их как FeatureCollection. Каждый объект будет иметь одно свойство на полосу входного изображения. Обратите внимание, что поведение по умолчанию — отбрасывать объекты, пересекающие замаскированные пиксели, что приводит к появлению свойств со значениями NULL (см. аргумент dropNulls).
Использование | Возврат | Image. sample ( region , scale , projection , factor , numPixels , seed , dropNulls , tileScale , geometries ) | FeatureCollection |
Аргумент | Тип | Подробности | это: image | Изображение | Изображение для выборки. |
region | Геометрия, по умолчанию: null | Регион, из которого будет взята выборка. Если не указано иное, используется весь контур изображения. |
scale | Плавающий, по умолчанию: null | Номинальный масштаб в метрах проекции для взятия образца. |
projection | Проекция, по умолчанию: null | Проекция, в которой будет производиться выборка. Если не указано, используется проекция первой полосы изображения. Если указано в дополнение к масштабу, масштаб изменяется до указанного. |
factor | Плавающий, по умолчанию: null | Коэффициент подвыборки в пределах (0, 1]. Если указан, то «numPixels» указывать не нужно. По умолчанию подвыборка не применяется. |
numPixels | Длинный, по умолчанию: null | Примерное количество пикселей для выборки. Если указано, «фактор» указывать не нужно. |
seed | Целое число, по умолчанию: 0 | Начальное число рандомизации, используемое для подвыборки. |
dropNulls | Логическое значение, по умолчанию: true | Примените фильтр к результату, чтобы исключить объекты, имеющие нулевые свойства. |
tileScale | Плавающий, по умолчанию: 1 | Коэффициент масштабирования, используемый для уменьшения размера плитки агрегации; использование большего значения tileScale (например, 2 или 4) может разрешить вычисления, для которых при использовании значений по умолчанию закончится память. |
geometries | Логическое значение, по умолчанию: false | Если значение равно true, добавляет центр выбранного пикселя в качестве геометрического свойства выходного объекта. В противном случае геометрия будет опущена (экономия памяти). |
Примеры
Редактор кода (JavaScript)
// Demonstrate extracting pixels from an image as features with
// ee.Image.sample(), and show how the features are aligned with the pixels.
// An image with one band of elevation data.
var image = ee.Image('CGIAR/SRTM90_V4');
var VIS_MIN = 1620;
var VIS_MAX = 1650;
Map.addLayer(image, {min: VIS_MIN, max: VIS_MAX}, 'SRTM');
// Region to sample.
var region = ee.Geometry.Polygon(
[[[-110.006, 40.002],
[-110.006, 39.999],
[-109.995, 39.999],
[-109.995, 40.002]]], null, false);
// Show region on the map.
Map.setCenter(-110, 40, 16);
Map.addLayer(ee.FeatureCollection([region]).style({"color": "00FF0022"}));
// Perform sampling; convert image pixels to features.
var samples = image.sample({
region: region,
// Default (false) is no geometries in the output.
// When set to true, each feature has a Point geometry at the center of the
// image pixel.
geometries: true,
// The scale is not specified, so the resolution of the image will be used,
// and there is a feature for every pixel. If we give a scale parameter, the
// image will be resampled and there will be more or fewer features.
//
// scale: 200,
});
// Visualize sample data using ee.FeatureCollection.style().
var styled = samples
.map(function (feature) {
return feature.set('style', {
pointSize: feature.getNumber('elevation').unitScale(VIS_MIN, VIS_MAX)
.multiply(15),
});
})
.style({
color: '000000FF',
fillColor: '00000000',
styleProperty: 'style',
neighborhood: 6, // increase to correctly draw large points
});
Map.addLayer(styled);
// Each sample feature has a point geometry and a property named 'elevation'
// corresponding to the band named 'elevation' of the image. If there are
// multiple bands they will become multiple properties. This will print:
//
// geometry: Point (-110.01, 40.00)
// properties:
// elevation: 1639
print(samples.first());
Настройка Python
Информацию об API Python и использовании geemap
для интерактивной разработки см. на странице «Среда Python» .
import ee
import geemap.core as geemap
Colab (Python)
# Demonstrate extracting pixels from an image as features with
# ee.Image.sample(), and show how the features are aligned with the pixels.
# An image with one band of elevation data.
image = ee.Image('CGIAR/SRTM90_V4')
vis_min = 1620
vis_max = 1650
m = geemap.Map()
m.add_layer(image, {'min': vis_min, 'max': vis_max}, 'SRTM')
# Region to sample.
region = ee.Geometry.Polygon(
[[
[-110.006, 40.002],
[-110.006, 39.999],
[-109.995, 39.999],
[-109.995, 40.002],
]],
None,
False,
)
# Show region on the map.
m.set_center(-110, 40, 16)
m.add_layer(ee.FeatureCollection([region]).style(color='00FF0022'))
# Perform sampling convert image pixels to features.
samples = image.sample(
region=region,
# Default (False) is no geometries in the output.
# When set to True, each feature has a Point geometry at the center of the
# image pixel.
geometries=True,
# The scale is not specified, so the resolution of the image will be used,
# and there is a feature for every pixel. If we give a scale parameter, the
# image will be resampled and there will be more or fewer features.
#
# scale=200,
)
def scale_point_size(feature):
elevation = feature.getNumber('elevation')
point_size = elevation.unitScale(vis_min, vis_max).multiply(15)
feature.set('style', {'pointSize': point_size})
return feature
# Visualize sample data using ee.FeatureCollection.style().
styled = samples.map(scale_point_size).style(
color='000000FF',
fillColor='00000000',
styleProperty='style',
neighborhood=6, # increase to correctly draw large points
)
m.add_layer(styled)
display(m)
# Each sample feature has a point geometry and a property named 'elevation'
# corresponding to the band named 'elevation' of the image. If there are
# multiple bands they will become multiple properties. This will print:
#
# geometry: Point (-110.01, 40.00)
# properties:
# elevation: 1639
display(samples.first())
,Выбирает пиксели изображения, возвращая их как FeatureCollection. Каждый объект будет иметь одно свойство на полосу входного изображения. Обратите внимание, что поведение по умолчанию — отбрасывать объекты, пересекающие замаскированные пиксели, что приводит к появлению свойств со значениями NULL (см. аргумент dropNulls).
Использование | Возврат | Image. sample ( region , scale , projection , factor , numPixels , seed , dropNulls , tileScale , geometries ) | FeatureCollection |
Аргумент | Тип | Подробности | это: image | Изображение | Изображение для выборки. |
region | Геометрия, по умолчанию: null | Регион, из которого будет взята выборка. Если не указано иное, используется весь контур изображения. |
scale | Плавающий, по умолчанию: null | Номинальный масштаб в метрах проекции для взятия образца. |
projection | Проекция, по умолчанию: null | Проекция, в которой будет производиться выборка. Если не указано, используется проекция первой полосы изображения. Если указано в дополнение к масштабу, масштаб изменяется до указанного. |
factor | Плавающий, по умолчанию: null | Коэффициент подвыборки в пределах (0, 1]. Если указан, то «numPixels» указывать не нужно. По умолчанию подвыборка не применяется. |
numPixels | Длинный, по умолчанию: null | Примерное количество пикселей для выборки. Если указано, «фактор» указывать не нужно. |
seed | Целое число, по умолчанию: 0 | Начальное число рандомизации, используемое для подвыборки. |
dropNulls | Логическое значение, по умолчанию: true | Примените фильтр к результату, чтобы исключить объекты, имеющие нулевые свойства. |
tileScale | Плавающий, по умолчанию: 1 | Коэффициент масштабирования, используемый для уменьшения размера плитки агрегации; использование большего значения tileScale (например, 2 или 4) может разрешить вычисления, для которых при использовании значений по умолчанию закончится память. |
geometries | Логическое значение, по умолчанию: false | Если значение равно true, добавляет центр выбранного пикселя в качестве геометрического свойства выходного объекта. В противном случае геометрия будет опущена (экономия памяти). |
Примеры
Редактор кода (JavaScript)
// Demonstrate extracting pixels from an image as features with
// ee.Image.sample(), and show how the features are aligned with the pixels.
// An image with one band of elevation data.
var image = ee.Image('CGIAR/SRTM90_V4');
var VIS_MIN = 1620;
var VIS_MAX = 1650;
Map.addLayer(image, {min: VIS_MIN, max: VIS_MAX}, 'SRTM');
// Region to sample.
var region = ee.Geometry.Polygon(
[[[-110.006, 40.002],
[-110.006, 39.999],
[-109.995, 39.999],
[-109.995, 40.002]]], null, false);
// Show region on the map.
Map.setCenter(-110, 40, 16);
Map.addLayer(ee.FeatureCollection([region]).style({"color": "00FF0022"}));
// Perform sampling; convert image pixels to features.
var samples = image.sample({
region: region,
// Default (false) is no geometries in the output.
// When set to true, each feature has a Point geometry at the center of the
// image pixel.
geometries: true,
// The scale is not specified, so the resolution of the image will be used,
// and there is a feature for every pixel. If we give a scale parameter, the
// image will be resampled and there will be more or fewer features.
//
// scale: 200,
});
// Visualize sample data using ee.FeatureCollection.style().
var styled = samples
.map(function (feature) {
return feature.set('style', {
pointSize: feature.getNumber('elevation').unitScale(VIS_MIN, VIS_MAX)
.multiply(15),
});
})
.style({
color: '000000FF',
fillColor: '00000000',
styleProperty: 'style',
neighborhood: 6, // increase to correctly draw large points
});
Map.addLayer(styled);
// Each sample feature has a point geometry and a property named 'elevation'
// corresponding to the band named 'elevation' of the image. If there are
// multiple bands they will become multiple properties. This will print:
//
// geometry: Point (-110.01, 40.00)
// properties:
// elevation: 1639
print(samples.first());
Настройка Python
Информацию об API Python и использовании geemap
для интерактивной разработки см. на странице «Среда Python» .
import ee
import geemap.core as geemap
Colab (Python)
# Demonstrate extracting pixels from an image as features with
# ee.Image.sample(), and show how the features are aligned with the pixels.
# An image with one band of elevation data.
image = ee.Image('CGIAR/SRTM90_V4')
vis_min = 1620
vis_max = 1650
m = geemap.Map()
m.add_layer(image, {'min': vis_min, 'max': vis_max}, 'SRTM')
# Region to sample.
region = ee.Geometry.Polygon(
[[
[-110.006, 40.002],
[-110.006, 39.999],
[-109.995, 39.999],
[-109.995, 40.002],
]],
None,
False,
)
# Show region on the map.
m.set_center(-110, 40, 16)
m.add_layer(ee.FeatureCollection([region]).style(color='00FF0022'))
# Perform sampling convert image pixels to features.
samples = image.sample(
region=region,
# Default (False) is no geometries in the output.
# When set to True, each feature has a Point geometry at the center of the
# image pixel.
geometries=True,
# The scale is not specified, so the resolution of the image will be used,
# and there is a feature for every pixel. If we give a scale parameter, the
# image will be resampled and there will be more or fewer features.
#
# scale=200,
)
def scale_point_size(feature):
elevation = feature.getNumber('elevation')
point_size = elevation.unitScale(vis_min, vis_max).multiply(15)
feature.set('style', {'pointSize': point_size})
return feature
# Visualize sample data using ee.FeatureCollection.style().
styled = samples.map(scale_point_size).style(
color='000000FF',
fillColor='00000000',
styleProperty='style',
neighborhood=6, # increase to correctly draw large points
)
m.add_layer(styled)
display(m)
# Each sample feature has a point geometry and a property named 'elevation'
# corresponding to the band named 'elevation' of the image. If there are
# multiple bands they will become multiple properties. This will print:
#
# geometry: Point (-110.01, 40.00)
# properties:
# elevation: 1639
display(samples.first())
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-24 UTC.
[null,null,["Последнее обновление: 2025-07-24 UTC."],[],[]]