lfolle commited on
Commit
e5a19d6
1 Parent(s): 10b3587
.gitattributes CHANGED
@@ -1,2 +1,3 @@
1
  checkpoint filter=lfs diff=lfs merge=lfs -text
2
  *.png filter=lfs diff=lfs merge=lfs -text
 
1
  checkpoint filter=lfs diff=lfs merge=lfs -text
2
  *.png filter=lfs diff=lfs merge=lfs -text
3
+ .xlsx filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,12 +1,92 @@
1
- ---
2
- title: LDM SyntheticChestX Ray
3
- emoji: 📉
4
- colorFrom: indigo
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 3.12.0
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Xray Synthetic
2
+
3
+
4
+
5
+ ## Getting started
6
+
7
+ To make it easy for you to get started with GitLab, here's a list of recommended next steps.
8
+
9
+ Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
10
+
11
+ ## Add your files
12
+
13
+ - [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
14
+ - [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
15
+
16
+ ```
17
+ cd existing_repo
18
+ git remote add origin https://git5.cs.fau.de/mri/xray-synthetic.git
19
+ git branch -M main
20
+ git push -uf origin main
21
+ ```
22
+
23
+ ## Integrate with your tools
24
+
25
+ - [ ] [Set up project integrations](https://git5.cs.fau.de/mri/xray-synthetic/-/settings/integrations)
26
+
27
+ ## Collaborate with your team
28
+
29
+ - [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
30
+ - [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
31
+ - [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
32
+ - [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
33
+ - [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
34
+
35
+ ## Test and Deploy
36
+
37
+ Use the built-in continuous integration in GitLab.
38
+
39
+ - [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
40
+ - [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
41
+ - [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
42
+ - [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
43
+ - [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
44
+
45
+ ***
46
+
47
+ # Editing this README
48
+
49
+ When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
50
+
51
+ ## Suggestions for a good README
52
+ Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
53
+
54
+ ## Name
55
+ Choose a self-explaining name for your project.
56
+
57
+ ## Description
58
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
59
+
60
+ ## Badges
61
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
62
+
63
+ ## Visuals
64
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
65
+
66
+ ## Installation
67
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
68
+
69
+ ## Usage
70
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
71
+
72
+ ## Support
73
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
74
+
75
+ ## Roadmap
76
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
77
+
78
+ ## Contributing
79
+ State if you are open to contributions and what your requirements are for accepting them.
80
+
81
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
82
+
83
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
84
+
85
+ ## Authors and acknowledgment
86
+ Show your appreciation to those who have contributed to the project.
87
+
88
+ ## License
89
+ For open source projects, say how it is licensed.
90
+
91
+ ## Project status
92
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import gradio as gr
3
+
4
+ from utils import get_index_to_class_mapping
5
+ from load_data import generate_video_and_gradcam
6
+ from load_disease_info import disease_info
7
+ from PIL import Image
8
+
9
+
10
+ def display_name(pathology_str:str) -> str:
11
+ return disease_info(pathology_str)
12
+
13
+
14
+ def show_logo(path):
15
+ numpy_logo = np.asarray(Image.open(path))
16
+ return numpy_logo
17
+
18
+
19
+ with gr.Blocks() as demo:
20
+ with gr.Column():
21
+ gr.Markdown("# Latent diffusion model (LDM) for synthetic X-ray generation")
22
+ with gr.Row():
23
+ gr.HTML("<img width='200' height='200' src='/file/logos/FAU_TechFak_H_RGB_white.png' alt='FAU TechFak logo'>")
24
+ gr.HTML("<img width='200' height='200' src='/file/logos/LME_logo_english.png' alt='LME logo'>")
25
+ gr.HTML("<img width='200' height='200' src='/file/logos/MDD-logo-weiss.png' alt='Medical data donors logo'>")
26
+ with gr.Column():
27
+ gr.Markdown("To create a synthetic image select the pathology from the set below and click **Generate**.")
28
+ radio = gr.Radio(list(get_index_to_class_mapping().values()), label="Pathology")
29
+ btn = gr.Button("Generate")
30
+ with gr.Row():
31
+ with gr.Tab(label="Diffusion model"):
32
+ video = gr.Video(label="Diffusion steps & Generated X-ray")
33
+ with gr.Tab(label="GradCAM Overlay"):
34
+ gr_image = gr.Image()
35
+ with gr.Column():
36
+ gr.Markdown("## Description of the diseases")
37
+ disease_description = gr.HTML(label="Disease description")
38
+
39
+
40
+ def submit(radio_selection):
41
+ generated_video, generated_gradcam = generate_video_and_gradcam(radio_selection)
42
+ return {
43
+ video: generated_video,
44
+ gr_image: generated_gradcam,
45
+ disease_description: display_name(radio_selection)
46
+ }
47
+
48
+ btn.click(fn=submit, inputs=radio, outputs=[video, gr_image, disease_description])
49
+
50
+ demo.launch()
checkpoint ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8bcd64e481cb5f3027c2fc20458cea81b33239e411dd86c59ccaa66ea6ca5f8a
3
+ size 28504657
create_video.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ from PIL import Image
4
+
5
+
6
+ def noise_process(numpy_image, steps=149):
7
+ noisy_image_list = []
8
+ noisy_image = numpy_image
9
+ noisy_image_list.append(noisy_image)
10
+
11
+ for step in range(steps):
12
+ noise = 255 * np.random.normal(0, 0.07*(step+1) * 0.1, numpy_image.size).reshape(numpy_image.shape)
13
+ noisy_image = noisy_image + noise
14
+ noisy_image_list.append(noisy_image)
15
+ return noisy_image_list
16
+
17
+
18
+ def generate_video(numpy_image):
19
+ save_path = "result.mp4"
20
+ width = 256
21
+ hieght = 256
22
+ fps = 30
23
+ sec = 5
24
+ image_lst = noise_process(numpy_image)
25
+ image_lst = np.array([(i-np.min(i))/(np.max(i)-np.min(i)) for i in image_lst])
26
+ image_lst = np.round(image_lst * 255).astype(np.uint8)
27
+ copies = int((sec * fps) / len(image_lst))
28
+ spill_over = sec * fps - copies * len(image_lst)
29
+ image_lst = np.repeat(image_lst, copies, axis=0)
30
+ image_lst = np.concatenate((image_lst, image_lst[:spill_over]), axis=0)
31
+ image_lst = image_lst[::-1]
32
+ fourcc = cv2.VideoWriter_fourcc(*'MP42')
33
+ video = cv2.VideoWriter(save_path, fourcc, float(fps), (width, hieght))
34
+ for frame_count in range(fps * sec):
35
+ img = np.expand_dims(image_lst[frame_count],2)
36
+ video.write(img.astype(np.uint8))
37
+ video.release()
38
+ return save_path
39
+
40
+
41
+ if __name__ == "__main__":
42
+ im = Image.open(r"C:\Users\folle\Downloads\ldm_images\Atelectasis\0_4.png")
43
+ im_to_disp = np.array(im)
44
+ generate_video(im_to_disp)
disease_info.xlsx ADDED
Binary file (14.7 kB). View file
grad_cam.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ import numpy as np
4
+ from PIL import Image
5
+ from utils import *
6
+ from tqdm import tqdm
7
+ from gradcam import GradCAM, GradCAMpp
8
+ from overlay_image import overlay_numpy
9
+
10
+ DISEASES = [ 'Atelectasis',
11
+ 'Cardiomegaly',
12
+ 'Effusion',
13
+ 'Infiltration',
14
+ 'Mass',
15
+ 'Nodule',
16
+ 'Pneumonia',
17
+ 'Pneumothorax',
18
+ 'Consolidation',
19
+ 'Edema',
20
+ 'Emphysema',
21
+ 'Fibrosis',
22
+ 'Pleural Thickening',
23
+ 'Hernia' ]
24
+
25
+ class GradCamGenerator:
26
+ def __init__(self, model_path, layer, overlay=False):
27
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
28
+ self.model = self.load_model(model_path)
29
+ self.layer = layer
30
+ self.overlay = overlay # Overlay GC heatmaps with image
31
+ self.layer_module = self.model.get_submodule(layer)
32
+ self.gc_model2 = GradCAM(self.model, self.layer_module) # , device_ids=self.device)
33
+
34
+ def load_model(self, model_path, print_net=False):
35
+ checkpoint = torch.load(model_path, map_location=self.device)
36
+ model = checkpoint['model']
37
+ self.set_inplace_False(model)
38
+ if print_net:
39
+ print(model)
40
+ return model
41
+
42
+ def set_inplace_False(self, module):
43
+ for layer in module._modules.values():
44
+ if isinstance(layer, nn.ReLU):
45
+ layer.inplace = False
46
+ self.set_inplace_False(layer)
47
+
48
+ def generate_grad_cam(self, path):
49
+ img = self.pil_loader(path, 3)
50
+ input_image = self.transform_pil_to_tensor(img)
51
+ tclass = self.target_from_path(path)
52
+ #tmp_pred = self.model(input_image)
53
+ grayscale_cams = self.gc_model2(input=input_image, class_idx=tclass)
54
+ attribution = 255*grayscale_cams[0].detach().cpu().numpy().squeeze()
55
+ attribution /= attribution.max()
56
+ if self.overlay:
57
+ overlay_numpy(img, attribution, path)
58
+ #print()
59
+ return attribution
60
+
61
+ def target_from_path(self, path):
62
+ disease = path.split('/')[-2]
63
+ indx = DISEASES.index(disease) if disease!='No Finding' else 0
64
+ return torch.tensor(indx, device=self.device)
65
+
66
+ def save_img(self, image, input_path):
67
+ gc_filename = input_path[:-4]+'_gc'+input_path[-4:]
68
+ image_PIL = Image.fromarray(image).convert('L')
69
+ image_PIL.save(gc_filename)
70
+
71
+ def transform_pil_to_tensor(self, pil_image):
72
+ # ImageNet mean and std
73
+ mean = [0.485, 0.456, 0.406]
74
+ std = [0.229, 0.224, 0.225]
75
+
76
+ # transformation to be applied
77
+ transform = transforms.Compose([
78
+ transforms.Resize(224),
79
+ transforms.ToTensor(),
80
+ transforms.Normalize(mean, std)
81
+ ])
82
+ tensor = transform(pil_image).to(self.device)
83
+ return tensor.unsqueeze(0)
84
+
85
+ def pil_loader(self, path, n_channels):
86
+ # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
87
+ with open(path, 'rb') as f:
88
+ img = Image.open(f)
89
+ if n_channels == 1:
90
+ return img.convert('L')
91
+ elif n_channels == 3:
92
+ return img.convert('RGB')
93
+ else:
94
+ raise ValueError('Invalid value for parameter n_channels!')
95
+
96
+ def create_GC_from_folder(path, classifier='checkpoint', layer_name='features.norm5', overlay=True, override_gc=True):
97
+ GC = GradCamGenerator(classifier, layer_name, overlay=overlay)
98
+ folds = ['data/' + i for i in os.listdir(path) if 'No Finding' not in i][10:]
99
+ for cf in folds:
100
+ files = [cf+'/'+f for f in os.listdir(cf) if ('_gc' not in f and 'overlay' not in f and
101
+ (not os.path.exists(cf+'/'+f[:-4]+'_gc.png') or override_gc) and
102
+ (not os.path.exists(cf+'/'+f[:-4]+'_overlay.png') or not overlay))]
103
+ for cfil in tqdm(files):
104
+ GC.generate_grad_cam(cfil)
105
+ #GCmap = GC.generate_grad_cam(cfil)
106
+ #GC.save_img(GCmap, cfil)
107
+
108
+ if __name__=='__main__':
109
+ import matplotlib.pyplot as plt
110
+ path = 'data/'
111
+ create_GC_from_folder(path)
load_data.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import random
3
+ from PIL import Image
4
+ import os
5
+ from glob import glob
6
+
7
+ from utils import get_index_to_class_mapping
8
+ from create_video import generate_video
9
+
10
+
11
+ def load_overlay(pathology_str:str, index:int):
12
+ path = "data"
13
+ pathology_path = os.path.join(path, pathology_str, f"*_{index}_overlay.png")
14
+ pathology_path = glob(pathology_path)
15
+ if len(pathology_path) == 0:
16
+ return Image.fromarray(np.zeros((256, 256))).convert("L")
17
+ pathology_path = pathology_path[0]
18
+ im = Image.open(pathology_path)
19
+ return im
20
+
21
+ def generate_image(pathology_str:str):
22
+ pathology_idx = get_index_to_class_mapping()
23
+ pathology_idx_inverted = {v: k for k, v in pathology_idx.items()}
24
+ idx = random.randint(1, 100)
25
+ im = Image.open(os.path.join("data", pathology_str, f"{pathology_idx_inverted[pathology_str] - 1}_{idx}.png"))
26
+ im_to_disp = np.array(im)
27
+ return im_to_disp, idx
28
+
29
+ def generate_video_and_gradcam(pathology_str):
30
+ image, idx = generate_image(pathology_str)
31
+ video = generate_video(image)
32
+ generated_gradcam = load_overlay(pathology_str, idx)
33
+ return video, generated_gradcam
load_disease_info.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+
3
+
4
+ def disease_info(disease_index):
5
+ df = pd.read_excel(r"disease_info.xlsx")
6
+ df = df[df["Disease"] == disease_index].iloc[0]
7
+ html_text = ""
8
+ html_text += "<h1>Diagnosis</h1>\n" + "<p>" + str(df["Diagnosis"]) + "</p>" + "<br><br>"
9
+ html_text += "<h1>Cause</h1>\n" + "<p>" + str(df["Cause"]) + "</p>" + "<br><br>"
10
+ html_text += "<h1>Symptoms</h1>\n" + "<p>" + str(df["Symptoms"]) + "</p>" + "<br><br>"
11
+ html_text += "<h1>Treatment</h1>\n" + "<p>" + str(df["Treatment"]) + "</p>" + "<br><br>"
12
+ return html_text
13
+
14
+
15
+ if __name__ == "__main__":
16
+ disease_info("Pneumothorax")
logos/FAU_TechFak_H_RGB_blue.png ADDED

Git LFS Details

  • SHA256: 34b60df14a08b6b40765acd5339dfb6da7f4ce7a39e675fa7521b94fe3d68e3d
  • Pointer size: 131 Bytes
  • Size of remote file: 316 kB
logos/FAU_TechFak_H_RGB_white.png ADDED

Git LFS Details

  • SHA256: 881bea81d0459f80a2b54792a259b8b2aaf8b663f43cc156a755ad3c5b6c0164
  • Pointer size: 131 Bytes
  • Size of remote file: 291 kB
logos/LME_logo_english.png ADDED

Git LFS Details

  • SHA256: ef498ff34f4aa7e4d47585df175de8dcf75c3d20c6e38cd99eabd82904b8fdd6
  • Pointer size: 131 Bytes
  • Size of remote file: 261 kB
logos/MDD-logo-weiss.png ADDED

Git LFS Details

  • SHA256: 54784c68bf85d1335120109a307c7ad6f931bbe2fe6c60aaabcbb0544ce43ee6
  • Pointer size: 130 Bytes
  • Size of remote file: 28.7 kB
logos/MDD-logo.png ADDED

Git LFS Details

  • SHA256: 63b757e88b8ae5a9c464d8b0830028569e24adbe52520f179b1e66157b88215b
  • Pointer size: 130 Bytes
  • Size of remote file: 20.2 kB
overlay_image.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ import os
5
+
6
+ def overlay_file(im_path, heat_map_path):
7
+ im = np.array(Image.open(im_path))
8
+ heat_map = np.array(Image.open(heat_map_path))
9
+
10
+ overlay_numpy(im, heat_map, im_path)
11
+
12
+ def overlay_numpy(im, heat_map, path):
13
+ fig = plt.figure()
14
+ plt.imshow(im, 'gray', interpolation='none')
15
+ plt.imshow(heat_map, 'jet', interpolation='none', alpha=0.35),
16
+ plt.axis('off')
17
+ #plt.show()
18
+ file_name = os.path.splitext(path)[0] + '_overlay.png'
19
+ fig.savefig(file_name, bbox_inches='tight', pad_inches=0, transparent=True, dpi=1200)
20
+ plt.close()
21
+
22
+ if __name__=='__main__':
23
+ overlay_file('1_99.png', '1_99_gc.png')
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ torchvision
3
+ numpy
4
+ pandas
5
+ torch
6
+ ffprobe
7
+ pytorch-gradcam
8
+ PIL
9
+ tqdm
10
+ opencv-python
11
+ pandas
utils.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ import torch.nn as nn
5
+ from torchvision import models, transforms
6
+ from PIL import Image
7
+ from matplotlib import pyplot as plt
8
+
9
+
10
+ def get_index_to_class_mapping():
11
+ indices = np.arange(1, 16)
12
+ class_names = ['Atelectasis', 'Cardiomegaly', 'Consolidation', 'Edema', 'Effusion', 'Emphysema', 'Fibrosis',
13
+ 'Hernia', 'Infiltration', 'Mass', 'No Finding', 'Nodule', 'Pleural Thickening', 'Pneumonia',
14
+ 'Pneumothorax']
15
+ mapping = dict(zip(indices, class_names))
16
+ return mapping
17
+
18
+
19
+ def load_classifier_from_file(ckpt_file, location='cpu'):
20
+ checkpoint = torch.load(ckpt_file, map_location=location)
21
+ model = checkpoint['model']
22
+ return model
23
+
24
+
25
+ def transform_pil_to_tensor(pil_image, device='cpu'):
26
+ # ImageNet mean and std
27
+ mean = [0.485, 0.456, 0.406]
28
+ std = [0.229, 0.224, 0.225]
29
+
30
+ # transformation to be applied
31
+ transform = transforms.Compose([
32
+ transforms.Resize(224),
33
+ transforms.ToTensor(),
34
+ transforms.Normalize(mean, std)
35
+ ])
36
+
37
+ tensor = transform(pil_image).to(device)
38
+ return tensor
39
+
40
+
41
+ def noise_process(numpy_image, steps=10):
42
+ noisy_image_list = []
43
+ noisy_image = numpy_image
44
+ noisy_image_list.append(noisy_image)
45
+
46
+ for step in range(steps):
47
+ noise = 255 * np.random.normal(0, (step+1) * 0.1, numpy_image.size).reshape(numpy_image.shape)
48
+ noisy_image = noisy_image + noise
49
+ noisy_image_list.append(noisy_image)
50
+ plt.imshow(noisy_image, cmap='gray')
51
+ plt.show()
52
+
53
+ return noisy_image_list