Bob-Shih_liteon commited on
Commit
a61fdc0
·
1 Parent(s): 371a737

add SNR table and code formatter

Browse files
Files changed (2) hide show
  1. app.py +165 -57
  2. customs/SNR.png +3 -0
app.py CHANGED
@@ -1,37 +1,59 @@
1
  import gradio as gr
2
  from customs.utils import rgb2rggb, rggb2rgb, CV72fillCurve, rggb2rgb_np
3
- import torch,os
4
  import numpy as np
5
  from openvino.inference_engine import IECore
6
  from cryptography.fernet import Fernet
7
 
8
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
9
  CONFIG = {
10
  "noise_levels": [4, 6, 8, 10, 12],
11
  "raw_images": [
12
  "data/RAW/noisy/4Card_Gain160_E30.npy",
13
  "data/RAW/noisy/4Card_Gain180_E30.npy",
14
  "data/RAW/noisy/4Card_Gain200_E30.npy",
15
- "data/RAW/noisy/4Card_Gain220_E30.npy"
16
  ],
17
  "weights": [
18
  "customs/weights/model_ir_0.xml.encrypted",
19
  "customs/weights/model_ir_1.xml.encrypted",
20
  "customs/weights/model_ir_2.xml.encrypted",
21
- "customs/weights/model_ir_3.xml.encrypted"
22
  ],
23
- "SIDD_model_weights": "customs/weights/model_ir_SIDD.xml.encrypted"
24
  }
25
 
 
26
  def main():
27
  with gr.Blocks() as demo:
28
- create_text("Raw Image Denoiser",size=10)
29
- create_text("Data Detail : Collect images of imx678 image sensor and analyze the noise composition and distribution",size=5)
30
- create_text("Model Detail : ",size=5)
31
- create_text("Synthesis Data : We have the technology to analyze and apply noise",size=3)
32
- create_text("Our Denoiser : Our model architecture is trained on synthesize noise with SD images",size=3)
33
- create_text("SIDD Denoiser : Our model architecture is trained on SIDD dataset",size=3)
34
- create_text("Community : Any questions please contact us (tim.liu@liteon.com)",size=3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  with gr.Tab("Synthesis"):
36
  with gr.Column():
37
  with gr.Row():
@@ -42,17 +64,29 @@ def main():
42
  use_synthesis = gr.Checkbox(label="Use synthesis", value=True)
43
  image_button1 = gr.Button("Inference")
44
  # create_text("SIDD Denoiser : Our model architecture is trained to SIDD dataset")
45
- image_input1 = [image1, noise_level1, denoise_level1, use_synthesis]
46
-
 
 
 
 
 
47
  with gr.Row():
48
  SynthesisNoise1 = gr.Image(label="Synthesis noise")
49
  OurDenoise1 = gr.Image(label="Our denoiser result")
50
  with gr.Row():
51
  SIDDDenoise1 = gr.Image(label="SIDD denoiser result")
52
- examples1 = gr.Examples(examples=[["data/RGB/4Card.png"],["data/RGB/Color.png"],["data/RGB/Focus.png"]],inputs=image_input1)
 
 
 
 
 
 
 
53
 
54
  image_output1 = [SynthesisNoise1, OurDenoise1, SIDDDenoise1]
55
-
56
  with gr.Tab("Real"):
57
  with gr.Column():
58
  with gr.Row():
@@ -67,11 +101,14 @@ def main():
67
  SIDDDenoise2 = gr.Image(label="SIDD denoiser result")
68
 
69
  image_output2 = [RealRow, OurDenoise2, SIDDDenoise2]
70
-
71
- image_button1.click(denoise_synthesis, inputs=image_input1, outputs=image_output1)
 
 
72
  image_button2.click(denoise_real, inputs=image_input2, outputs=image_output2)
73
  demo.launch()
74
 
 
75
  def decrypt_model(encrypted_file_path, decrypted_file_path):
76
  """
77
  解密模型文件
@@ -84,14 +121,16 @@ def decrypt_model(encrypted_file_path, decrypted_file_path):
84
  # get env key
85
  key = os.getenv("IRModelKey")
86
  cipher_suite = Fernet(key)
87
- with open(encrypted_file_path, 'rb') as file:
88
  encrypted_data = file.read()
89
  decrypted_data = cipher_suite.decrypt(encrypted_data)
90
- with open(decrypted_file_path, 'wb') as file:
91
  file.write(decrypted_data)
92
 
 
93
  class IEModel:
94
  """Class for inference of models in the Inference Engine format"""
 
95
  def __init__(self, exec_net, inputs_info, input_key, output_key, switch_rb=True):
96
  self.net = exec_net
97
  self.inputs_info = inputs_info
@@ -112,8 +151,9 @@ class IEModel:
112
 
113
  def forward_async(self, img):
114
  id = len(self.reqs_ids)
115
- self.net.start_async(request_id=id,
116
- inputs={self.input_key: self._preprocess(img)})
 
117
  self.reqs_ids.append(id)
118
 
119
  def grab_all_async(self):
@@ -128,40 +168,84 @@ class IEModel:
128
  def get_input_shape(self):
129
  """Returns an input shape of the wrapped IE model"""
130
  return self.inputs_info[self.input_key].input_data.shape
131
-
132
- def load_ie_model(model_xml, device, plugin_dir, cpu_extension='', num_reqs=1, **kwargs):
 
 
 
133
  """Loads a model in the Inference Engine format"""
134
- if cpu_extension and 'CPU' in device:
135
- IECore().add_extension(cpu_extension, 'CPU')
136
  # Read IR
137
  net = IECore().read_network(model_xml, os.path.splitext(model_xml)[0] + ".bin")
138
 
139
- assert len(net.input_info) == 1 or len(net.input_info) == 2, \
140
- "Supports topologies with only 1 or 2 inputs"
141
- assert len(net.outputs) == 1 or len(net.outputs) == 4 or len(net.outputs) == 5, \
142
- "Supports topologies with only 1, 4 or 5 outputs"
 
 
143
 
144
  input_blob = next(iter(net.input_info))
145
  out_blob = next(iter(net.outputs))
146
  net.batch_size = 1
147
 
148
  # Loading model to the plugin
149
- exec_net = IECore().load_network(network=net, device_name=device, num_requests=num_reqs)
 
 
150
  model = IEModel(exec_net, net.input_info, input_blob, out_blob, **kwargs)
151
  return model
152
 
153
- decrypt_model("customs/weights/model_ir_0.xml.encrypted", "customs/weights/model_ir_0_decrypted.xml")
154
- decrypt_model("customs/weights/model_ir_0.bin.encrypted", "customs/weights/model_ir_0_decrypted.bin")
155
- decrypt_model("customs/weights/model_ir_1.xml.encrypted", "customs/weights/model_ir_1_decrypted.xml")
156
- decrypt_model("customs/weights/model_ir_1.bin.encrypted", "customs/weights/model_ir_1_decrypted.bin")
157
- decrypt_model("customs/weights/model_ir_2.xml.encrypted", "customs/weights/model_ir_2_decrypted.xml")
158
- decrypt_model("customs/weights/model_ir_2.bin.encrypted", "customs/weights/model_ir_2_decrypted.bin")
159
- decrypt_model("customs/weights/model_ir_3.xml.encrypted", "customs/weights/model_ir_3_decrypted.xml")
160
- decrypt_model("customs/weights/model_ir_3.bin.encrypted", "customs/weights/model_ir_3_decrypted.bin")
161
- decrypt_model("customs/weights/model_ir_SIDD.xml.encrypted", "customs/weights/model_ir_SIDD_decrypted.xml")
162
- decrypt_model("customs/weights/model_ir_SIDD.bin.encrypted", "customs/weights/model_ir_SIDD_decrypted.bin")
163
- denoiseModelList = [load_ie_model(weight.split('.')[0] + "_decrypted.xml", "CPU", None, "")for weight in CONFIG["weights"]]
164
- SIDD_model = load_ie_model(CONFIG["SIDD_model_weights"].split('.')[0] + "_decrypted.xml", "CPU", None, "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
  def denoise_synthesis(image, noise_level=1, denoise_level=1, use_synthesis=True):
167
  # # Assuming image is a numpy array
@@ -173,33 +257,57 @@ def denoise_synthesis(image, noise_level=1, denoise_level=1, use_synthesis=True)
173
  # noiseImage = CV72fillCurve_np(rggb, CONFIG["noise_levels"][noise_level-1], CONFIG["noise_levels"][noise_level-1]+1)
174
  # rgb = rggb2rgb_np(noiseImage)
175
  # rgb = np.clip(rgb, 0, 1) # In-place clipping
176
-
177
  # torch function speed more than numpy
178
  rgb = torch.tensor(image).permute(2, 0, 1).unsqueeze(0)
179
  # rgb is not 1080 x 1920, resize it , test in 360 x 640
180
- rgb = torch.nn.functional.interpolate(rgb, size=(1080, 1920), mode='bilinear', align_corners=False)
181
- rggb = rgb2rggb(rgb.squeeze(0).permute(1, 2, 0)) / 255 # Normalize to [0, 1]
 
 
182
  if use_synthesis:
183
- rggb = CV72fillCurve(rggb, CONFIG["noise_levels"][noise_level-1], CONFIG["noise_levels"][noise_level-1]+1)
 
 
 
 
184
  rgb = rggb2rgb(rggb)
185
- rgb = rgb.clamp_(0, 1).cpu().numpy() # In-place clipping
186
  noiseImage = rggb.numpy()
187
- output = denoiseModelList[denoise_level-1].forward(noiseImage)
188
  SIDDOutput = SIDD_model.forward(noiseImage)
189
- return rgb, RGGB2RGBNumpy(output.squeeze().transpose(1, 2, 0)), RGGB2RGBNumpy(SIDDOutput.squeeze().transpose(1, 2, 0))
 
 
 
 
 
190
 
191
  def denoise_real(noise_level=1, denoise_level=1):
192
- noiseImage = np.load(CONFIG["raw_images"][noise_level-1]).astype(np.float32) / 65535.0
 
 
193
  # noiseImage = torch.from_numpy(noiseImage).permute(2, 0, 1).to(device).unsqueeze(0)
194
- output = denoiseModelList[denoise_level-1].forward(noiseImage)
195
  SIDDOutput = SIDD_model.forward(noiseImage)
196
- return RGGB2RGBNumpy(noiseImage), RGGB2RGBNumpy(output.squeeze().transpose(1, 2, 0)), RGGB2RGBNumpy(SIDDOutput.squeeze().transpose(1, 2, 0))
 
 
 
 
 
197
 
198
  def create_slider(label):
199
- return gr.Slider(minimum=1, maximum=4, value=1, step=1, interactive=True, label=label)
 
 
 
 
 
 
 
 
200
 
201
- def create_text(text,size = 3,color = "black"):
202
- gr.Markdown("<font size="+str(size)+" color="+str(color)+">"+str(text)+"</font>")
203
 
204
  def RGGB2RGBNumpy(numpyInput):
205
  # Assuming rggb2rgb is a function that can handle numpy arrays
@@ -208,6 +316,6 @@ def RGGB2RGBNumpy(numpyInput):
208
  output = np.clip(output, 0, 1)
209
  return output
210
 
 
211
  if __name__ == "__main__":
212
  main()
213
-
 
1
  import gradio as gr
2
  from customs.utils import rgb2rggb, rggb2rgb, CV72fillCurve, rggb2rgb_np
3
+ import torch, os
4
  import numpy as np
5
  from openvino.inference_engine import IECore
6
  from cryptography.fernet import Fernet
7
 
8
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9
  CONFIG = {
10
  "noise_levels": [4, 6, 8, 10, 12],
11
  "raw_images": [
12
  "data/RAW/noisy/4Card_Gain160_E30.npy",
13
  "data/RAW/noisy/4Card_Gain180_E30.npy",
14
  "data/RAW/noisy/4Card_Gain200_E30.npy",
15
+ "data/RAW/noisy/4Card_Gain220_E30.npy",
16
  ],
17
  "weights": [
18
  "customs/weights/model_ir_0.xml.encrypted",
19
  "customs/weights/model_ir_1.xml.encrypted",
20
  "customs/weights/model_ir_2.xml.encrypted",
21
+ "customs/weights/model_ir_3.xml.encrypted",
22
  ],
23
+ "SIDD_model_weights": "customs/weights/model_ir_SIDD.xml.encrypted",
24
  }
25
 
26
+
27
  def main():
28
  with gr.Blocks() as demo:
29
+ create_text("Raw Image Denoiser", size=10)
30
+ create_text(
31
+ "Data Detail : Collect images of imx678 image sensor and analyze the noise composition and distribution",
32
+ size=5,
33
+ )
34
+ create_text("Model Detail : ", size=5)
35
+ create_text(
36
+ "Synthesis Data : We have the technology to analyze and apply noise", size=3
37
+ )
38
+ create_text(
39
+ "Our Denoiser : Our model architecture is trained on synthesize noise with SD images",
40
+ size=3,
41
+ )
42
+ create_text(
43
+ "SIDD Denoiser : Our model architecture is trained on SIDD dataset", size=3
44
+ )
45
+ create_text(
46
+ "Community : Any questions please contact us (tim.liu@liteon.com)", size=3
47
+ )
48
+ # Add picture here
49
+ with gr.Row():
50
+ with gr.Column(scale=1): # Empty column to create space on the left
51
+ pass
52
+ with gr.Column(scale=2): # Column containing the image
53
+ gr.Image(label="SNR", value="customs/SNR.png", height=260)
54
+ with gr.Column(scale=1): # Empty column to create space on the right
55
+ pass
56
+
57
  with gr.Tab("Synthesis"):
58
  with gr.Column():
59
  with gr.Row():
 
64
  use_synthesis = gr.Checkbox(label="Use synthesis", value=True)
65
  image_button1 = gr.Button("Inference")
66
  # create_text("SIDD Denoiser : Our model architecture is trained to SIDD dataset")
67
+ image_input1 = [
68
+ image1,
69
+ noise_level1,
70
+ denoise_level1,
71
+ use_synthesis,
72
+ ]
73
+
74
  with gr.Row():
75
  SynthesisNoise1 = gr.Image(label="Synthesis noise")
76
  OurDenoise1 = gr.Image(label="Our denoiser result")
77
  with gr.Row():
78
  SIDDDenoise1 = gr.Image(label="SIDD denoiser result")
79
+ examples1 = gr.Examples(
80
+ examples=[
81
+ ["data/RGB/4Card.png"],
82
+ ["data/RGB/Color.png"],
83
+ ["data/RGB/Focus.png"],
84
+ ],
85
+ inputs=image_input1,
86
+ )
87
 
88
  image_output1 = [SynthesisNoise1, OurDenoise1, SIDDDenoise1]
89
+
90
  with gr.Tab("Real"):
91
  with gr.Column():
92
  with gr.Row():
 
101
  SIDDDenoise2 = gr.Image(label="SIDD denoiser result")
102
 
103
  image_output2 = [RealRow, OurDenoise2, SIDDDenoise2]
104
+
105
+ image_button1.click(
106
+ denoise_synthesis, inputs=image_input1, outputs=image_output1
107
+ )
108
  image_button2.click(denoise_real, inputs=image_input2, outputs=image_output2)
109
  demo.launch()
110
 
111
+
112
  def decrypt_model(encrypted_file_path, decrypted_file_path):
113
  """
114
  解密模型文件
 
121
  # get env key
122
  key = os.getenv("IRModelKey")
123
  cipher_suite = Fernet(key)
124
+ with open(encrypted_file_path, "rb") as file:
125
  encrypted_data = file.read()
126
  decrypted_data = cipher_suite.decrypt(encrypted_data)
127
+ with open(decrypted_file_path, "wb") as file:
128
  file.write(decrypted_data)
129
 
130
+
131
  class IEModel:
132
  """Class for inference of models in the Inference Engine format"""
133
+
134
  def __init__(self, exec_net, inputs_info, input_key, output_key, switch_rb=True):
135
  self.net = exec_net
136
  self.inputs_info = inputs_info
 
151
 
152
  def forward_async(self, img):
153
  id = len(self.reqs_ids)
154
+ self.net.start_async(
155
+ request_id=id, inputs={self.input_key: self._preprocess(img)}
156
+ )
157
  self.reqs_ids.append(id)
158
 
159
  def grab_all_async(self):
 
168
  def get_input_shape(self):
169
  """Returns an input shape of the wrapped IE model"""
170
  return self.inputs_info[self.input_key].input_data.shape
171
+
172
+
173
+ def load_ie_model(
174
+ model_xml, device, plugin_dir, cpu_extension="", num_reqs=1, **kwargs
175
+ ):
176
  """Loads a model in the Inference Engine format"""
177
+ if cpu_extension and "CPU" in device:
178
+ IECore().add_extension(cpu_extension, "CPU")
179
  # Read IR
180
  net = IECore().read_network(model_xml, os.path.splitext(model_xml)[0] + ".bin")
181
 
182
+ assert (
183
+ len(net.input_info) == 1 or len(net.input_info) == 2
184
+ ), "Supports topologies with only 1 or 2 inputs"
185
+ assert (
186
+ len(net.outputs) == 1 or len(net.outputs) == 4 or len(net.outputs) == 5
187
+ ), "Supports topologies with only 1, 4 or 5 outputs"
188
 
189
  input_blob = next(iter(net.input_info))
190
  out_blob = next(iter(net.outputs))
191
  net.batch_size = 1
192
 
193
  # Loading model to the plugin
194
+ exec_net = IECore().load_network(
195
+ network=net, device_name=device, num_requests=num_reqs
196
+ )
197
  model = IEModel(exec_net, net.input_info, input_blob, out_blob, **kwargs)
198
  return model
199
 
200
+
201
+ decrypt_model(
202
+ "customs/weights/model_ir_0.xml.encrypted",
203
+ "customs/weights/model_ir_0_decrypted.xml",
204
+ )
205
+ decrypt_model(
206
+ "customs/weights/model_ir_0.bin.encrypted",
207
+ "customs/weights/model_ir_0_decrypted.bin",
208
+ )
209
+ decrypt_model(
210
+ "customs/weights/model_ir_1.xml.encrypted",
211
+ "customs/weights/model_ir_1_decrypted.xml",
212
+ )
213
+ decrypt_model(
214
+ "customs/weights/model_ir_1.bin.encrypted",
215
+ "customs/weights/model_ir_1_decrypted.bin",
216
+ )
217
+ decrypt_model(
218
+ "customs/weights/model_ir_2.xml.encrypted",
219
+ "customs/weights/model_ir_2_decrypted.xml",
220
+ )
221
+ decrypt_model(
222
+ "customs/weights/model_ir_2.bin.encrypted",
223
+ "customs/weights/model_ir_2_decrypted.bin",
224
+ )
225
+ decrypt_model(
226
+ "customs/weights/model_ir_3.xml.encrypted",
227
+ "customs/weights/model_ir_3_decrypted.xml",
228
+ )
229
+ decrypt_model(
230
+ "customs/weights/model_ir_3.bin.encrypted",
231
+ "customs/weights/model_ir_3_decrypted.bin",
232
+ )
233
+ decrypt_model(
234
+ "customs/weights/model_ir_SIDD.xml.encrypted",
235
+ "customs/weights/model_ir_SIDD_decrypted.xml",
236
+ )
237
+ decrypt_model(
238
+ "customs/weights/model_ir_SIDD.bin.encrypted",
239
+ "customs/weights/model_ir_SIDD_decrypted.bin",
240
+ )
241
+ denoiseModelList = [
242
+ load_ie_model(weight.split(".")[0] + "_decrypted.xml", "CPU", None, "")
243
+ for weight in CONFIG["weights"]
244
+ ]
245
+ SIDD_model = load_ie_model(
246
+ CONFIG["SIDD_model_weights"].split(".")[0] + "_decrypted.xml", "CPU", None, ""
247
+ )
248
+
249
 
250
  def denoise_synthesis(image, noise_level=1, denoise_level=1, use_synthesis=True):
251
  # # Assuming image is a numpy array
 
257
  # noiseImage = CV72fillCurve_np(rggb, CONFIG["noise_levels"][noise_level-1], CONFIG["noise_levels"][noise_level-1]+1)
258
  # rgb = rggb2rgb_np(noiseImage)
259
  # rgb = np.clip(rgb, 0, 1) # In-place clipping
260
+
261
  # torch function speed more than numpy
262
  rgb = torch.tensor(image).permute(2, 0, 1).unsqueeze(0)
263
  # rgb is not 1080 x 1920, resize it , test in 360 x 640
264
+ rgb = torch.nn.functional.interpolate(
265
+ rgb, size=(1080, 1920), mode="bilinear", align_corners=False
266
+ )
267
+ rggb = rgb2rggb(rgb.squeeze(0).permute(1, 2, 0)) / 255 # Normalize to [0, 1]
268
  if use_synthesis:
269
+ rggb = CV72fillCurve(
270
+ rggb,
271
+ CONFIG["noise_levels"][noise_level - 1],
272
+ CONFIG["noise_levels"][noise_level - 1] + 1,
273
+ )
274
  rgb = rggb2rgb(rggb)
275
+ rgb = rgb.clamp_(0, 1).cpu().numpy() # In-place clipping
276
  noiseImage = rggb.numpy()
277
+ output = denoiseModelList[denoise_level - 1].forward(noiseImage)
278
  SIDDOutput = SIDD_model.forward(noiseImage)
279
+ return (
280
+ rgb,
281
+ RGGB2RGBNumpy(output.squeeze().transpose(1, 2, 0)),
282
+ RGGB2RGBNumpy(SIDDOutput.squeeze().transpose(1, 2, 0)),
283
+ )
284
+
285
 
286
  def denoise_real(noise_level=1, denoise_level=1):
287
+ noiseImage = (
288
+ np.load(CONFIG["raw_images"][noise_level - 1]).astype(np.float32) / 65535.0
289
+ )
290
  # noiseImage = torch.from_numpy(noiseImage).permute(2, 0, 1).to(device).unsqueeze(0)
291
+ output = denoiseModelList[denoise_level - 1].forward(noiseImage)
292
  SIDDOutput = SIDD_model.forward(noiseImage)
293
+ return (
294
+ RGGB2RGBNumpy(noiseImage),
295
+ RGGB2RGBNumpy(output.squeeze().transpose(1, 2, 0)),
296
+ RGGB2RGBNumpy(SIDDOutput.squeeze().transpose(1, 2, 0)),
297
+ )
298
+
299
 
300
  def create_slider(label):
301
+ return gr.Slider(
302
+ minimum=1, maximum=4, value=1, step=1, interactive=True, label=label
303
+ )
304
+
305
+
306
+ def create_text(text, size=3, color="black"):
307
+ gr.Markdown(
308
+ "<font size=" + str(size) + " color=" + str(color) + ">" + str(text) + "</font>"
309
+ )
310
 
 
 
311
 
312
  def RGGB2RGBNumpy(numpyInput):
313
  # Assuming rggb2rgb is a function that can handle numpy arrays
 
316
  output = np.clip(output, 0, 1)
317
  return output
318
 
319
+
320
  if __name__ == "__main__":
321
  main()
 
customs/SNR.png ADDED

Git LFS Details

  • SHA256: 4dfa6f7cbb0ccd0369fcff163e45c9f19a449e2dfb053316e7b08c8017a4c959
  • Pointer size: 130 Bytes
  • Size of remote file: 90.6 kB