从USGS网站,使用python下载landsat影像,可以批量,修改版

这篇文章是在利用Python下载Landsat数据_孤城_001的博客-CSDN博客_python下载landsat的基础上完成的,但是可能因为种种原因,目前它的方法已经不能使用,需要修改安装包中的部分语句。

1,首先安装第三方包

pip install landsatxplore

2,修改包的内容

修改下面的函数,在EarthExplorer.py文件中。我主要删除了所有与 ncform 相关的东西,因为目前EarthExplorer删除了该部分内容。下面的代码,直接替换原来的文件就行。

class EarthExplorer(object):
    """Access Earth Explorer portal."""

    def __init__(self, username, password):
        """Access Earth Explorer portal."""
        self.session = requests.Session()
        self.login(username, password)
        self.api = API(username, password)

    def logged_in(self):
        """Check if the log-in has been successfull based on session cookies."""
        eros_sso = self.session.cookies.get("EROS_SSO_production_secure")
        return bool(eros_sso)

    def login(self, username, password):
        """Login to Earth Explorer."""
        rsp = self.session.get(EE_LOGIN_URL)
        csrf = _get_tokens(rsp.text)

        payload = {
            "username": username,
            "password": password,
            "csrf": csrf,
        }
        rsp = self.session.post(EE_LOGIN_URL, data=payload, allow_redirects=True)

        if not self.logged_in():
            raise EarthExplorerError("EE: login failed.")

    def logout(self):
        """Log out from Earth Explorer."""
        self.session.get(EE_LOGOUT_URL)

    def _download(self, url, output_dir, timeout, chunk_size=1024, skip=False):
        """Download remote file given its URL."""
        # Check availability of the requested product
        # EarthExplorer should respond with JSON
        with self.session.get(
            url, allow_redirects=False, stream=True, timeout=timeout
        ) as r:
            r.raise_for_status()
            error_msg = r.json().get("errorMessage")
            if error_msg:
                raise EarthExplorerError(error_msg)
            download_url = r.json().get("url")

        try:
            with self.session.get(
                download_url, stream=True, allow_redirects=True, timeout=timeout
            ) as r:
                file_size = int(r.headers.get("Content-Length"))
                with tqdm(
                    total=file_size, unit_scale=True, unit="B", unit_divisor=1024
                ) as pbar:
                    local_filename = r.headers["Content-Disposition"].split("=")[-1]
                    local_filename = local_filename.replace('"', "")
                    local_filename = os.path.join(output_dir, local_filename)
                    if skip:
                        return local_filename
                    with open(local_filename, "wb") as f:
                        for chunk in r.iter_content(chunk_size=chunk_size):
                            if chunk:
                                f.write(chunk)
                                pbar.update(chunk_size)
        except requests.exceptions.Timeout:
            raise EarthExplorerError(
                "Connection timeout after {} seconds.".format(timeout)
            )
        return local_filename

    def download(self, identifier, output_dir, dataset=None, timeout=300, skip=False):
        """Download a Landsat scene.

        Parameters
        ----------
        identifier : str
            Scene Entity ID or Display ID.
        output_dir : str
            Output directory. Automatically created if it does not exist.
        dataset : str, optional
            Dataset name. If not provided, automatically guessed from scene id.
        timeout : int, optional
            Connection timeout in seconds.
        skip : bool, optional
            Skip download, only returns the remote filename.

        Returns
        -------
        filename : str
            Path to downloaded file.
        """
        os.makedirs(output_dir, exist_ok=True)
        if not dataset:
            dataset = guess_dataset(identifier)
        if is_display_id(identifier):
            entity_id = self.api.get_entity_id(identifier, dataset)
        else:
            entity_id = identifier
        url = EE_DOWNLOAD_URL.format(
            data_product_id=DATA_PRODUCTS[dataset], entity_id=entity_id
        )
        filename = self._download(url, output_dir, timeout=timeout, skip=skip)
        return filename

3 可以下载了,下面的代码几乎是抄的,我只是稍加注释和修改,稍作说明

import landsatxplore.api
from landsatxplore.earthexplorer import EarthExplorer

def request_Landsat(username,password,product,lat,lon,start_date,end_date,cloud_max):

    api = landsatxplore.api.API(username, password)

    scenes = api.search(
        dataset=product,
        latitude=lat,
        longitude=lon,
        start_date=start_date,
        end_date=end_date,
        max_cloud_cover=cloud_max)

    print('{} scenes found.'.format(len(scenes)))
    api.logout()
    return scenes

def download_landsat(username,password,Landsat_name,output_dir):

    Earth_Down = EarthExplorer(username, password)

    for scene in Landsat_name:

# 下面代码将'entityId'改为'display_id',因为两个id下载名称有差别:
#        'entity_id': 'LC81960462015361LGN01', 
#        'display_id': 'LC08_L1TP_196046_20151227_20170331_01_T1'

        ID = scene['display_id']
        print('Downloading data %s '% ID)
# 下面这行代码将原来的scene_id 改为identifier,因为scene_id已被弃用
        Earth_Down.download(identifier=ID, output_dir=output_dir)

    Earth_Down.logout()

if __name__ == '__main__':

    
    username = ''
    password = ''

#下面所有6行代码,可以建立任意循环,以达到批量下载的目的,不赘述
    product = 'LANDSAT_8_C1'
    lat = 19.53
    lon = -1.53
    start_date='2014-01-01'
    end_date='2016-01-01'
    cloud_max = 10
    output_dir = 'G:\\aa\data'
    Landsat_name = request_Landsat(username,password,product,lat,lon,start_date,end_date,cloud_max)
    print(Landsat_name)

    download_landsat(username,password,Landsat_name,output_dir)

4 尝试了一下,速度喜人

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 25
    评论
### 回答1: 要使用Python下载Landsat数据,我建议使用landsat-util工具。landsat-util是一个用于管理和下载Landsat数据的Python命令行工具。下面是使用landsat-util工具的步骤: 1. 首先,你需要在计算机上安装Pythonlandsat-util包。你可以在Python官方网站下载并安装Python,然后使用pip命令安装landsat-util包。 2. 在命令行中输入`landsat configure`命令,按照提示输入USGS EarthExplorer网站的用户名和密码,以获取访问权限。 3. 使用`landsat search`命令来搜索Landsat数据。你可以根据地理区域、日期范围、云量等条件来筛选数据。 4. 选择符合要求的数据,并使用`landsat download [sceneID]`命令下载数据。sceneID可以在搜索结果中找到。 5. 下载的数据将储存在你所指定的目录中。你可以使用`landsat process`命令对数据进行预处理和校正,例如大气校正、反射率计算等。 使用landsat-util工具,你可以轻松地通过命令行下载和处理Landsat数据,而无需手动搜索和下载。这使得批量下载Landsat数据变得非常方便,并且可以自动化整个流程。 请注意,使用landsat-util下载Landsat数据需要网络连接,并且你需要在USGS EarthExplorer网站上创建一个帐户并允许下载权限。同时,你也应该在搜索和下载数据时遵守相关的数据使用和许可条款。 ### 回答2: Python有多种库和模块可用于下载Landsat卫星图像数据,其中最常用的是提供遥感数据下载功能的地理空间数据处理库,如gdal、geopandas、rasterio等。这些库能够通过代码方式访问和下载Landsat数据。 其中,使用rasterio库可以实现Landsat图像数据的下载。首先,需要在代码中导入rasterio库,并设置Landsat图像数据的下载链接。例如,获取Landsat 8 OLI/TIRS数据的下载链接是通过USGS EarthExplorer网站进行的,可以通过调用rasterio.rio.download函数来进行下载。以下是一个示例代码: ```python import rasterio url = "https://earthexplorer.usgs.gov/download/12864/LC08_L1TP_024032_20200718_20200730_01_T1.tar.gz" rasterio.rio.download(url, "./LC08_L1TP_024032_20200718_20200730_01_T1.tar.gz") ``` 上述代码中,`url`变量设定了数据下载链接,`rasterio.rio.download`函数将数据下载到当前工作目录下,保存为`LC08_L1TP_024032_20200718_20200730_01_T1.tar.gz`文件。 另外,对于需要大规模下载Landsat数据的情况,还可以使用Python的多线程或并行处理库来提高下载速度。常用的有concurrent.futures、multiprocessing等。 总的来说,Python提供了多种库和模块用于Landsat数据的下载,通过调用相应函数和设置下载链接,可以方便地实现Landsat图像数据的获取。为了保证数据下载的可靠性和完整性,建议在下载前仔细阅读相应文档并设置好文件保存路径。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 25
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值