0

processing.org アプリを Python に移植しようとしていますが、いくつか問題があります。

これをPythonで書く必要があります:

int[][] elevation; // elevations in meters
float[][] felevation; // scaled to range [0,1] where 1=max
int maxheight;

void setup(){
size(600,600,P2D);

// read srtm binary file
elevation=new int[1201][1201];
felevation=new float[1201][1201];
byte b[] = loadBytes("N30W091.hgt"); // THIS IS A BINARY FILE
int ix=0;
maxheight=0;
for (int row=0;row<1201;row++) {
  for (int col=0;col<1201;col++) {
    // bytes are signed, from -128 to 127, converts to unsigned...
    int hi = b[ix] & 0xff; 
    int lo = b[ix+1] & 0xff; 
    int el=(int)((hi<<8)|lo); // big endian!
    elevation[row][col]=el;
    if (el>maxheight && el<32000) maxheight=el; 
    ix+=2;
   }
}

... 等々

私がこれまでに作ったのはこれです:

elevation = [[],[]]
maxheight=0

b = open("C:\\Users\\CNA\\sketchbook\\_SRTM\\data\\N59E010.hgt","rb")
fin = b.read(1)
print(len(fin))
ix = 0
for row in range(0,1201):
    for col in range(0,1201):
        hi = (fin[ix]   + 0xff)
        lo = (fin[ix+1] + 0xff)

そして私はいつも得る

Traceback (most recent call last):

  File "C:\Users\CNA\workspace\Revitter\PatternAsignment.py", line 16, in <module>

TypeError: unsupported operand type(s) for +: 'str' and 'int'

何か案は?..私はpythonが初めてで、バイトを扱った経験がありません...

4

3 に答える 3

5

慣用的な翻訳は、まったく異なる方法で機能します。

元のコードでは、一連のビット操作を行って 2 バイト値を 1 つの数値に変換していました。Python には、このための組み込み機能があります:structモジュールを使用します。結局のところ、このモジュールは一度に複数の値を読み取るように既に構築されています。

また、ファイル名にはスラッシュを使用してください。より簡単で、確実に機能します。with-block を使用して、ファイルが自動的に適切に閉じられるようにし、リスト内包表記を使用してループを簡素化します。リストの作成方法を Python に指示するのをやめて、必要なリストを要求してください。

これにより、次のことがわかります。

import struct
with open('C:/Users/CNA/sketchbook/_SRTM/data/N59E010.hgt', 'rb') as data:
    elevation = [
        list(struct.unpack('>1201H', data.read(1201 * 2)))
        for row in range(1201)
    ]
maxheight = max(max(cell for cell in row if cell < 32000) for row in elevation)

これで完了です。Python へようこそ :)

于 2012-05-05T14:25:39.990 に答える
2

Python では、次のような値'hello'[2]も文字列です (この場合は == 'l')。を使用して整数に変換し、 を使用ordして文字列に戻す必要がありますchr

elevation = [[],[]]
maxheight=0

b = open("C:\\Users\\CNA\\sketchbook\\_SRTM\\data\\N59E010.hgt","rb")
fin = b.read() # you probably need to read more than 1 byte, this will read whole file
print(len(fin))
ix = 0
for row in range(0,1201):
    for col in range(0,1201):
        hi = (ord(fin[ix])   + 0xff) # ord returns unsigned integer, so you probably don't need to convert it
        lo = (ord(fin[ix+1]) + 0xff)
        el = (hi << 8) | lo

参照: http://docs.python.org/library/functions.html

于 2012-05-05T13:20:11.150 に答える
0

.reshape 構文が正しいかどうかはわかりません (さらにテストします)-しかし、これに非常によく似たものがニーズに役立つはずです:

import numpy

def readHgtFile(fname, h=1201, w=1201):
    with open(fname, 'rb') as inf:
        return numpy.fromfile(inf, dtype=[('height', '>u2')], count=h*w).reshape((h,w))

def main():
    elevation = readHgtFile('N30W091.hgt')
    maxheight = elevation.max()

if __name__=="__main__":
    main()
于 2012-05-05T15:00:31.787 に答える