feature.py 13.5 KB
Newer Older
Sugon_ldc's avatar
Sugon_ldc 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import cv2
import os
import json
from libAIF import aif
import numpy as np
from label import RPPGLabel
from collections import deque
from multiprocessing import Process, Pool
import math

def make_feature_aif_databse(outputfile, basefolder, if_src_raw=False, expected_shape=(49,49,3)):
    aif_allftimg = aif(outputfile+"_ftimgd", outputfile+"_ftimgi")
    aif_allftimg.wbegin()

    all_labels = []
    fh_label = open(outputfile + "_label.json", 'w')
    for root, dirs, files in os.walk(basefolder):
        for dname in dirs:
            prev_path = os.path.join(root, dname) + "\\"
            # xsplit = prev_path.split("\\")
            dfilename = prev_path + "datafile"
            if os.path.exists(dfilename) and os.path.dirname(dfilename)[-1] == '1':# get only the first video
                print("on going: " + dfilename)

                #label src file
                src_label_fname = root + "\\" + "bvp_" + root.split("\\")[-1] + "_T" + os.path.dirname(dfilename)[-1] + ".csv"
                print("corresponding label: " + src_label_fname)
                rppg_lab = RPPGLabel(src_label_fname)

                #features & labels
                aif_inst = aif(dfilename, prev_path + "idxfile")
                dat_info = aif_inst.rbegin()
                for i in range(0, len(dat_info), 1):
                    if if_src_raw:
                        img0 = (aif_inst.extract_raw(i)).copy()
                    else:
                        img0 = aif_inst.extract(i)
                    # img0 = cv2.resize(img0, (144, 144))

                    if (i + 1) < len(dat_info):
                        if if_src_raw:
                            img1 = (aif_inst.extract_raw(i + 1)).copy()
                        else:
                            img1 = aif_inst.extract(i + 1)
                        if img1.shape == expected_shape and img0.shape == expected_shape:
                            # adjust to the median position
                            ftimg = img1 - img0 + 128
                            aif_allftimg.append(ftimg)# features
                            all_labels.append(rppg_lab.get_label_by_frame(i)) #labels
                        else:
                            aif_allftimg.append_any(np.array([]).tobytes())
                            all_labels.append(None)                            

                    else:# end of a file, append an empty node
                        aif_allftimg.append_any(np.array([]).tobytes())
                        all_labels.append(None)

                aif_inst.rfinish()
    json.dump(all_labels, fh_label)
    fh_label.close()
    aif_allftimg.wfinish()

#300 frames * 478 landmarks * 5 cross pixels * 3 channels
#every 5 pixel makes a cross
#dat shape=(300,49,49,3)
#return 478*3 (mean), 478*3 (std)
def get_norm(dat):
    ret_mean = []
    ret_std = []
    for i in range(0, 478): # cross
        c1=[]
        c2=[]
        c3=[]
        for f in range(0, len(dat)): # frames
            for j in range(0, 5): # pixels
                px_idx = (i * 5) + j
                px_ridx = px_idx // 49
                px_cidx = px_idx % 49
                c1.append(dat[f][px_ridx][px_cidx][0])
                c2.append(dat[f][px_ridx][px_cidx][1])
                c3.append(dat[f][px_ridx][px_cidx][2])
        ret_mean.append([np.mean(c1), np.mean(c2), np.mean(c3)])
        ret_std.append([np.std(c1), np.std(c2), np.std(c3)])
    return [ret_mean, ret_std]

#feat: 49*49*3, every 5 as a cross with 1 norm
#norm: 478*3 (mean), 478*3 (std)
def feat_normalize(feat, norm, m_offset=0):
    ret = []
    npixel = feat.shape[0] * feat.shape[1]
    norm = norm.reshape(-1, 478, 3)
    for i in range(0, npixel):
        irow = i // 49
        icol = i % 49
        if i < 478*5:
            tar_vec = [0,0,0]
            for z in range(0, 3):
                if norm[1][i//5][z] == 0:
                    if feat[irow][icol][z] >= 0:
                        tar_vec[z] = 4
                    else:
                        tar_vec[z] = -4
                else:
                    tar_vec[z] = (feat[irow][icol][z] - m_offset - norm[0][i//5][z]) / norm[1][i//5][z]
            ret.append(np.array(tar_vec))
        else:
            ret.append(np.array([0,0,0]))
    ret = np.array(ret, dtype='float32')
    return ret.reshape(49,49,3)

#prefix + digi + appendix
def merge_aifs_digiapdx(aiffolder, prefix,\
        appendix_d, appendix_i, begnum, endnum, destpath,\
        extract="image", dtype="float32"):
    merged_aif = aif(destpath + "_dfile", destpath + "_ifile")
    merged_aif.wbegin()
    for i in range(begnum, endnum + 1):
        src_d_path = aiffolder + prefix + str(i) + appendix_d
        src_i_path = aiffolder + prefix + str(i) + appendix_i
        if os.path.exists(src_d_path) and os.path.exists(src_i_path):
            print(src_i_path)
            src_aif = aif(src_d_path, src_i_path)
            info = src_aif.rbegin()
            buf = None
            for j in range(0, len(info)):
                if extract == "image":
                    buf = src_aif.extract(j)
                    merged_aif.append(buf)
                elif extract == "bytes":
                    buf = src_aif.extract_raw(j, dtype=dtype)
                    merged_aif.append_any(np.array(buf, dtype=dtype).tobytes())
            src_aif.rfinish()
    merged_aif.wfinish()

def merge_jsons(jsonfolder, prefix, appendix, begnum, endum, destpath):
    dat = []
    for i in range(begnum, endum + 1):
        filepath = jsonfolder + prefix + str(i) + appendix
        if os.path.exists(filepath):
            print(filepath)
            srcfh = open(filepath, 'r')
            dat.extend(json.load(srcfh))
            srcfh.close()
    fh = open(destpath, 'w')
    json.dump(dat, fh)
    fh.close()

def _make_norm_ldmk_MTCore(\
        outname_pre, subject_code, src_dfile, src_ifile, src_labfile,\
        norm_len, interval=5):
    if_src_raw = False
    expected_shape=(49,49,3)

    aif_dst_ftimg = aif(outname_pre + subject_code +"_ftimgd", outname_pre + subject_code +"_ftimgi")
    aif_dst_ftimg.wbegin()
    aif_dst_norm = aif(outname_pre + subject_code + "_normd", outname_pre + subject_code +"_normi")
    aif_dst_norm.wbegin()
    json_dst_labels = []
    fh_label = open(outname_pre + subject_code + "_label.json", 'w')
    print("on going: " + src_dfile)

    #label src file
    
    print("corresponding label: " + src_labfile)
    rppg_lab = RPPGLabel(src_labfile)

    #features & labels
    aif_inst = aif(src_dfile, src_ifile)
    dat_info = aif_inst.rbegin()

    # d_norm = []# [[[mean1,mean2,mean3],[std1,std2,std3]]...478]
    d_v300 = deque()

    total_none = 0

    for i in range(0, len(dat_info), interval):# frames within file
        if if_src_raw:
            img0 = (aif_inst.extract_raw(i)).copy()
        else:
            img0 = aif_inst.extract(i)
        # img0 = cv2.resize(img0, (144, 144))

        if (i + interval) < len(dat_info):
            # make norm
            # if i < norm_len and img0.shape == expected_shape:
            #     d_v300.append(img0) # 300 frames * 478 crosses
            # else:
            #     pass

            print('person: {}, frame num: {}'.format(subject_code,i))
            #one norm, one ft, one label
            if if_src_raw:
                img1 = (aif_inst.extract_raw(i + interval)).copy()
            else:
                img1 = aif_inst.extract(i + interval)

            if img1.shape == expected_shape and img0.shape == expected_shape:
                xdiff = img1 - img0 + 128
                if i < norm_len:
                    d_v300.append(xdiff) # 300 frames * 478 crosses
                else:
                    # make norm
                    cur_norm = get_norm(d_v300)
                    aif_dst_norm.append_any(np.array(cur_norm, dtype="float32").tobytes())
                    d_v300.popleft()
                    d_v300.append(xdiff)
                    # adjust to the median position
                    ftimg = xdiff
                    aif_dst_ftimg.append(ftimg)# features
                    xlab = rppg_lab.get_label_by_frame(i)
                    if xlab == None:
                        total_none += 1
                    json_dst_labels.append(xlab) #labels
            else:
                aif_dst_ftimg.append_any(np.array([]).tobytes())
                json_dst_labels.append(None)
                aif_dst_norm.append_any(np.array([]).tobytes())                        

        else:# end of a file, append an empty node
            aif_dst_ftimg.append_any(np.array([]).tobytes())
            json_dst_labels.append(None)
            aif_dst_norm.append_any(np.array([]).tobytes())
    aif_inst.rfinish()

    json.dump(json_dst_labels, fh_label)
    fh_label.close()
    aif_dst_ftimg.wfinish()
    aif_dst_norm.wfinish()
    print("total_none: " + str(total_none))

def _make_norm_pv_ldmk_MTCore(outname_pre, subject_code, src_dfile, src_ifile, src_labfile, norm_len):
    expected_shape=(49,49,3)

    aif_dst_ftimg = aif(outname_pre + subject_code +"_ftimgd", outname_pre + subject_code +"_ftimgi")
    aif_dst_ftimg.wbegin()
    aif_dst_norm = aif(outname_pre + subject_code + "_normd", outname_pre + subject_code +"_normi")
    aif_dst_norm.wbegin()
    json_dst_labels = []
    fh_label = open(outname_pre + subject_code + "_label.json", 'w')
    print("on going: " + src_dfile)

    #label src file
    
    print("corresponding label: " + src_labfile)
    rppg_lab = RPPGLabel(src_labfile)

    #features & labels
    aif_inst = aif(src_dfile, src_ifile)
    dat_info = aif_inst.rbegin()

    # loop here
    # make mixed label
    lab_coll = rppg_lab.get_frm_num_at_pvs()
    pv_frmnums_coll = []
    p_or_v = []
    niter = len(lab_coll[0]) if len(lab_coll[0]) > len(lab_coll[1]) else len(lab_coll[1])
    for xl in range(0, niter):
        if xl < len(lab_coll[0]):
            pv_frmnums_coll.append(lab_coll[0][xl])
            p_or_v.append(0)
        if xl < len(lab_coll[1]):
            pv_frmnums_coll.append(lab_coll[1][xl])
            p_or_v.append(1)
    # make featrue and norm
    loop_idx = 0
    for xpfrm in pv_frmnums_coll:
        # ret norm = []# [[[mean1,mean2,mean3],[std1,std2,std3]]...478]
        norm_buf = []
        if xpfrm < len(dat_info):
            img0 = aif_inst.extract(xpfrm)
            if xpfrm > norm_len and img0.shape == expected_shape:
                print(subject_code + ": " + str(xpfrm))
                # featlab
                aif_dst_ftimg.append(img0)
                json_dst_labels.append(p_or_v[loop_idx])
                # norm
                for i in range(xpfrm - norm_len, xpfrm):
                    norm_img = aif_inst.extract(xpfrm)
                    if norm_img.shape == expected_shape:
                        norm_buf.append(norm_img)
                cur_norm = get_norm(norm_buf)
                aif_dst_norm.append_any(np.array(cur_norm, dtype="float32").tobytes())
            loop_idx += 1
            
    aif_inst.rfinish()

    json.dump(json_dst_labels, fh_label)
    fh_label.close()
    aif_dst_ftimg.wfinish()
    aif_dst_norm.wfinish()

def make_normalized_landmarks_dbMT(outputfolder, basefolder, subject_list,\
                                   keyfunc, norm_len=60):
    pool = Pool(14)
    for root, dirs, files in os.walk(basefolder):
        for dname in dirs:
            prev_path = os.path.join(root, dname) + "\\"
            # xsplit = prev_path.split("\\")
            dfilename = prev_path + "datafile"
            difilename = prev_path + "idxfile"
            if os.path.exists(dfilename) and os.path.dirname(dfilename)[-1] == '1':# get only the first video
                src_label_fname = root + "\\" + "bvp_" + root.split("\\")[-1] + "_T" + os.path.dirname(dfilename)[-1] + ".csv"
                subject_code = root.split("\\")[-1]
                if len(subject_list) != 0 and subject_code not in subject_list:
                    break
                # MT
                pool.apply_async(func=keyfunc, args=(\
                    outputfolder, subject_code, dfilename,\
                    difilename, src_label_fname, norm_len,))
    pool.close()
    pool.join()

if __name__ == "__main__":
    # inter-frame plan
    # make_normalized_landmarks_dbMT(\
    #     "G:\\ecg\\AIFDatabase\\ldmk_intermediate\\interframe\\", "G:\\ecg\\raw",\
    #     subject_list=[], keyfunc=_make_norm_ldmk_MTCore)

    # _make_norm_ldmk_MTCore("G:/ecg/AIFDatabase/ldmk_intermediate/interframe/","s3",\
    #                     "G:/ecg/raw/s3/f_imgs1/datafile",\
    #                     "G:/ecg/raw/s3/f_imgs1/idxfile",\
    #                     "G:/ecg/raw/s3/bvp_s3_T1.csv",60)

    # only peaks and valleys ---- NO GOOD!
    # MT
    # make_normalized_landmarks_dbMT("G:\\ecg\\AIFDatabase\\ldmk_intermediate\\", "G:\\ecg\\raw",\
    #     subject_list=['s2'],\
    #     keyfunc=_make_norm_pv_ldmk_MTCore)
    # 
    # ST
    # _make_norm_pv_ldmk_MTCore("G:\\ecg\\AIFDatabase\\ldmk_intermediate\\peakvalley\\", "s2",\
    #                         "G:\\ecg\\raw\\s2\\f_imgs1\\datafile", "G:\\ecg\\raw\\s2\\f_imgs1\\idxfile",\
    #                         "G:\\ecg\\raw\\s2\\bvp_s2_T1.csv", 60)

    # image
    # merge_aifs_digiapdx("G:/ecg/AIFDatabase/ldmk_intermediate/interframe/",\
    #                     "s", "_ftimgd", "_ftimgi", 2, 38,\
    #                     "G:/ecg/AIFDatabase/ldmk_aggr/feature",dtype='uint8')
    # norm
    merge_aifs_digiapdx("G:/ecg/AIFDatabase/ldmk_intermediate/interframe/",\
                        "s", "_normd", "_normi", 2, 38, "G:/ecg/AIFDatabase/ldmk_aggr/norm",\
                        extract="bytes",dtype='float32')
    # # labels
    # merge_jsons("G:/ecg/AIFDatabase/ldmk_intermediate/interframe/",\
    #             "s", "_label.json", 2, 38, "G:/ecg/AIFDatabase/ldmk_aggr/label.json")