2017-12-01 2 views
0

Ich verwende die folgende Funktion mit python2.7:Wie konvertiert man ein numpy.array in eine Binärdatei?

def array2int(pixels): 
    out = 0 
    for bit in pixels: 
     out = (out << 1) | bit 
    return out 

die in der Regel funktioniert, aber wenn ich

v=np.array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 
     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) 
array2int(v.astype(int)) 

Pass gibt es -262145.

+0

'out = (out << 1) | int (bit) 'ist eine schnelle Lösung –

+1

Sie könnten auch versuchen:' int ("". join (map (str, v)), 2) ' – pault

+0

@pault funktioniert nicht für booleans, hart ;-) –

Antwort

3

Im Gegensatz zu Python verwendet numpy standardmäßig Ganzzahlen fester Größe. Diese können ersäufen

1<<65 
# 36893488147419103232 # correct 
npone = np.ones([1], dtype=int)[0] 
npone 
# 1 
type(npone) 
# <class 'numpy.int64'> 
npone<<65 
# 2 # wrong 

Beim Hinzufügen oder bitweise ODER-Verknüpfung oder was auch immer ein Python int und ein numpy int, numpy der Regel gewinnt und das Ergebnis wird ein numpy int:

out = 1 
type(out) 
# <class 'int'> 
out = (out << 1) | npone 
type(out) 
# <class 'numpy.int64'> 

Um das zu verhindern in Ihrer Funktion können Sie werfen explizit bit auf einen geeigneten int:

 out = (out << 1) | int(bit) 
Verwandte Themen