2017-02-28 24 views
1

我與Web服務請求使用基於傳遞參數,以獲得圖像的工作。我得到的第一個響應是一個帶有文件參考URL的XML模式。顯示TIFF圖像在使用Python不保存Juypyter筆記本/下載

<?xml version="1.0"?> 
<Coverages schemaLocation="http://localhost/server/schemas/wcs/1.1.1/wcsCoverages.xsd"> 
<Coverage> 
    <Title>Filename</Title> 
    <Abstract/> 
    <Identifier>Filename</Identifier> 
    <Reference href="http://localhost/server/temp/filename.tif"/> 
</Coverage> 
</Coverages> 

接下來使用xml.etree.ElementTree我提取了URL。接下來我需要的是dsiplay的Jupyter筆記本電腦,TIFF圖像(或其他圖像),而不下載(作爲一個圖像可以是有時超過50或100 MB)

目前我下載並繪製出文件讀取和文件數據轉換成陣列(如pyplot情節圖像陣列/矩陣)後。

import requests as req # request wcs urls 
import xml.etree.ElementTree as ET # used for xml parsing 
import matplotlib.pyplot as plt # display image 
import gdal 

# Download the File to local directory using Chunks 
    chunk_size=1024 
    local_filename = url.split('/')[-1] # Filename from url 
    r = req.get(url, stream=True) 
    with open(local_filename, 'wb') as f: 
     for chunk in r.iter_content(chunk_size): 
      if chunk: 
       f.write(chunk) 

    # Read File Raster Data as Array using Gdal 
    gtif = gdal.Open(local_filename) 
    georaster = gtif.ReadAsArray() 

    # Plot image using matplotlib 
    plt.imshow(georaster) 
    plt.title(local_filename) 
    plt.show() 

那麼,有沒有辦法將從請求API文件直接插入圖像陣列的原始響應(以塊或整體)和筆記本電腦顯示它(無需下載和本地目錄中取空間)

從TIFF文件GET請求的原始響應低於

resp2 = req.get('tiffFielurl') 
rawdata = resp2.content 
rawdata[0:10] 

Output: b'MM\x00*\x00\x00\x00\x08\x00\x10' 

我試圖尋找這個問題,但沒有發現任何很好的答案,所以如果有任何相關問題,或複製給我提供的鏈接。

+0

可以顯示使用Matplotlib遠程圖像在這個類似的StackOverflow問題概述:【如何繪製(從HTTP URL)的遠程圖像(http://stackoverflow.com/questions/12116050/how -to-積遠程圖像從-HTTP-URL)。 – Brian

+0

@布賴恩好像你已經給正在與「PNG」文件鏈接中提到的解決方案只,我想請求TIFF文件,並得到以下錯誤。 「** ValueError:invalid PNG header **」 –

+0

實際上,在嘗試了許多不同的方法後,我無法找到任何能夠很好地利用來自url的tiff文件(至少在我手中)的東西。您可以嘗試使用io.BytesIO或np.fromstring或np.frombuffer。如果不知道更多關於圖像數據(預期的數據類型和大小)並訪問我可以複製的示例,我將無法進一步幫助您。祝你好運,讓我知道,如果你發現任何工作。 – Brian

回答

0

這樣做大量的研究和嘗試不同的解決方案後,在我看來,做上述步驟即顯示TIFF文件,現在唯一的辦法就是下載和使用@中並轉換成使用matplotlib排列顯示讀取數據。

如在下面的鏈接提到的解決方案僅接受「PNG」文件。

How to plot remote image (from http url)

whcih說到最後,我們需要,我也嘗試和失敗PIL庫。

from PIL import Image 
resp2 = req.get('tiffFielurl') 
resp2.raw.decode_content = True 
im = Image.open(resp2.raw) 
im 

給出輸出:

<PIL.TiffImagePlugin.TiffImageFile image mode=I;16BS size=4800x4800 at 0x11CB7C50> 

和PIL對象轉換爲numpy的陣列或者甚至從PIL對象獲取數據或像素給出無法識別模式錯誤的錯誤。

im.getdata() 
im.getpixels((0,0)) 
numpy.array(im) 

所有給予同樣的錯誤

257   if not self.im or\ 
    258   self.im.mode != self.mode or self.im.size != self.size: 
--> 259    self.im = Image.core.new(self.mode, self.size) 
    260   # create palette (optional) 
    261   if self.mode == "P": 

ValueError: unrecognized mode 

它配備的是PIL甚至不支持在PIL的TIFF文件對象定義上述16位有符號整數像素。

https://pillow.readthedocs.io/en/4.0.x/handbook/concepts.html#concept-modes