gagan3012 commited on
Commit
a29a059
1 Parent(s): 5d9bedf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -0
app.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import cv2
3
+ import matplotlib.pyplot as plt
4
+ import numpy as np
5
+ import torch
6
+ import torchvision
7
+ import kornia as K
8
+
9
+ def inference(file1,num_iters):
10
+ img: np.ndarray = cv2.imread(file1.name)
11
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0
12
+ img = img + np.random.normal(loc=0.0, scale=0.1, size=img.shape)
13
+ img = np.clip(img, 0.0, 1.0)
14
+
15
+ # convert to torch tensor
16
+ noisy_image = K.utils.image_to_tensor(img).squeeze()
17
+
18
+ class TVDenoise(torch.nn.Module):
19
+ def __init__(self, noisy_image):
20
+ super(TVDenoise, self).__init__()
21
+ self.l2_term = torch.nn.MSELoss(reduction='mean')
22
+ self.regularization_term = K.losses.TotalVariation()
23
+ # create the variable which will be optimized to produce the noise free image
24
+ self.clean_image = torch.nn.Parameter(data=noisy_image.clone(), requires_grad=True)
25
+ self.noisy_image = noisy_image
26
+
27
+ def forward(self):
28
+ # print(self.l2_term(self.clean_image, self.noisy_image))
29
+ # print(self.regularization_term(self.clean_image))
30
+ return self.l2_term(self.clean_image, self.noisy_image) + 0.0001 * self.regularization_term(self.clean_image)
31
+
32
+ def get_clean_image(self):
33
+ return self.clean_image
34
+
35
+
36
+ tv_denoiser = TVDenoise(noisy_image)
37
+
38
+ # define the optimizer to optimize the 1 parameter of tv_denoiser
39
+ optimizer = torch.optim.SGD(tv_denoiser.parameters(), lr=0.1, momentum=0.9)
40
+
41
+ for i in range(int(num_iters)):
42
+ optimizer.zero_grad()
43
+ loss = torch.mean(tv_denoiser())
44
+ if i % 50 == 0:
45
+ print("Loss in iteration {} of {}: {:.3f}".format(i, num_iters, loss.item()))
46
+ loss.backward()
47
+ optimizer.step()
48
+
49
+ img_clean: np.ndarray = K.utils.tensor_to_image(tv_denoiser.get_clean_image())
50
+
51
+ return img, img_clean
52
+
53
+ examples = [
54
+ ]
55
+
56
+
57
+ inputs = [
58
+ gr.Image(type='file', label='Input Image'),
59
+ gr.Slider(minimum=50, maximum=10000, step=50, default=500, label="num_iters")
60
+ ]
61
+
62
+ outputs = [
63
+ gr.Image(type='file', label='Noised Image'),
64
+ gr.Image(type='file', label='Denoised Image'),
65
+ ]
66
+
67
+ title = "Image Stitching using Kornia and LoFTR"
68
+
69
+ demo_app = gr.Interface(
70
+ fn=inference,
71
+ inputs=inputs,
72
+ outputs=outputs,
73
+ title=title,
74
+ examples=examples,
75
+ theme='huggingface',
76
+ )
77
+ demo_app.launch(debug=True)