forked from tim-dav/cnn-sar-despeckle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtif2intensity.py
62 lines (52 loc) · 2.18 KB
/
tif2intensity.py
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
54
55
56
57
58
59
60
61
62
# helper methods for generating intensity images
import tifffile as tif
import numpy as np
import os
from model.util import PolarityType
def get_intensity_image(filename, channels_last=False):
"""
Get an intensity image the specified tif file
@param filename : the filename of the raw SAR image in tif format
@param channels_last: indicate if the image channels are stored last (defaul False)
@returns the 2-channel intensity image (VH and VV intensity channels)
"""
image = tif.imread(filename)
if channels_last:
image = np.rollaxis(image, 2)
bands = image.shape[0]
if bands != 4:
raise ValueError("In %s expected 4 bands but found %i" % (filename, bands))
else:
intensity = np.zeros((image.shape[1], image.shape[2], 2), dtype=np.float32)
for band, pol in enumerate(PolarityType):
i = pol.value * 2
j = i + 1 # indices of our desired bands
intensity[:, :, band] = np.sqrt(image[i] * image[i] + image[j] * image[j])
return intensity.astype(np.float32)
def intensity_images_from_dir(load_dir, save_dir):
"""
Convert a directory of raw SAR images into 2-channel intensity images and save them
@param load_dir: the directory from which to load the raw images
@param save_dir: the directory in which to save the intensity images
"""
print("BEGIN directory ", load_dir)
files = os.listdir(load_dir)
additional_dirs = []
for f in files:
if str(f)[-3:] != "tif":
path = os.path.join(load_dir, f + "/")
if not os.path.isdir(path):
print("\tSKIPPING:", f, "expected filetype TIFF")
else:
try:
intensity = get_intensity_image(os.path.join(load_dir, f))
if intensity is not None:
try:
tif.imsave(data=intensity, file=os.path.join(save_dir, f))
except:
print("\tERROR saving ", f, ". Was the output directory created?")
except ValueError as e:
print(e)
except:
print("\tERROR converting", f)
print("END directory", load_dir)