-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocessing.py
79 lines (63 loc) · 1.83 KB
/
preprocessing.py
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
# -*- coding: utf-8 -*-
"""
Created on Thu May 12 14:41:37 2022
@author: Tibbe Lukkassen
"""
import os
import torch
from skimage.io import imread
from skimage.color import rgb2hsv, rgb2gray
import torchvision as tv
from PIL import Image
import matplotlib.pyplot as plt
from matplotlib import cm
def fetch_files(path):
"""
Fetch all files in a directory
"""
files = []
for r, d, f in os.walk(path):
for file in f:
if file[-4:] == ".png":
files.append(os.path.join(r, file))
return files
def mask_vine(image):
hsv = rgb2hsv(image)
saturation_mask = hsv[:,:,1] > 0.34
hue_mask = (hsv[:,:,0] > 0.080) * (hsv[:,:, 0] < 0.360)
return rgb2gray(image) * saturation_mask * hue_mask
def pad(img, size_max=256):
"""
Pads images to the specified size (height x width).
"""
width, height = img.size
pad_height = max(0, size_max - height)
pad_width = max(0, size_max - width)
pad_top = pad_height // 2
pad_bottom = pad_height - pad_top
pad_left = pad_width // 2
pad_right = pad_width - pad_left
return tv.transforms.functional.pad(img, (pad_left, pad_top, pad_right, pad_bottom), (0,0,0,256))
def transform_im(img):
image = mask_vine(img)
image = cm.gray(image)
image = torch.from_numpy(image)
image = image.T
transform = tv.transforms.Compose([
tv.transforms.ToPILImage(),
tv.transforms.Resize(255,max_size=256),
tv.transforms.Lambda(pad)
])
image=transform(image)
return image
files = fetch_files("./data")
index = 0
for file in files:
image = imread(file)
image = transform_im(image)
print(image.size)
plt.imshow(image)
plt.show()
if index > 0 and index % 10 == 0:
print(f"Processed {index} files out of {len(files)}")
index += 1