Skip to content

Commit 3d7c36e

Browse files
authored
Add files via upload
1 parent 71f5003 commit 3d7c36e

4 files changed

+517
-0
lines changed

NDVIStandAlone.py

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Experimental Vegetation Index Mapping program using DJI Mavic Pro DNG (raw image) +
4+
JPEG 16-bit combo images taken using InfraBlue Filter
5+
6+
This Version uses a special Broad Dual Bandpass NIR and Blue filter with a Narrow Bandpass in the Green
7+
to Create a combo NIR Blue + Green Image Allowing for Standalone JPG to NDVI
8+
9+
%(c)-J. Campbell MuonRay Enterprises 2019
10+
This Python script was created using the Spyder Editor
11+
12+
"""
13+
import warnings
14+
warnings.filterwarnings('ignore')
15+
from scipy import misc
16+
import imageio
17+
import numpy as np
18+
from matplotlib import pyplot as plt # For image viewing
19+
20+
#!/usr/bin/python
21+
import getopt
22+
import sys
23+
24+
import matplotlib.pyplot as plt
25+
from matplotlib import colors
26+
from matplotlib import ticker
27+
from matplotlib.colors import LinearSegmentedColormap
28+
29+
30+
class NDVI(object):
31+
def __init__(self, file_path, output_file=False, colors=False):
32+
self.image = plt.imread(file_path)
33+
self.output_name = 'NDVI.jpg'
34+
self.colors = ['gray', 'gray', 'red', 'yellow', 'green']
35+
36+
def create_colormap(self, *args):
37+
return LinearSegmentedColormap.from_list(name='custom1', colors=args)
38+
39+
def create_colorbar(self, fig, image):
40+
position = fig.add_axes([0.125, 0.19, 0.2, 0.05])
41+
norm = colors.Normalize(vmin=-1., vmax=1.)
42+
cbar = plt.colorbar(image,
43+
cax=position,
44+
orientation='horizontal',
45+
norm=norm)
46+
cbar.ax.tick_params(labelsize=6)
47+
tick_locator = ticker.MaxNLocator(nbins=3)
48+
cbar.locator = tick_locator
49+
cbar.update_ticks()
50+
cbar.set_label("NDVI", fontsize=10, x=0.5, y=0.5, labelpad=-25)
51+
52+
def convert(self):
53+
"""
54+
This function performs the NDVI calculation and returns an GrayScaled frame with mapped colors)
55+
"""
56+
NIR = (self.image[:, :, 0]).astype('float')
57+
blue = (self.image[:, :, 2]).astype('float')
58+
green = (self.image[:, :, 1]).astype('float')
59+
bottom = (blue - green) ** 2
60+
bottom[bottom == 0] = 1 # remove 0 from nd.array
61+
VIS = (blue + green) ** 2 / bottom
62+
NDVI = (NIR - VIS) / (NIR + VIS)
63+
64+
fig, ax = plt.subplots()
65+
image = ax.imshow(NDVI, cmap=self.create_colormap(*self.colors))
66+
plt.axis('off')
67+
68+
self.create_colorbar(fig, image)
69+
70+
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
71+
fig.savefig(self.output_name, dpi=600, transparent=True, bbox_inches=extent, pad_inches=0)
72+
# plt.show()
73+
74+
75+
def main(argv):
76+
77+
78+
input_file = 'DJI_0069.JPG'
79+
80+
output_file = False
81+
colors = False
82+
83+
blue_ndvi = NDVI(input_file, output_file=output_file or False, colors=colors or False)
84+
blue_ndvi.convert()
85+
86+
87+
if __name__ == "__main__":
88+
main(sys.argv[1:])

ndviandendviandsavibatchversion.py

+152
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,152 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Sat Oct 12 03:38:28 2019
4+
5+
@author: cosmi
6+
7+
rawpy is an easy-to-use Python wrapper for the LibRaw library.
8+
rawpy works natively with numpy arrays and supports a lot of options,
9+
including direct access to the unprocessed Bayer data
10+
It also contains some extra functionality for finding and repairing hot/dead pixels.
11+
import rawpy.enhance for this
12+
13+
First, install the LibRaw library on your system.
14+
15+
pip install libraw.py
16+
17+
then install rawpy
18+
19+
pip install rawpy
20+
21+
"""
22+
23+
"""
24+
Experimental Vegetation Index Mapping program using DJI Mavic 2 Pro
25+
JPEG 16-bit combo images taken using InfraBlue Filter
26+
Useful for Batch Processing Multiple Images
27+
28+
%(c)-J. Campbell MuonRay Enterprises 2019
29+
This Python script was created using the Spyder Editor
30+
31+
"""
32+
33+
import warnings
34+
warnings.filterwarnings('ignore')
35+
#import imageio
36+
import numpy as np
37+
from matplotlib import pyplot as plt # For image viewing
38+
39+
from matplotlib import colors
40+
from matplotlib import ticker
41+
from matplotlib.colors import LinearSegmentedColormap
42+
43+
#dng reading requires libraw to work
44+
45+
import os
46+
import rawpy
47+
48+
49+
cols1 = ['blue', 'green', 'yellow', 'red']
50+
cols2 = ['gray', 'gray', 'red', 'yellow', 'green']
51+
cols3 = ['gray', 'blue', 'green', 'yellow', 'red']
52+
cols4 = ['black', 'gray', 'blue', 'green', 'yellow', 'red']
53+
54+
def create_colormap(args):
55+
return LinearSegmentedColormap.from_list(name='custom1', colors=cols3)
56+
57+
#colour bar to match grayscale units
58+
def create_colorbar(fig, image):
59+
position = fig.add_axes([0.125, 0.19, 0.2, 0.05])
60+
norm = colors.Normalize(vmin=-1., vmax=1.)
61+
cbar = plt.colorbar(image,
62+
cax=position,
63+
orientation='horizontal',
64+
norm=norm)
65+
cbar.ax.tick_params(labelsize=6)
66+
tick_locator = ticker.MaxNLocator(nbins=3)
67+
cbar.locator = tick_locator
68+
cbar.update_ticks()
69+
cbar.set_label("NDVI", fontsize=10, x=0.5, y=0.5, labelpad=-25)
70+
71+
72+
for infile in os.listdir("./"):
73+
print( "file : " + infile)
74+
if infile[-3:] == "tif" or infile[-3:] == "DNG" :
75+
# print "is tif or DNG (RAW)"
76+
outfile = infile[:-3] + "jpeg"
77+
raw = rawpy.imread(infile)
78+
79+
80+
print( "new filename : " + outfile)
81+
# Extract Red, Green and Blue channels and save as separate files
82+
83+
rgb = raw.postprocess(gamma=(1,1), no_auto_bright=True, output_bps=16)
84+
85+
R = rgb[:,:,0]
86+
G = rgb[:,:,1]
87+
B = rgb[:,:,2]
88+
89+
# Get the red band from the rgb image, and open it as a numpy matrix
90+
#NIR = image[:, :, 0]
91+
#ir = np.asarray(NIR, float)
92+
93+
ir = (R).astype('float')
94+
95+
# Get one of the IR image bands (all bands should be same)
96+
#blue = image[:, :, 2]
97+
98+
#r = np.asarray(blue, float)
99+
100+
r = (B).astype('float')
101+
102+
103+
104+
"For ENDVI"
105+
#g = np.asarray(G, float)
106+
107+
g = (G).astype('float')
108+
109+
#(NIR + Green)
110+
irg = np.add(ir, g)
111+
112+
"For SAVVI"
113+
114+
115+
L=0.5;
116+
117+
rplusb = np.add(ir, r)
118+
rminusb = np.subtract(ir, r)
119+
oneplusL = np.add(1, L)
120+
121+
# Create a numpy matrix of zeros to hold the calculated NDVI values for each pixel
122+
# The NDVI image will be the same size as the input image
123+
124+
125+
ndvi = np.zeros(r.size)
126+
127+
ndvi = np.true_divide(np.subtract(irg, 2*r), np.add(irg, 2*r))
128+
129+
#ndvi = np.true_divide(np.subtract(ir, r), np.add(ir, r))
130+
131+
#savi = np.multiply(oneplusL , (np.true_divide((rminusb), np.add(rplusb, L))))
132+
#endvi = np.true_divide(np.subtract(irg, 2*r), np.add(irg, 2*r))
133+
134+
135+
136+
137+
fig, ax = plt.subplots()
138+
139+
image = ax.imshow(ndvi, cmap=create_colormap(colors))
140+
plt.axis('off')
141+
#Lock or Unlock Key Bar Here for Mapping/Sampling/Showcasing:
142+
#create_colorbar(fig, image)
143+
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
144+
#imageio.imsave(outfile, ndvi)
145+
fig.savefig(outfile, dpi=600, transparent=True, bbox_inches=extent, pad_inches=0)
146+
147+
# plt.show()
148+
149+
150+
# rgb = raw.postprocess()
151+
152+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Sat Oct 12 03:38:28 2019
4+
5+
@author: cosmi
6+
7+
rawpy is an easy-to-use Python wrapper for the LibRaw library.
8+
rawpy works natively with numpy arrays and supports a lot of options,
9+
including direct access to the unprocessed Bayer data
10+
It also contains some extra functionality for finding and repairing hot/dead pixels.
11+
import rawpy.enhance for this
12+
13+
First, install the LibRaw library on your system.
14+
15+
pip install libraw.py
16+
17+
then install rawpy
18+
19+
pip install rawpy
20+
21+
"""
22+
23+
"""
24+
Experimental Vegetation Index Mapping program using DJI Mavic 2 Pro
25+
JPEG 16-bit combo images taken using InfraBlue Filter
26+
Useful for Batch Processing Multiple Images
27+
28+
%(c)-J. Campbell MuonRay Enterprises 2019
29+
This Python script was created using the Spyder Editor
30+
31+
"""
32+
33+
import warnings
34+
warnings.filterwarnings('ignore')
35+
#import imageio
36+
import numpy as np
37+
from matplotlib import pyplot as plt # For image viewing
38+
39+
from matplotlib import colors
40+
from matplotlib import ticker
41+
from matplotlib.colors import LinearSegmentedColormap
42+
43+
#dng reading requires libraw to work
44+
45+
import os
46+
import rawpy
47+
48+
49+
cols1 = ['blue', 'green', 'yellow', 'red']
50+
cols2 = ['gray', 'gray', 'red', 'yellow', 'green']
51+
cols3 = ['gray', 'blue', 'green', 'yellow', 'red']
52+
cols4 = ['black', 'gray', 'blue', 'green', 'yellow', 'red']
53+
54+
def create_colormap(args):
55+
return LinearSegmentedColormap.from_list(name='custom1', colors=cols3)
56+
57+
#colour bar to match grayscale units
58+
def create_colorbar(fig, image):
59+
position = fig.add_axes([0.125, 0.19, 0.2, 0.05])
60+
norm = colors.Normalize(vmin=-1., vmax=1.)
61+
cbar = plt.colorbar(image,
62+
cax=position,
63+
orientation='horizontal',
64+
norm=norm)
65+
cbar.ax.tick_params(labelsize=6)
66+
tick_locator = ticker.MaxNLocator(nbins=3)
67+
cbar.locator = tick_locator
68+
cbar.update_ticks()
69+
cbar.set_label("NDVI", fontsize=10, x=0.5, y=0.5, labelpad=-25)
70+
71+
72+
for infile in os.listdir("./"):
73+
print( "file : " + infile)
74+
if infile[-3:] == "tif" or infile[-3:] == "DNG" :
75+
# print "is tif or DNG (RAW)"
76+
outfile = infile[:-3] + "jpeg"
77+
raw = rawpy.imread(infile)
78+
79+
80+
print( "new filename : " + outfile)
81+
# Extract Red, Green and Blue channels and save as separate files
82+
83+
rgb = raw.postprocess(gamma=(1,1), no_auto_bright=True, output_bps=16)
84+
85+
R = rgb[:,:,0]
86+
G = rgb[:,:,1]
87+
B = rgb[:,:,2]
88+
89+
# Get the red band from the rgb image, and open it as a numpy matrix
90+
#NIR = image[:, :, 0]
91+
#ir = np.asarray(NIR, float)
92+
93+
ir = (R).astype('float')
94+
95+
# Get one of the IR image bands (all bands should be same)
96+
#blue = image[:, :, 2]
97+
98+
#r = np.asarray(blue, float)
99+
100+
r = (B).astype('float')
101+
102+
103+
104+
"For ENDVI"
105+
#g = np.asarray(G, float)
106+
107+
g = (G).astype('float')
108+
109+
#(NIR + Green)
110+
irg = np.add(ir, g)
111+
112+
"For SAVI"
113+
114+
115+
L=0.5;
116+
117+
rplusb = np.add(ir, r)
118+
rminusb = np.subtract(ir, r)
119+
oneplusL = np.add(1, L)
120+
121+
# Create a numpy matrix of zeros to hold the calculated NDVI values for each pixel
122+
# The NDVI image will be the same size as the input image
123+
124+
125+
ndvi = np.zeros(r.size)
126+
127+
128+
ndvi = np.true_divide(np.subtract(irg, 2*r), np.add(irg, 2*r))
129+
#ndvi = np.true_divide(np.subtract(ir, r), np.add(ir, r))
130+
131+
#savi = np.true_divide(np.multiply(rminusb, 1+L), np.add(rplusb, L))
132+
#endvi = np.true_divide(np.subtract(irg, 2*r), np.add(irg, 2*r))
133+
134+
135+
136+
137+
fig, ax = plt.subplots()
138+
139+
image = ax.imshow(ndvi, cmap='Greys')
140+
plt.axis('off')
141+
#Lock or Unlock Key Bar Here for Mapping/Sampling/Showcasing:
142+
#create_colorbar(fig, image)
143+
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
144+
#imageio.imsave(outfile, ndvi)
145+
fig.savefig(outfile, dpi=600, transparent=True, bbox_inches=extent, pad_inches=0)
146+
147+
# plt.show()
148+
149+
150+
# rgb = raw.postprocess()
151+
152+
153+
154+

0 commit comments

Comments
 (0)