Imagefunctions.py 8.86 KB
Newer Older
luroth's avatar
luroth committed
1
2
3
4
5
6
import rawpy
import numpy as np
import cv2

####
# TEST
luroth's avatar
luroth committed
7
path_image = '/home/luroth/PycharmProjects/crop_growth_analysis/Scripts/Analysis/Active_Learning/samples2/RAW/_DSC7431.ARW'
luroth's avatar
luroth committed
8

luroth's avatar
luroth committed
9
10
def enhance_for_fft_sonyA9_rawpy(image_raw, pixel_shift):
    '''Gets a rawpy.RawPy object and generates 16 bit RGB, HSV, Lab and ExG/ExR representants
luroth's avatar
luroth committed
11

luroth's avatar
luroth committed
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
    :param image_raw: rawpy.RawPy object
    :param pixel_shift: Offset pixel used to cutout border pixel
    :return: tuple of RGB, HSV, and Lab (all 0..1 float32) and ExG and ExR (n..m float32)
    :return: descriptors as numpy array
    :return: descriptor names
    '''

    # Demosaic image using rawpy
    a_XYZ_16bit = image_raw.postprocess(
        output_bps=16,
        output_color=rawpy.ColorSpace.XYZ,
        demosaic_algorithm=0,
        use_camera_wb=True,
        no_auto_bright=True)

    # Cut image
    a_XYZ_16bit = a_XYZ_16bit[
                pixel_shift:a_XYZ_16bit.shape[0] - pixel_shift,
                pixel_shift:a_XYZ_16bit.shape[1] - pixel_shift,
                :
            ]

    # Convert XYZ to RGB space using opencv (cv2)
    a_RGB_16bit = cv2.cvtColor(a_XYZ_16bit, cv2.COLOR_XYZ2RGB)

    # Scale to 0...1
    a_RGB_16bitf = np.array(a_RGB_16bit / 2 ** 16, dtype=np.float32)

    # Convert to HSV space using opencv (cv2)
    a_HSV_16bitf = cv2.cvtColor(a_RGB_16bitf, cv2.COLOR_RGB2HSV)

    # Convert to LAB space using opencv (cv2)
    a_Lab_16bitf = cv2.cvtColor(a_RGB_16bitf, cv2.COLOR_RGB2Lab)

    # Calcualte vegetation indices: ExR and ExG and ExB
    R, G, B = cv2.split(a_RGB_16bitf)

    R = np.array(R, dtype=np.float32)
    G = np.array(G, dtype=np.float32)
    B = np.array(B, dtype=np.float32)

    normalizer = np.array(R + G + B)
    # Avoid division by zero
    normalizer[normalizer == 0] = 1
    normalizer = normalizer
    r, g, b = (R, G, B) / normalizer
    #print('rmin: ',np.min(r),'rmax: ',np.max(r),'gmin: ',np.min(g),'gmax: ',np.max(g),'bmin: ',np.min(b),'bmax: ',np.max(b))
    # ExR + ExG + ExB
    a_ExR = np.array(1.4 * r - b, dtype=np.float32)
    a_ExG = np.array(2.0 * g - r - b, dtype=np.float32)

    a_ExB = np.array(1.4 * b - g, dtype=np.float32) # Mao, W., Wang, Y., Wang, Y., 2003. Real-time detection of between-row weeds using machine vision. ASAE paper number 031004. The Society for Agricultural, Food, and Biological Systems, St. Joseph, MI.
    a_ExB_n = a_ExB + 1
    a_ExB_n = a_ExB_n/ 2.4

    RGB_intensities = R + G + B
    RGB_intensities = RGB_intensities - np.min(RGB_intensities)
luroth's avatar
luroth committed
69
    RGB_intensities = (RGB_intensities / 3) + 0.00000001
luroth's avatar
luroth committed
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

    RGB_VARI = (G - R) / ((G + R - B) + 0.00000001)  # Avoid non-zero values

    green_chromatic_coordinate = G / RGB_intensities
    green_chromatic_coordinate = np.nan_to_num(green_chromatic_coordinate)

    red_chromatic_coordinate = R / RGB_intensities
    red_chromatic_coordinate = np.nan_to_num(red_chromatic_coordinate)

    blue_chromatic_coordinate = B / RGB_intensities
    blue_chromatic_coordinate = np.nan_to_num(blue_chromatic_coordinate)

    H = a_HSV_16bitf[:, :, 0]
    S = a_HSV_16bitf[:, :, 1]
    V = a_HSV_16bitf[:, :, 2]

    L = a_Lab_16bitf[:, :, 0]
    a = a_Lab_16bitf[:, :, 1]
    b = a_Lab_16bitf[:, :, 2]

    # Return as tuple
    return ((a_RGB_16bitf, a_ExG, a_ExR, a_ExB, a_ExB_n,
             R, G, B, RGB_intensities,
             RGB_VARI,
             green_chromatic_coordinate, red_chromatic_coordinate, blue_chromatic_coordinate,
             H, S, V,
luroth's avatar
luroth committed
96
             L, a, b))
luroth's avatar
luroth committed
97
98
99


def postprocess_sonyA9_RAW(path_image, pixel_shift=0):
luroth's avatar
luroth committed
100
101
102
103
104
105
106
107
108
109
110
111
    # Read RAW file
    image_raw = rawpy.imread(path_image)

    # Calculate RGB using conventional debayering
    # Debayer and expose RAW image to XYZ space using rawpy
    XYZ_conventional = image_raw.postprocess(output_bps=16, output_color=rawpy.ColorSpace.XYZ, demosaic_algorithm=0,
                                             use_camera_wb=True, no_auto_bright=True)
    # Convert XYZ to RGB space
    RGB_conventional = cv2.cvtColor(XYZ_conventional, cv2.COLOR_XYZ2RGB)

    return RGB_conventional

luroth's avatar
bugfix    
luroth committed
112
def read_sonyA9_RAW(path_image):
luroth's avatar
luroth committed
113
114
    # Read RAW file
    image_raw = rawpy.imread(path_image)
luroth's avatar
bugfix    
luroth committed
115
116
117
118
    return image_raw

def enhance_sonyA9_rawpy(image_raw, pixel_shift=0):
    '''Reads a sony alpha 9 RAW file and enhances it with additional descriptors'''
luroth's avatar
luroth committed
119
120
121
122
123
124
125
126

    # Create mask for R, G, and B channel that correspond to the locations of the pixels in the Bayer matrix
    mask_R = np.invert(image_raw.raw_colors_visible == 0)
    mask_G = np.isin(image_raw.raw_colors_visible, (1, 3), invert=True)
    mask_B = np.invert(image_raw.raw_colors_visible == 2)

    # Apply mask to RAW file
    # Stack channels
luroth's avatar
luroth committed
127
    RGB_raw = np.stack(np.tile(image_raw.raw_image_visible, [3, 1, 1]), axis=2)
luroth's avatar
luroth committed
128
129
130
131
132
133
134
135
136
    # Stack masks
    mask_RGB = np.stack([mask_R, mask_G, mask_B], axis=2)
    # Mask stacked RAW
    RGB_raw_masked = np.ma.masked_array(RGB_raw, mask_RGB, fill_value=0)
    # Fill zeros for positions where no specific info for this color is present
    RGB_raw_filled = RGB_raw_masked.filled()

    # Calculate R and B for G positions
    # Kernels
luroth's avatar
luroth committed
137
    kernel_mean = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) * 1 / 2
luroth's avatar
luroth committed
138
139
140
141
142
143
144
145
146
147
148
    kernel_diff = np.array([[-1, -1, -1], [-1, 0, 1], [1, 1, 1]])
    # Extract color channels
    R, G, B = cv2.split(RGB_raw_filled)
    # Calculate R and B for G positions
    R_Gpos = cv2.filter2D(R, -1, kernel_mean)
    B_Gpos = cv2.filter2D(B, -1, kernel_mean)
    # Calculate differences in R and B for G position
    R_diff_Gpos = np.abs(cv2.filter2D(R, -1, kernel_diff))
    B_diff_Gpos = np.abs(cv2.filter2D(B, -1, kernel_diff))
    # Stack RGB bands
    RGBrb_Gpos = np.stack([R_Gpos, G, B_Gpos, R_diff_Gpos, B_diff_Gpos], axis=2)
luroth's avatar
luroth committed
149
    RGBrb_Gpos = np.ma.masked_array(RGBrb_Gpos, np.tile(mask_G[:, :, np.newaxis], 5), fill_value=0).filled()
luroth's avatar
luroth committed
150
151
152
153

    # Calculate RGB using conventional debayering
    # Debayer and expose RAW image to XYZ space using rawpy
    XYZ_conventional = image_raw.postprocess(output_bps=16, output_color=rawpy.ColorSpace.XYZ, demosaic_algorithm=0,
luroth's avatar
luroth committed
154
                                             use_camera_wb=True, no_auto_bright=True)
luroth's avatar
luroth committed
155
156
    # Convert XYZ to RGB space
    RGB_conventional = cv2.cvtColor(XYZ_conventional, cv2.COLOR_XYZ2RGB)
157
158

    # Convert to float
luroth's avatar
luroth committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
    RGB_conventional_float32 = np.array(RGB_conventional / 2 ** 16, dtype=np.float32)

    # Get HSV space
    HSV_conventional_float32 = cv2.cvtColor(RGB_conventional_float32, cv2.COLOR_RGB2HSV)
    HSV_conventional_float32[:, :, 0] = HSV_conventional_float32[:, :, 0] / 360
    HSV_conventional = np.uint16(HSV_conventional_float32 * 2 ** 16)

    # Get LAB space
    Lab_conventional_float32 = cv2.cvtColor(RGB_conventional_float32, cv2.COLOR_RGB2Lab)
    Lab_conventional_float32[:, :, 0] = Lab_conventional_float32[:, :, 0] / 100
    Lab_conventional_float32[:, :, 1] = (Lab_conventional_float32[:, :, 1] + 128) / 128
    Lab_conventional_float32[:, :, 2] = (Lab_conventional_float32[:, :, 2] + 128) / 128
    Lab_conventional = np.uint16(Lab_conventional_float32 * 2 ** 16)

    # Calcualte ExR and ExG
    R, G, B = cv2.split(RGB_conventional)
    normalizer = np.add(np.add(R, G), B)
176
    # Cheat: avoid div. by zero
luroth's avatar
luroth committed
177
178
179
180
181
182
183
184
    normalizer[normalizer == 0] = 1
    # ExR + ExG
    ExR = np.divide(np.subtract(1.4 * R, G), normalizer)
    ExG = np.divide(np.subtract(np.subtract(2.0 * G, R), B), normalizer)
    ExRG_conventional_float = np.stack([ExR, ExG], axis=2)
    ExRG_conventional = np.uint16(ExRG_conventional_float * 2 ** 16)

    # Concat all
luroth's avatar
luroth committed
185
186
187
    all_descriptors = np.concatenate(
        [RGBrb_Gpos, XYZ_conventional, RGB_conventional, HSV_conventional, Lab_conventional, ExRG_conventional], axis=2)
    all_descriptors = all_descriptors[pixel_shift:mask_G.shape[0] - pixel_shift, pixel_shift:mask_G.shape[1] - pixel_shift, :]
luroth's avatar
luroth committed
188
    # Names
luroth's avatar
luroth committed
189
190
    descriptor_names = ["rawR", "rawG", "rawB", "rawR_diff", "rawB_diff", "X", "Y", "Z", "sR", "sG", "sB", "H", "S",
                        "V", "L", "a", "b", "ExR", "ExG"]
luroth's avatar
luroth committed
191
    # Mask
luroth's avatar
luroth committed
192
193
    raw_mask = mask_G[pixel_shift:mask_G.shape[0] - pixel_shift, pixel_shift:mask_G.shape[1] - pixel_shift]
    return (all_descriptors, descriptor_names, raw_mask)
luroth's avatar
luroth committed
194
195


luroth's avatar
bugfix    
luroth committed
196
197
def preview_sonyA9_rawpy(image_raw, pixel_shift=0):
    '''Gets a sony alpha 9 RAW file and generates a 8bit preview tiff'''
luroth's avatar
luroth committed
198
199
200

    image_8bit = image_raw.postprocess(output_bps=8, output_color=rawpy.ColorSpace.sRGB, demosaic_algorithm=0)

luroth's avatar
luroth committed
201
202
    return (image_8bit[pixel_shift:image_8bit.shape[0] - pixel_shift, pixel_shift:image_8bit.shape[1] - pixel_shift])

luroth's avatar
stuff    
luroth committed
203
204
205
206
207
208
209
210
211
212
213
def read_canon_5D_Mark_II_RAW(path_image):
    # Read RAW file
    image_raw = rawpy.imread(path_image)
    return image_raw

def preview_canon_5D_Mark_II_RAW_rawpy(image_raw, pixel_shift=0):
    '''Gets a canon EOS 5D Mark II RAW file and generates a 8bit preview tiff'''

    image_8bit = image_raw.postprocess(output_bps=8, output_color=rawpy.ColorSpace.sRGB, demosaic_algorithm=0)

    return (image_8bit[pixel_shift:image_8bit.shape[0] - pixel_shift, pixel_shift:image_8bit.shape[1] - pixel_shift])
luroth's avatar
luroth committed
214
215

if __name__ == "__main__":
luroth's avatar
luroth committed
216
    print("Nothing to run")