IR_image_tools.py 8.79 KB
Newer Older
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
# -*- coding: utf-8 -*-
"""
Created on Wed May  9 14:56:32 2018

@author: holn

mainly to clean up the downloadversionIRdata code
Tools for:
    checking IR images, 
    calculate gain and offset again from 
    check backgroundframes
    check coldframes
    ...
"""
import numpy as np
import matplotlib.pyplot as plt

def bestimmtheitsmaß_general(data,fit):
    R=0
    if len(fit)==len(data):
        mittel=np.sum(data)/len(data)
        qam=quad_abweich_mittel(fit,mittel)
        R=qam/(qam+quad_abweich(data,fit))
    else:
        print("Arrays must have same dimensions")
    return R
    
def quad_abweich_mittel(data,mittel):
    R=0
    for i in data:
        R=R+(i-mittel)**2
    return R
    
def quad_abweich(data,fit):
    R=0
    if len(fit)==len(data):
        for i in range(len(data)):
            R=R+(data[i]-fit[i])**2
    else:
        print("Arrays must have same dimensions")
    return R    
        
def check_coldframe(coldframe,references=None,threshold=0.5,plot_it=False):
    '''
    return true/false and the quality factor
    '''
    shapi=np.shape(coldframe)
    ##function  (np.arange(0,768)-384)**(2)/900-50
    datasets=[]
    for i in [int(shapi[1]//4),int(shapi[1]//2),int(shapi[1]//4*3)]:
        dataline=coldframe[0:shapi[0],i]    
        datasets.append(dataline-np.mean(dataline))
    if references==None:
        references=[]
        for dat in datasets:        
            mini=np.mean(dat[shapi[0]/2-50:shapi[0]/2+50])
            a=(np.mean(dat[0:50])-mini)/(int(shapi[0]/2))**2
            reference=a*(np.arange(0,shapi[0])-int(shapi[0]/2))**(2)+mini
            references.append(reference)
    bestimmtheit=[]
    if plot_it:
        plt.figure()
        plt.imshow(coldframe,vmin=np.mean(coldframe)-500,vmax=np.mean(coldframe)+500)
        plt.figure()
    for i_dat in range(len(datasets)):
        dat=datasets[i_dat]
        reference=references[i_dat]
        bestimmtheit.append(bestimmtheitsmaß_general(dat,reference))
        if plot_it:            
            plt.plot(dat,label='data')
            plt.plot(reference,label='reference')
#            print(int(shapi[0]/2),1*(np.max(datasets[-1])-mini),mini)
            plt.legend()
    if np.mean(bestimmtheit)>threshold:
        return True,bestimmtheit
    else:
        return False,bestimmtheit

def check_coldframe_by_refframe(coldframe,reference_frame,threshold=0.8,plot_it=False):
    references=[]
    shapi=np.shape(reference_frame)
    for i in [int(shapi[1]//4),int(shapi[1]//2),int(shapi[1]//4*3)]:
        dataline=reference_frame[0:shapi[0],i]    
        references.append(dataline-np.mean(dataline))
    return check_coldframe(coldframe,references,threshold,plot_it)
        
def check_backgroundframe(backgroundframe,threshold=50):
    '''
    return true or false
    '''
    shapi=np.shape(backgroundframe)
    valid=True
    dataset=[]
    for i in [int(shapi[1]//4),int(shapi[1]//2),int(shapi[1]//4*3)]:
        referenceline=backgroundframe[0:shapi[0],i]    
        meanref=referenceline-np.mean(referenceline)
        dataset.append(np.max(meanref)-np.min(meanref))
    if np.mean(dataset)<threshold:
        valid=False    
    return valid,np.mean(dataset)
    
def find_outlier_pixels(frame,tolerance=3,worry_about_edges=True,plot_it=False):
    # This function finds the bad pixels in a 2D dataset. 
    # Tolerance is the number of standard deviations used for cutoff.
    frame = np.array(frame)#, dtype=int)
    from scipy.ndimage import median_filter
    blurred = median_filter(frame, size=9)
    difference = frame - blurred
    threshold = tolerance*np.std(difference)
    mean = np.mean(difference)
    if plot_it:
        
        
        fig = plt.figure()
        fig.suptitle('find_outlier_pixels: histogram')
        plt.hist(difference.ravel(),50,log=True,histtype='stepfilled')
        plt.axvline(mean, linewidth=2, color='k',label='mean')
        x1 = mean - np.std(difference)
        x2 = mean + np.std(difference)
        plt.axvspan(x1,x2, linewidth=2, facecolor='g',alpha=0.1,label='standard deviation')
        x1 = mean - tolerance*np.std(difference)
        x2 = mean + tolerance*np.std(difference)
        plt.axvspan(x1,x2, linewidth=2, facecolor='r',alpha=0.1,label='threshold for bad pixel')
        plt.legend()
        plt.show()
        
    #find the hot pixels
    bad_pixels = np.transpose(np.nonzero((np.abs(difference)>threshold)) )
    bad_pixels = (bad_pixels).tolist()
    bad_pixels = [tuple(l) for l in bad_pixels]
    
    if plot_it:
        plt.figure()
        plt.imshow(frame)
        for i in range(len(bad_pixels)):
            plt.scatter(bad_pixels[i][1],bad_pixels[i][0],c='None')
        plt.show()
   
    return bad_pixels

def correct_images(images,badpixels):
    if type(badpixels)!=int:
        for i in range(len(images)):
            images[i]=(restore_pixels(images[i],np.invert(badpixels==1))).astype(np.float32)
        print("done")
    return images

def restore_pixels(frame, bad_pixel):
    # make sure bad pixel are provided as mask and list  
    if type(bad_pixel) is list:
        blist = bad_pixel
        bmask = np.ones(frame.shape,dtype=bool)
        for pix in bad_pixel:
            bmask[pix] = False
        bmask = np.invert(bmask)
    else:
        bmask = np.invert(bad_pixel)
        x,y = np.where(bmask)
        blist = list(zip(x,y))
#    print('restore_pixels() working on: ',blist)
    # prepare internal result frames
    resframe = frame.astype(float)
    # -----------------------------------
    # restore by list
    #
    height = np.shape(frame)[0]
    width  = np.shape(frame)[1]
    for pos in blist:
        # assume four neighbouring, non-bad pixels exist
        n_neighbours = 4
        # -- top neighbour --
        if pos[0] == 0:
            # out of bounds
            top = 0
            n_neighbours -= 1
        else:
            i_t = pos[0] - 1
            while (bmask[i_t,pos[1]] & (i_t >= 0)):
                i_t -= 1
            if i_t >= 0:
                top = frame[i_t,pos[1]]
            else:
                # out of bounds
                top = 0
                n_neighbours -= 1
            #print('top: ',i_t, top)    
        # -- bottom neighbour --
        if pos[0] == height-1:
            # out of bounds
            bottom = 0
            n_neighbours -= 1
        else:
            i_b = pos[0] + 1
            while (bmask[i_b,pos[1]] & (i_b <= height-2)):
                i_b += 1
            if i_b >= 0:
                bottom = frame[i_b,pos[1]]
            else:
                # out of bounds
                bottom = 0
                n_neighbours -= 1
            #print('bottom: ',i_b, bottom)
        # -- left neighbour --
        if pos[1] == 0:
            # out of bounds
            left = 0
            n_neighbours -= 1
        else:
            i_l = pos[1] - 1
            while (bmask[pos[0],i_l] & (i_l >= 0)):
                i_l -= 1
            if i_l >= 0:
                left = frame[pos[0],i_l]
            else:
                # out of bounds
                left = 0
                n_neighbours -= 1
            #print('left: ',i_l, left)    
        # -- right neighbour --
        if pos[1] == width-1:
            # out of bounds
            right = 0
            n_neighbours -= 1
        else:
            i_r = pos[1] + 1
            while (bmask[pos[0],i_r] & (i_r <= width-2)):
                i_r += 1
            if i_r >= 0:
                right = frame[pos[0],i_r]
            else:
                # out of bounds
                right = 0
                n_neighbours -= 1
            #print('right: ',i_r, right)                
        # averaging
        if n_neighbours > 0:
            #print('original value: ',frame[pos[0],pos[1]])
            resframe[pos[0],pos[1]] = (top + bottom + left + right)/n_neighbours
            #print('average of ',n_neighbours,' neighbours: ',frame1[pos[0],pos[1]])
        else:
            print('ERROR: no adjacent pixel found!')
    return resframe

def generate_new_hot_image(cold,reference_cold,reference_hot):
    if cold==None or reference_cold==None or reference_hot==None:
        raise Exception("Cannot Calculate new Hot image, if images are missing!")
    else:
        return reference_hot+(cold-reference_cold)
    
def calculate_gain_offset_image(cold_image,hot_image=None,reference_cold=None,reference_hot=None):
    if hot_image==None:
        hot_image=generate_new_hot_image(cold_image,reference_cold,reference_hot)
    Sh_ref =  hot_image[ ( np.int( np.shape(hot_image)[0]   /2  )  ) ][np.int( (np.shape(hot_image)[1]   /2  ) ) ]          
    Sc_ref =  cold_image[ ( np.int(  (np.shape(cold_image)[0])  /2 )  ) ][( np.int(  (np.shape(cold_image)[1])  /2 ) ) ]  
    Gain_rel =  ( Sh_ref  - Sc_ref ) / ( hot_image  - cold_image)    
    Off_h_rel = Sh_ref -   hot_image*Gain_rel
    Off_c_rel = Sc_ref -   cold_image*Gain_rel    
    Offset_rel  = ( Off_h_rel + Off_c_rel ) /2
    return Gain_rel,Offset_rel