|
| 1 | +import torch |
| 2 | +import torchvision |
| 3 | +import torchvision.datasets as datasets |
| 4 | +from torchvision.transforms import v2 |
| 5 | +from torch.utils.data import DataLoader |
| 6 | +from torchvision.datasets.folder import default_loader |
| 7 | +import cv2 |
| 8 | +import numpy as np |
| 9 | +import os |
| 10 | + |
| 11 | +NUM_WORKERS = os.cpu_count() |
| 12 | + |
| 13 | +def create_dataloaders(train_path: str, |
| 14 | + test_path: str, |
| 15 | + batch_size: int, |
| 16 | + pre_proc_type: str, |
| 17 | + num_workers: int = NUM_WORKERS): |
| 18 | + |
| 19 | + # Importing the datasets with imageFolder |
| 20 | + train_ds = HistogramDataset(train_path, pre_proc_type) |
| 21 | + test_ds = HistogramDataset(test_path, pre_proc_type) |
| 22 | + |
| 23 | + # Creating the dataloaders |
| 24 | + train_dataloader = DataLoader(train_ds, batch_size=batch_size, num_workers=num_workers, shuffle=True, pin_memory=True, drop_last=False) |
| 25 | + test_dataloader = DataLoader(test_ds, batch_size=batch_size, num_workers=num_workers, shuffle=False, pin_memory=True, drop_last=False) |
| 26 | + |
| 27 | + classes = train_ds.classes |
| 28 | + |
| 29 | + return train_dataloader, test_dataloader, classes |
| 30 | + |
| 31 | + |
| 32 | +class HistogramDataset(torchvision.datasets.ImageFolder): |
| 33 | + def __init__(self, root, preproc_type, loader=default_loader, is_valid_file=None): |
| 34 | + super(HistogramDataset, self).__init__(root=root, loader=loader, is_valid_file=is_valid_file) |
| 35 | + self.pre_proc_type = preproc_type |
| 36 | + |
| 37 | + def __getitem__(self, index): |
| 38 | + image_path, target = self.samples[index] |
| 39 | + im = cv2.imread(image_path) |
| 40 | + |
| 41 | + im_nonoise = cv2.GaussianBlur(im, (3, 3), 1) |
| 42 | + if(self.pre_proc_type == 'lab' or self.pre_proc_type=='rgb'): |
| 43 | + if(self.pre_proc_type == 'lab'): |
| 44 | + prep_image = (im_nonoise * 1. / 255).astype(np.float32) |
| 45 | + im_lab = cv2.cvtColor(prep_image, cv2.COLOR_BGR2LAB) |
| 46 | + hist = calc_hists(im_lab, self.pre_proc_type) |
| 47 | + |
| 48 | + # Setting up a matrix |
| 49 | + hist = np.stack([h for h in hist], axis=-1) |
| 50 | + # hist = np.stack([h for h in hist], axis=-1) |
| 51 | + hist = np.squeeze(hist) |
| 52 | + |
| 53 | + # Normalizing the vector with L2 normalization |
| 54 | + norm = np.linalg.norm(hist) |
| 55 | + norm_hist = hist / norm |
| 56 | + # you need to convert img from np.array to torch.tensor |
| 57 | + # this has to be done CAREFULLY! |
| 58 | + sample = torchvision.transforms.ToTensor()(norm_hist) |
| 59 | + return sample, target |
| 60 | + |
| 61 | + |
| 62 | +# Define a function to compute the histogram of the image (channel by channel) |
| 63 | +def calc_hists(img: np.ndarray, hist_type) -> list: |
| 64 | + """ |
| 65 | + Calculates the histogram of the image (channel by channel). |
| 66 | +
|
| 67 | + Args: |
| 68 | + img (numpy.ndarray): image to calculate the histogram |
| 69 | +
|
| 70 | + Returns: |
| 71 | + list: list of histograms |
| 72 | + """ |
| 73 | + |
| 74 | + assert img.ndim == 3, "The image must have 3 dimensions: (Height,Width,Channels)" |
| 75 | + |
| 76 | + ch_1 = img[..., 0] |
| 77 | + ch_2 = img[..., 1] |
| 78 | + ch_3 = img[..., 2] |
| 79 | + |
| 80 | + # Color image |
| 81 | + if hist_type == 'rgb': |
| 82 | + # Get the 3 channels |
| 83 | + # Compute the histogram for each channel. Please, bear in mind that in the "Range" parameter, the upper bound is exclusive. So, for considering values in the range [0,255] we must pass [0,256]. https://docs.opencv.org/3.4/d8/dbc/tutorial_histogram_calculation.html |
| 84 | + blue_hist = cv2.calcHist([ch_1], [0], None, [16], [0, 256]) |
| 85 | + red_hist = cv2.calcHist([ch_2], [0], None, [16], [0, 256]) |
| 86 | + green_hist = cv2.calcHist([ch_3], [0], None, [16], [0, 256]) |
| 87 | + |
| 88 | + return [blue_hist, green_hist, red_hist] |
| 89 | + # Greyscale image |
| 90 | + elif hist_type == 'lab': |
| 91 | + |
| 92 | + L_hist = cv2.calcHist([ch_1], [0], None, [16], [0, 100]) |
| 93 | + a_hist = cv2.calcHist([ch_2], [0], None, [16], [-128, 128]) |
| 94 | + b_hist = cv2.calcHist([ch_3], [0], None, [16], [-128, 128]) |
| 95 | + |
| 96 | + return [L_hist, a_hist, b_hist] |
| 97 | + else: |
| 98 | + raise Exception("The image must have either 1 (greyscale image) or 3 (color image) channels") |
| 99 | + |
| 100 | + |
0 commit comments