ZonalStat.py 6.94 KB
Newer Older
luroth's avatar
luroth committed
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
'''
Created on 16.03.2017

@author: luroth
'''

from pylab import plot,show
from numpy import vstack,array
from numpy.random import rand
import numpy.ma as ma
import numpy as np
from scipy.cluster.vq import kmeans,vq
from scipy import misc
import sklearn.cluster
import multiprocessing
import matplotlib.pyplot as plt
from osgeo import gdalnumeric
import os
import sys
import getopt
import csv
from scipy import ndimage
import geojson
import json
from Common import *
from osgeo import ogr, gdal
import pandas as pd
from multiprocessing import Process, Queue, Manager
import time
from progressbar import ProgressBar

def zonal_worker(work_queue, result_queue, metadata_folder, sub_plots):
    for job in iter(work_queue.get, 'STOP'):
        PhotoID = job['PhotoID']
        result = zonal_stat(metadata_folder, sub_plots, PhotoID)
        result_queue.put(result)

def zonal_stat(metadata_folder, sub_plots, PhotoID):
    samples = []
    
    subplots_ds = gdal.Open(os.path.join(metadata_folder, PhotoID + '_mask_subsamples.tif'))
    subplots = np.array(subplots_ds.GetRasterBand(1).ReadAsArray(), dtype=int)
    origin_shape = subplots.shape
    subplots = subplots.reshape(-1)
    
    photo_meta_x_ds = gdal.Open(os.path.join(metadata_folder, PhotoID + '_metadata_coord_x.tif'))
    photo_meta_x = np.array(photo_meta_x_ds.GetRasterBand(1).ReadAsArray(), dtype=np.float64)
    photo_meta_x += DELTA_x
    
    photo_meta_y_ds = gdal.Open(os.path.join(metadata_folder, PhotoID + '_metadata_coord_y.tif'))
    photo_meta_y = np.array(photo_meta_y_ds.GetRasterBand(1).ReadAsArray(), dtype=np.float64)
    photo_meta_y += DELTA_y

    photo_meta_xy = np.stack((photo_meta_x, photo_meta_y), axis=2)
    photo_meta_xy = photo_meta_xy.reshape(-1,2)
    
    photo_meta_x = photo_meta_x.reshape(-1)
    photo_meta_y = photo_meta_y.reshape(-1)
    
    segmented  =  misc.imread(os.path.join(metadata_folder, PhotoID + '_segmented_ExG.tif'))
    segmented = segmented.reshape(-1)
    
    photo_meta_z  =  misc.imread(os.path.join(metadata_folder, PhotoID + '_metadata_coord_z.tif'))
    photo_meta_z = photo_meta_z.reshape(-1)
    
    photo_meta_angle_z  =  misc.imread(os.path.join(metadata_folder, PhotoID + '_metadata_angle_z.tif'))
    photo_meta_angle_z = photo_meta_angle_z.reshape(-1)
    photo_meta_angle_xy  =  misc.imread(os.path.join(metadata_folder, PhotoID + '_metadata_angle_xy.tif'))
    photo_meta_angle_xy = photo_meta_angle_xy.reshape(-1)

    for sub_plot in sub_plots:
        plot_id = sub_plot['properties']['plot_number']
        subsample = sub_plot['properties']['subsample']
        
        #print("calculating plot id", plot_id, ', subsample', subsample)
        
        mask_subplot = subplots == (plot_id*100+subsample)
        
        subplot_segmented = segmented[mask_subplot]
        
        if subplot_segmented.size > 0:
            subplot_mean_cc = np.mean(subplot_segmented)
            subplot_mean_x = np.mean(photo_meta_x[mask_subplot])
            subplot_mean_y = np.mean(photo_meta_y[mask_subplot])
            subplot_mean_z = np.mean(photo_meta_z[mask_subplot])
            subplot_mean_angle_z = np.mean(photo_meta_angle_z[mask_subplot])
            subplot_mean_angle_xy = np.mean(photo_meta_angle_xy[mask_subplot])
            
            image_x, image_y = np.where(mask_subplot.reshape(origin_shape))
            image_x = np.mean(image_x)
            image_y = np.mean(image_y)
        
            #print(subplot_mean_cc, end="", flush=True)
            samples.append({"plot_id":plot_id, 'subsample':subsample, 'CC':subplot_mean_cc,
                           'glob_X':subplot_mean_x,
                           'glob_Y':subplot_mean_y,
                           'glob_Z':subplot_mean_z,
                           'angle_z':subplot_mean_angle_z,
                           'angle_xy':subplot_mean_angle_xy,
                           'image':PhotoID,
                           'image_x':image_x,
                           'image_y':image_y})
        else:
            pass
    
    return samples


def main(argv):
    camera_position_file = ''
    metadata_folder = ''
    output_directory = ''
    sub_plots_file = ''
    
    try:
        opts, args = getopt.getopt(argv,"hc:m:p:s:o:")
    except getopt.GetoptError:
        print('test.py -c <camera position file> -m <metadata folder> -o <Output directory>')
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print('test.py -c <camera position file> -m <metadata folder> -o <Output directory>')
            sys.exit()
        elif opt == "-c":
            camera_position_file = arg
        elif opt == "-m":
            metadata_folder = arg    
        elif opt == "-o":
            output_directory = arg      
        elif opt == "-s":
            sub_plots_file = arg              
    
    print('Metdadata folder is', metadata_folder)
    
    all_cc = []
    
    sub_plots_file = r'E:\UAV\_Workspace_\2016_ethz_eschikon_FIP_50m_general\design_subsamples.geojson'
    with open(sub_plots_file, 'r') as f:
        sub_plots_tmp = geojson.load(f)
        sub_plots = sub_plots_tmp['features']
        
    with open(camera_position_file, 'r') as csvfile:
        spamreader = csv.reader(csvfile, delimiter='\t', quotechar='|')
        next(spamreader, None)
        next(spamreader, None)
   
        m = Manager()
        jobs = m.Queue()
        results = m.Queue()
        processes = []
        
        max_jobs = 0
        count = 0
        for row in spamreader:  
            PhotoID = os.path.splitext(row[0])[0]
            
            if (os.path.isfile(os.path.join(metadata_folder, PhotoID + '_mask_subsamples.tif')) and 
                os.path.isfile(os.path.join(metadata_folder, PhotoID + '_segmented_ExG.tif'))):
                
                job = dict()
                job['PhotoID'] = PhotoID
                jobs.put(job)
                 
                max_jobs += 1
            
        progress = ProgressBar(min_value=0, max_value=max_jobs)
            
        for w in range(multiprocessing.cpu_count()-2):
            p = Process(target=zonal_worker, args=(jobs, results, metadata_folder, sub_plots))
            p.daemon = True
            p.start()
            processes.append(p)
            jobs.put('STOP')
        
        print("jobs all started")
        
        samples = []
        progress.update(0)
        while count < (max_jobs):
            samples_ = results.get()
            samples.extend(samples_)
            progress.update(count)
            count+=1
            
        progress.finish()
        
        for p in processes:
            p.join()
        
        pd_data = pd.DataFrame(samples)
        pd_data.to_csv(os.path.join(metadata_folder, "CC.csv"))
                
if __name__ == "__main__":
    main(sys.argv[1:])
    
    print("\n============\nAll images segmented, END\n")