from future import absolute_import, division, print_function
import os
import random
import numpy as np
from PIL import Image
from skimage.filters import gaussian, sobel
from scipy.interpolate import griddata
import cv2
import torch
from torchvision import transforms
import multiprocessing as mp
from utils import transfer_color
import matplotlib.pyplot as plt
import sys
def pil_loader(path):
print(path)
with open(path, 'rb') as f:
from PIL import Image
with Image.open(f) as img:
return img.convert('RGB')
def read_pfm(file):
with open(file, 'rb') as fh:
fh.readline()
width, height = str(fh.readline().rstrip())[2:-1].split()
fh.readline()
disp = np.fromfile(fh, '<f')
return np.flipud(disp.reshape(int(height), int(width)))
def preprocess(inputs, feed_width, feed_height, disable_normalisation, has_gt, to_tensor, is_train, brightness, contrast, saturation, hue):
if is_train and random.random() > 0.5:
color_aug = transforms.ColorJitter.get_params(
brightness, contrast, saturation, hue)
for key in ['image', 'stereo_image']:
inputs[key] = color_aug(inputs[key])
code
for key in ['image', 'stereo_image']:
if disable_normalisation:
inputs[key] = to_tensor(inputs[key])
else:
inputs[key] = (to_tensor(inputs[key]) - 0.45) / 0.225
if has_gt:
inputs['disparity'] = torch.from_numpy(inputs['disparity']).float()
if inputs.get('mono_disparity') is not None:
inputs['mono_disparity'] = torch.from_numpy(inputs['mono_disparity']).float()
Traceback (most recent call last):
File "/home/notebook/data/group/Ruby/stereo-from-mono/datasets/my_dataset_copy_2.py", line 308, in
for count in tqdm(range(count_start, count_end), desc='Processing Images')
TypeError: 'module' object is not callable
if name == "main":
data_path = "/home/notebook/data/group/Ruby/langan_datasets/nightlangan3_deblur/"
np.random.seed(42)
code
itxt_path = '/home/notebook/data/group/Ruby/stereo-from-mono/langan_img.txt'
dtxt_path = '/home/notebook/data/group/Ruby/stereo-from-mono/langan_depth.txt'
all_img = []
all_depth = []
with open(itxt_path, 'r') as fi:
for li in fi.readlines():
li = li.strip('\n')
all_img.append(li)
with open(dtxt_path, 'r') as fd:
for ld in fd.readlines():
ld = ld.strip('\n')
all_depth.append(ld)
img_path = all_img
depth_path = all_depth
save_path = r"/home/notebook/data/group/Ruby/langan_datasets/langan"
# count_start, count_end = 0, 356
count_start, count_end = 0, len(all_img)
feed_height, feed_width, process_width = 1024, 768, 768 + 20
disable_background, is_train = False, True
disable_normalisation, has_gt, disable_sharpening = True, True, True
max_disparity = 20
disable_synthetic_augmentation = True
brightness, contrast, saturation, hue = (0.8, 1.2), (0.8, 1.2), (0.8, 1.2), (-0.1, 0.1)
np_xs, np_ys = np.meshgrid(np.arange(process_width), np.arange(feed_height))
to_tensor = transforms.ToTensor()
keep_aspect_ratio = True
data_paths = (img_path, depth_path)
num_workers = 16
with mp.Pool(processes=num_workers) as pool:
results = [pool.apply_async(worker,
args=(save_path, data_paths, max_disparity,
disable_background, disable_sharpening,
disable_synthetic_augmentation, process_width,
feed_height, feed_width, disable_normalisation,
has_gt, to_tensor, is_train, brightness, contrast,
saturation, hue, np_xs, np_ys, keep_aspect_ratio, count))
for count in range(count_start, count_end)]
processed_data = [p.get() for p in results]
print("Processing complete.")
It looks like you've shared a complete Python script designed for processing images and depth data, possibly for training a neural network on stereo vision tasks. Below is a summary of the code structure along with explanations of key components.
Overview
The script reads images and corresponding disparity maps (depth maps), processes them, applies various augmentations, and saves the processed images to a specified directory. The use of multiprocessing enables faster execution, especially beneficial when handling large datasets.
Key Components
Imports and Setup:
The script imports various libraries such as numpy, PIL, cv2, torch, and others for image processing and manipulation.
It defines functions for loading images and disparities, augmenting data, and resizing/cropping images.
Image Loading:
The pil_loader function loads images from specified paths using the PIL library.
The read_pfm function reads disparity maps from PFM files.
Data Preparation:
Functions like load_images, load_disparity, preprocess, prepare_sizes, crop_all, and resize_all prepare the input images and disparity maps for training/processing.
Disparity Processing:
The process_disparity function adjusts disparity values, applies sharpening where necessary, and resamples the disparity map.
Image Projection:
The project_image function creates a stereo view by projecting one image onto another using the modified disparity map. This function handles occlusions as well.
Augmentation:
Functions like augment_synthetic_image apply synthetic noise or Gaussian blur to the images for data augmentation.
Processing and Saving:
The process_and_save function handles the final processing of the data and saves the resultant images and disparity maps to disk.
Worker Function:
The worker function orchestrates the loading, processing, and saving of data for each image-disparity pair. It is called in a multiprocessing context to parallelize the workload.
Main Execution Block:
Reads paths from text files containing image and disparity paths.
Initializes parameters like image sizes, normalization flags, augmentation settings, and begins processing using multiprocessing.
Running the Script
To run the script, you should ensure that all necessary libraries are installed (e.g., PIL, opencv-python, torch, scikit-image, and numpy).
Specify the paths for your data correctly, including the images and disparities.
Adjust parameters as needed for your specific dataset and desired processing outputs.
Possible Improvements
Error Handling: Adding error handling throughout the script could enhance robustness, especially when loading files.
Configurability: Instead of hardcoded values, consider using a configuration file (like JSON or YAML) to allow easier adjustments of parameters.
Logging: Integrate logging instead of using print statements to make debugging and tracking progress easier.
Testing: Implement unit tests for key functions to ensure they work as expected.
This script is advanced and seems well-optimized for its purpose, but it also includes many specific parameters which can be tuned based on the characteristics of the dataset used for training or testing.
from tqdm import tqdm
import os
import random
import numpy as np
from PIL import Image
from skimage.filters import gaussian, sobel
from scipy.interpolate import griddata
import cv2
import torch
from torchvision import transforms
import multiprocessing as mp
from utils import transfer_color
import matplotlib.pyplot as plt
import sys