spectral.py
1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 23 13:52:22 2017
@author: david
"""
import numpy
#sift a 2D hyperspectral image into a PxB matrix where P is the number of pixels and B is the number of bands
def sift2(I, mask = []):
#get the shape of the input array
S = I.shape
#convert that array into a 1D matrix
M = numpy.reshape(I, (S[2], S[0] * S[1]))
#gif no mask is provided, just return all pixels
if mask == []:
return M
#if a mask is provided, only return pixels corresponding to that mask
flatmask = numpy.reshape(mask, (S[0] * S[1]))
i = numpy.flatnonzero(flatmask) #get the nonzero indices
return M[:, i] #return pixels corresponding to the masked values
def unsift2(M, mask):
#get the size of the input matrix
S = M.shape
#count the number of nonzero values in the mask
nnz = numpy.count_nonzero(mask)
#the number of masked values should be the same as the number of pixels in the input matrix
if len(S) == 1:
if not S[0] == nnz:
print("ERROR: expected " + str(nnz) + " pixels based on the mask but there are " + str(S[0]) + " in the matrix.")
elif not S[1] == nnz:
print("ERROR: expected " + str(nnz) + " pixels based on the mask but there are " + str(S[1]) + " in the matrix.")
i = numpy.nonzero(mask)
if len(S) == 1:
I = numpy.zeros((1, mask.shape[0], mask.shape[1]), dtype=M.dtype)
else:
I = numpy.zeros((M.shape[0], mask.shape[0], mask.shape[1]), dtype=M.dtype)
I[:, i[0], i[1]] = M
return I
#create a function that sifts a color image
#input: image name, mask