pix2pixmodel = None
midasmodel = None
srlnet = None
leresmodel = None
factor = None
whole_size_threshold = 3000 # R_max from the paper
GPU_threshold = 1600 - 32 # Limit for the GPU (NVIDIA RTX 2080), can be adjusted
MAIN PART OF OUR METHOD
def run(dataset, option):
code
# Load merge network
opt = TestOptions().parse()
global pix2pixmodel
pix2pixmodel = Pix2Pix4DepthModel(opt)
pix2pixmodel.save_dir = './pix2pix/checkpoints/mergemodel'
pix2pixmodel.load_networks('latest')
pix2pixmodel.eval()
# Decide which depth estimation network to load
if option.depthNet == 0:
midas_model_path = "models/model.pt"
global midasmodel
midasmodel = MidasNet(midas_model_path, non_negative=True)
midasmodel.to(device)
midasmodel.eval()
elif option.depthNet == 1:
global srlnet
srlnet = DepthNet.DepthNet()
srlnet = torch.nn.DataParallel(srlnet, device_ids=[0]).cuda()
checkpoint = torch.load('structuredrl/model.pth.tar')
srlnet.load_state_dict(checkpoint['state_dict'])
srlnet.eval()
elif option.depthNet == 2:
global leresmodel
leres_model_path = "models/res101.pth"
checkpoint = torch.load(leres_model_path)
leresmodel = RelDepthModel(backbone='resnext101')
leresmodel.load_state_dict(strip_prefix_if_present(checkpoint['depth_model'], "module."),
strict=True)
del checkpoint
torch.cuda.empty_cache()
leresmodel.to(device)
leresmodel.eval()
# Generating required directories
result_dir = option.output_dir
os.makedirs(result_dir, exist_ok=True)
if option.savewholeest:
whole_est_outputpath = option.output_dir + '_wholeimage'
os.makedirs(whole_est_outputpath, exist_ok=True)
if option.savepatchs:
patchped_est_outputpath = option.output_dir + '_patchest'
os.makedirs(patchped_est_outputpath, exist_ok=True)
# Generate mask used to smoothly blend the local pathc estimations to the base estimate.
# It is arbitrarily large to avoid artifacts during rescaling for each crop.
mask_org = generatemask((3000, 3000))
mask = mask_org.copy()
# Value x of R_x defined in the section 5 of the main paper.
r_threshold_value = 0.2
if option.R0:
r_threshold_value = 0
elif option.R20:
r_threshold_value = 0.2
# Go through all images in input directory
print("start processing")
for image_ind, images in enumerate(dataset):
print('processing image', image_ind, ':', images.name)
# Load image from dataset
img = images.rgb_image
input_resolution = img.shape
scale_threshold = 3 # Allows up-scaling with a scale up to 3
# Find the best input resolution R-x. The resolution search described in section 5-double estimation of the main paper and section B of the
# supplementary material.
whole_image_optimal_size, patch_scale = calculateprocessingres(img, option.net_receptive_field_size,
r_threshold_value, scale_threshold,
whole_size_threshold)
print('\t wholeImage being processed in :', whole_image_optimal_size)
# Generate the base estimate using the double estimation.
whole_estimate = doubleestimate(img, option.net_receptive_field_size, whole_image_optimal_size,
option.pix2pixsize, option.depthNet)
if option.R0 or option.R20:
path = os.path.join(result_dir, images.name)
if option.output_resolution == 1:
midas.utils.write_depth(path, cv2.resize(whole_estimate, (input_resolution[1], input_resolution[0]),
interpolation=cv2.INTER_CUBIC),
bits=2, colored=option.colorize_results)
else:
midas.utils.write_depth(path, whole_estimate, bits=2, colored=option.colorize_results)
continue
# Output double estimation if required
if option.savewholeest:
path = os.path.join(whole_est_outputpath, images.name)
if option.output_resolution == 1:
midas.utils.write_depth(path,
cv2.resize(whole_estimate, (input_resolution[1], input_resolution[0]),
interpolation=cv2.INTER_CUBIC), bits=2,
colored=option.colorize_results)
else:
midas.utils.write_depth(path, whole_estimate, bits=2, colored=option.colorize_results)
# Compute the multiplier described in section 6 of the main paper to make sure our initial patch can select
# small high-density regions of the image.
global factor
factor = max(min(1, 4 * patch_scale * whole_image_optimal_size / whole_size_threshold), 0.2)
print('Adjust factor is:', 1/factor)
# Check if Local boosting is beneficial.
if option.max_res < whole_image_optimal_size:
print("No Local boosting. Specified Max Res is smaller than R20")
path = os.path.join(result_dir, images.name)
if option.output_resolution == 1:
midas.utils.write_depth(path,
cv2.resize(whole_estimate,
(input_resolution[1], input_resolution[0]),
interpolation=cv2.INTER_CUBIC), bits=2,
colored=option.colorize_results)
else:
midas.utils.write_depth(path, whole_estimate, bits=2,
colored=option.colorize_results)
continue
# Compute the default target resolution.
if img.shape[0] > img.shape[1]:
a = 2 * whole_image_optimal_size
b = round(2 * whole_image_optimal_size * img.shape[1] / img.shape[0])
else:
a = round(2 * whole_image_optimal_size * img.shape[0] / img.shape[1])
b = 2 * whole_image_optimal_size
b = int(round(b / factor))
a = int(round(a / factor))
# recompute a, b and saturate to max res.
if max(a,b) > option.max_res:
print('Default Res is higher than max-res: Reducing final resolution')
if img.shape[0] > img.shape[1]:
a = option.max_res
b = round(option.max_res * img.shape[1] / img.shape[0])
else:
a = round(option.max_res * img.shape[0] / img.shape[1])
b = option.max_res
b = int(b)
a = int(a)
img = cv2.resize(img, (b, a), interpolation=cv2.INTER_CUBIC)
# Extract selected patches for local refinement
base_size = option.net_receptive_field_size*2
patchset = generatepatchs(img, base_size)
print('Target resolution: ', img.shape)
# Computing a scale in case user prompted to generate the results as the same resolution of the input.
# Notice that our method output resolution is independent of the input resolution and this parameter will only
# enable a scaling operation during the local patch merge implementation to generate results with the same resolution
# as the input.
if option.output_resolution == 1:
mergein_scale = input_resolution[0] / img.shape[0]
print('Dynamicly change merged-in resolution; scale:', mergein_scale)
else:
mergein_scale = 1
imageandpatchs = ImageandPatchs(option.data_dir, images.name, patchset, img, mergein_scale)
whole_estimate_resized = cv2.resize(whole_estimate, (round(img.shape[1]*mergein_scale),
round(img.shape[0]*mergein_scale)), interpolation=cv2.INTER_CUBIC)
imageandpatchs.set_base_estimate(whole_estimate_resized.copy())
imageandpatchs.set_updated_estimate(whole_estimate_resized.copy())
print('\t Resulted depthmap res will be :', whole_estimate_resized.shape[:2])
print('patchs to process: '+str(len(imageandpatchs)))
# Enumerate through all patches, generate their estimations and refining the base estimate.
for patch_ind in range(len(imageandpatchs)):
# Get patch information
patch = imageandpatchs[patch_ind] # patch object
patch_rgb = patch['patch_rgb'] # rgb patch
patch_whole_estimate_base = patch['patch_whole_estimate_base'] # corresponding patch from base
rect = patch['rect'] # patch size and location
patch_id = patch['id'] # patch ID
org_size = patch_whole_estimate_base.shape # the original size from the unscaled input
print('\t processing patch', patch_ind, '|', rect)
# We apply double estimation for patches. The high resolution value is fixed to twice the receptive
# field size of the network for patches to accelerate the process.
patch_estimation = doubleestimate(patch_rgb, option.net_receptive_field_size, option.patch_netsize,
option.pix2pixsize, option.depthNet)
# Output patch estimation if required
if option.savepatchs:
path = os.path.join(patchped_est_outputpath, imageandpatchs.name + '_{:04}'.format(patch_id))
midas.utils.write_depth(path, patch_estimation, bits=2, colored=option.colorize_results)
patch_estimation = cv2.resize(patch_estimation, (option.pix2pixsize, option.pix2pixsize),
interpolation=cv2.INTER_CUBIC)
patch_whole_estimate_base = cv2.resize(patch_whole_estimate_base, (option.pix2pixsize, option.pix2pixsize),
interpolation=cv2.INTER_CUBIC)
# Merging the patch estimation into the base estimate using our merge network:
# We feed the patch estimation and the same region from the updated base estimate to the merge network
# to generate the target estimate for the corresponding region.
pix2pixmodel.set_input(patch_whole_estimate_base, patch_estimation)
# Run merging network
pix2pixmodel.test()
visuals = pix2pixmodel.get_current_visuals()
prediction_mapped = visuals['fake_B']
prediction_mapped = (prediction_mapped+1)/2
prediction_mapped = prediction_mapped.squeeze().cpu().numpy()
mapped = prediction_mapped
# We use a simple linear polynomial to make sure the result of the merge network would match the values of
# base estimate
p_coef = np.polyfit(mapped.reshape(-1), patch_whole_estimate_base.reshape(-1), deg=1)
merged = np.polyval(p_coef, mapped.reshape(-1)).reshape(mapped.shape)
merged = cv2.resize(merged, (org_size[1],org_size[0]), interpolation=cv2.INTER_CUBIC)
# Get patch size and location
w1 = rect[0]
h1 = rect[1]
w2 = w1 + rect[2]
h2 = h1 + rect[3]
# To speed up the implementation, we only generate the Gaussian mask once with a sufficiently large size
# and resize it to our needed size while merging the patches.
if mask.shape != org_size:
mask = cv2.resize(mask_org, (org_size[1],org_size[0]), interpolation=cv2.INTER_LINEAR)
tobemergedto = imageandpatchs.estimation_updated_image
# Update the whole estimation:
# We use a simple Gaussian mask to blend the merged patch region with the base estimate to ensure seamless
# blending at the boundaries of the patch region.
tobemergedto[h1:h2, w1:w2] = np.multiply(tobemergedto[h1:h2, w1:w2], 1 - mask) + np.multiply(merged, mask)
imageandpatchs.set_updated_estimate(tobemergedto)
# Output the result
path = os.path.join(result_dir, imageandpatchs.name)
if option.output_resolution == 1:
midas.utils.write_depth(path,
cv2.resize(imageandpatchs.estimation_updated_image,
(input_resolution[1], input_resolution[0]),
interpolation=cv2.INTER_CUBIC), bits=2, colored=option.colorize_results)
else:
midas.utils.write_depth(path, imageandpatchs.estimation_updated_image, bits=2, colored=option.colorize_results)
print("finished")
Generating local patches to perform the local refinement described in section 6 of the main paper.
def generatepatchs(img, base_size):
code
# Compute the gradients as a proxy of the contextual cues.
img_gray = rgb2gray(img)
whole_grad = np.abs(cv2.Sobel(img_gray, cv2.CV_64F, 0, 1, ksize=3)) +\
np.abs(cv2.Sobel(img_gray, cv2.CV_64F, 1, 0, ksize=3))
threshold = whole_grad[whole_grad > 0].mean()
whole_grad[whole_grad < threshold] = 0
# We use the integral image to speed-up the evaluation of the amount of gradients for each patch.
gf = whole_grad.sum()/len(whole_grad.reshape(-1))
grad_integral_image = cv2.integral(whole_grad)
# Variables are selected such that the initial patch size would be the receptive field size
# and the stride is set to 1/3 of the receptive field size.
blsize = int(round(base_size/2))
stride = int(round(blsize*0.75))
# Get initial Grid
patch_bound_list = applyGridpatch(blsize, stride, img, [0, 0, 0, 0])
# Refine initial Grid of patches by discarding the flat (in terms of gradients of the rgb image) ones. Refine
# each patch size to ensure that there will be enough depth cues for the network to generate a consistent depth map.
print("Selecting patchs ...")
patch_bound_list = adaptiveselection(grad_integral_image, patch_bound_list, gf)
# Sort the patch list to make sure the merging operation will be done with the correct order: starting from biggest
# patch
patchset = sorted(patch_bound_list.items(), key=lambda x: getitem(x[1], 'size'), reverse=True)
return patchset
search_step = int(32/factor)
# Go through all patches
for c in range(len(patch_bound_list)):
# Get patch
bbox = patch_bound_list[str(c)]['rect']
# Compute the amount of gradients present in the patch from the integral image.
cgf = getGF_fromintegral(integral_grad, bbox)/(bbox[2]*bbox[3])
# Check if patching is beneficial by comparing the gradient density of the patch to
# the gradient density of the whole image
if cgf >= gf:
bbox_test = bbox.copy()
patchlist[str(count)] = {}
# Enlarge each patch until the gradient density of the patch is equal
# to the whole image gradient density
while True:
bbox_test[0] = bbox_test[0] - int(search_step/2)
bbox_test[1] = bbox_test[1] - int(search_step/2)
bbox_test[2] = bbox_test[2] + search_step
bbox_test[3] = bbox_test[3] + search_step
# Check if we are still within the image
if bbox_test[0] < 0 or bbox_test[1] < 0 or bbox_test[1] + bbox_test[3] >= height \
or bbox_test[0] + bbox_test[2] >= width:
break
# Compare gradient density
cgf = getGF_fromintegral(integral_grad, bbox_test)/(bbox_test[2]*bbox_test[3])
if cgf < gf:
break
bbox = bbox_test.copy()
# Add patch to selected patches
patchlist[str(count)]['rect'] = bbox
patchlist[str(count)]['size'] = bbox[2]
count = count + 1
# Return selected patches
return patchlist
Generate a double-input depth estimation
def doubleestimate(img, size1, size2, pix2pixsize, net_type):
# Generate the low resolution estimation
estimate1 = singleestimate(img, size1, net_type)
# Resize to the inference size of merge network.
estimate1 = cv2.resize(estimate1, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC)
code
# Generate the high resolution estimation
estimate2 = singleestimate(img, size2, net_type)
# Resize to the inference size of merge network.
estimate2 = cv2.resize(estimate2, (pix2pixsize, pix2pixsize), interpolation=cv2.INTER_CUBIC)
# Inference on the merge model
pix2pixmodel.set_input(estimate1, estimate2)
pix2pixmodel.test()
visuals = pix2pixmodel.get_current_visuals()
prediction_mapped = visuals['fake_B']
prediction_mapped = (prediction_mapped+1)/2
prediction_mapped = (prediction_mapped - torch.min(prediction_mapped)) / (
torch.max(prediction_mapped) - torch.min(prediction_mapped))
prediction_mapped = prediction_mapped.squeeze().cpu().numpy()
return prediction_mapped
if name == "main":
# Adding necessary input arguments
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--data_dir', type=str, required=True, help='input files directory '
'Images can be .png .jpg .tiff')
parser.add_argument('--output_dir', type=str, required=True, help='result dir. result depth will be png.'
' vides are JMPG as avi')
parser.add_argument('--savepatchs', type=int, default=0, required=False,
help='Activate to save the patch estimations')
parser.add_argument('--savewholeest', type=int, default=0, required=False,
help='Activate to save the base estimations')
parser.add_argument('--output_resolution', type=int, default=1, required=False,
help='0 for results in maximum resolution 1 for resize to input size')
parser.add_argument('--net_receptive_field_size', type=int, required=False) # Do not set the value here
parser.add_argument('--pix2pixsize', type=int, default=1024, required=False) # Do not change it
parser.add_argument('--depthNet', type=int, default=0, required=False,
help='use to select different base depth networks 0:midas 1:strurturedRL 2:LeRes')
parser.add_argument('--colorize_results', action='store_true')
parser.add_argument('--R0', action='store_true')
parser.add_argument('--R20', action='store_true')
parser.add_argument('--Final', action='store_true')
parser.add_argument('--max_res', type=float, default=np.inf)
code
# Check for required input
option_, _ = parser.parse_known_args()
print(option_)
if int(option_.R0) + int(option_.R20) + int(option_.Final) == 0:
assert False, 'Please activate one of the [R0, R20, Final] options using --[R0]'
elif int(option_.R0) + int(option_.R20) + int(option_.Final) > 1:
assert False, 'Please activate only ONE of the [R0, R20, Final] options'
if option_.depthNet == 1:
from structuredrl.models import DepthNet
# Setting each networks receptive field and setting the patch estimation resolution to twice the receptive
# field size to speed up the local refinement as described in the section 6 of the main paper.
if option_.depthNet == 0:
option_.net_receptive_field_size = 384
option_.patch_netsize = 2*option_.net_receptive_field_size
elif option_.depthNet == 1:
option_.net_receptive_field_size = 448
option_.patch_netsize = 2*option_.net_receptive_field_size
elif option_.depthNet == 2:
option_.net_receptive_field_size = 448
option_.patch_netsize = 2 * option_.net_receptive_field_size
else:
assert False, 'depthNet can only be 0,1 or 2'
# Create dataset from input images
dataset_ = ImageDataset(option_.data_dir, 'test')
# Run pipeline
run(dataset_, option_)
Как мне сделать так чтобы код сначала проверял совпадения файлов в папке с результатами и входной папке и обрабатывал только те изображения которых нет в папке с результатами
Assistant
To modify the script such that it processes only the images that are not already present in the results directory, you can add a check at the beginning of the image processing loop to see if the output file already exists. If it does, then skip processing that image. Here's how you can implement this:
Modify the run function to include a check for existing output files.
Skip processing for any input image that already has a corresponding output in the results directory.
Here's the modified part of the run function:
python
def run(dataset, option):
# Load merge network and depth estimation network as previously defined
...
# Generating required directories
result_dir = option.output_dir
os.makedirs(result_dir, exist_ok=True)
if option.savewholeest:
whole_est_outputpath = option.output_dir + '_wholeimage'
os.makedirs(whole_est_outputpath, exist_ok=True)
if option.savepatchs:
patchped_est_outputpath = option.output_dir + '_patchest'
os.makedirs(patchped_est_outputpath, exist_ok=True)
...
print("Start processing")
for image_ind, images in enumerate(dataset):
output_path = os.path.join(result_dir, images.name)
# Check if the output file already exists
if os.path.isfile(output_path + '.png'):
print(f'Skipping {images.name}, already processed.')
continue
print('Processing image', image_ind, ':', images.name)
# Load image and process with your existing code
...
Explanation
File Existence Check: Before processing an image, the script checks if a file with the same name already exists in the output directory. You may need to adjust the file extension (e.g., '.png') based on your specific output format.
Skip Processed Files: If the output file exists, a message is printed indicating that the file is being skipped, and the iteration continues to the next file.
Implementing this logic will ensure that only new or unprocessed images are subjected to the full pipeline, thereby saving computation time and resources.
Как мне в мой бат файл добавить второй этап:
@echo off
call conda activate nvidia_gpu
python stereo_image_generator.py ^
--images_dir ./inputs ^
--depth_maps_dir ./outputs_leres ^
--output_dir ./result/sbs ^
--divergence 4 ^
--separation 0
pause
Assistant
To combine both stages in a single batch file, you simply need to append the second command sequence to the existing batch file content. Ensure that each command sequence is complete and maintains the correct use of arguments and line continuation characters (^) where required. Here's how you can structure your combined batch file:
batch
@echo off
:: Activate the conda environment
call conda activate nvidia_gpu
:: First stage - Execute run.py script
python run.py ^
--Final ^
--data_dir C:/Developing/Python/Network/static/uploads/images ^
--output_dir C:/Developing/Python/Network/static/uploads/images/vr ^
--depthNet 2
:: Second stage - Execute stereo_image_generator.py script
python stereo_image_generator.py ^
--images_dir ./inputs ^
--depth_maps_dir ./outputs_leres ^
--output_dir ./result/sbs ^
--divergence 4 ^
--separation 0
:: Pause to review any command output before the window closes
pause
Explanation:
Environment Activation: The conda environment is activated only once at the beginning of the script. All Python commands executed afterwards will use this environment until the command window is closed or the environment is deactivated explicitly.
Line Continuation: The caret symbol (^) is used as a line continuation character for clarity in multi-line commands. Ensure there are no trailing spaces after the caret as it can cause syntax errors.
Sequence: The scripts are executed sequentially. The first Python script runs to completion before the second one starts.
Pause: The pause command at the end of the file will keep the command prompt window open so you can read the output from the executed scripts. This is especially useful for debugging and ensuring both scripts executed successfully.
Make sure the paths and script names (run.py and stereo_image_generator.py) are correct and reflect your project structure accurately. Adjust the paths if necessary based on where your scripts and directories are actually located.
User
что за ошибка?
Traceback (most recent call last):
File "C:\Developing\Python\BoostingMonocularDepth\stereo_image_generator.py", line 65, in
main()
File "C:\Developing\Python\BoostingMonocularDepth\stereo_image_generator.py", line 62, in main
process_images(args.images_dir, args.depth_maps_dir, args.output_dir, args.divergence, args.separation)
File "C:\Developing\Python\BoostingMonocularDepth\stereo_image_generator.py", line 43, in process_images
matching_depth_map = get_matching_depth_map(image_file, depth_map_files)
File "C:\Developing\Python\BoostingMonocularDepth\stereo_image_generator.py", line 17, in get_matching_depth_map
matching_depth_map = [f for f in depth_map_files if base_image_name in str(f)][0]
IndexError: list index out of range
Assistant
The error you're encountering is an IndexError: list index out of range. This means that the list comprehension used in the function get_matching_depth_map did not find any matching items, resulting in an empty list. When attempting to access the first element of this list with [0], the index is out of range because the list is empty.
Here's a closer look at the specific line causing the error:
python
matching_depth_map = [f for f in depth_map_files if base_image_name in str(f)][0]
Possible Reasons and Solutions
No Matching Depth Files: The base image name might not match any of the depth map files. Ensure that the naming convention between image files and depth map files is consistent. You might want to add some debug prints to show what base_image_name and each depth_map_file contain.
File Extension Differences: Make sure the images and depth maps, despite similar names, also have matching extensions (e.g., .jpg, .png). A mismatch here could cause the list to be empty.
Directory File Population: Verify that the depth_map_files list is correctly populated with all the files present in the depth_maps_dir. There could be an issue in how files are being read into this list.
Use a Default or Handle Empty Lists: You can handle this error by providing a default value or adding a check for an empty list:
python
matching_depth_maps = [f for f in depth_map_files if base_image_name in str(f)]
if matching_depth_maps:
matching_depth_map = matching_depth_maps[0]
else:
print(f"No matching depth map found for {base_image_name}.")
# Optionally, continue with next image or handle the error as needed
Debugging Steps
Print Debug Information: Add print statements before the offending line to see what filenames are being compared. For example:
python
print(f"Looking for matching depth map for {base_image_name} in {depth_map_files}")
Check Directory Contents: Manually check the depth_maps_dir directory to ensure files are present and named correctly.
Use Logging: Implement logging to track the flow of your script and catch where things may be going wrong.
By following the above steps, you should be able to identify the mismatch that is causing the list to be empty.
User
def get_matching_depth_map(image_file, depth_map_files):
base_image_name = Path(image_file).stem
matching_depth_map = [f for f in depth_map_files if base_image_name in str(f)][0]
return matching_depth_map
может быть добавить проверку сюда?
Assistant
Yes, adding a check within the get_matching_depth_map function can help you handle cases where no matching depth map is found for a given image file. You can modify the function to include a check for the case when the list comprehension returns an empty list. Here's how you could do it:
python
from pathlib import Path
def get_matching_depth_map(image_file, depth_map_files):
base_image_name = Path(image_file).stem
# Find all matching depth maps
matching_depth_maps = [f for f in depth_map_files if base_image_name in str(f)]
# Check if we found any matches
if matching_depth_maps:
return matching_depth_maps[0]
else:
# Handle the case where no matching depth map is found
print(f"Warning: No matching depth map found for {base_image_name}.")
return None # or handle it differently, e.g., raise an exception or return a default value
Explanation
List Comprehension: The list comprehension gathers all depth map files that contain the base_image_name.
Check for Matches: The if matching_depth_maps: checks if the list is non-empty.
Return First Match: If matches are found, it returns the first match using matching_depth_maps[0].
Handle No Matches: If the list is empty, it prints a warning message and returns None. You can change this behavior to better suit your application logic, such as raising an exception or handling it gracefully in the calling function.
In Calling Function
In the function where get_matching_depth_map is called, you should handle the case where it returns None:
python
def process_images(images_dir, depth_maps_dir, output_dir, divergence, separation):
...
for image_file in image_files:
matching_depth_map = get_matching_depth_map(image_file, depth_map_files)
if matching_depth_map is None:
continue # skip this image or handle accordingly
...
This will allow your program to continue processing other images even if some do not have matching depth maps, and it provides you visibility into images that might have issues through warnings.
User
вот весь код что поправить?
from stereoimage_generation import create_stereoimages
from tqdm import tqdm
import argparse
from pathlib import Path
from PIL import Image
import numpy as np
import cv2
import os
# Find all matching depth maps
matching_depth_maps = [f for f in depth_map_files if base_image_name in str(f)]
# Check if we found any matches
if matching_depth_maps:
return matching_depth_maps[0]
else:
# Handle the case where no matching depth map is found
print(f"Warning: No matching depth map found for {base_image_name}.")
return None # or handle it differently, e.g., raise an exception or return a default value
def create_stereo_images(input_image, depth_map, output_path, divergence, separation):
try:
# Инвертирование карты глубины для модели leres
inverted_depth_map = invert_depth_map(depth_map)
code
# Создание стереоизображения
stereo_images = create_stereoimages(input_image, inverted_depth_map, divergence=divergence, separation=separation, modes=['left-right'], fill_technique='polylines_sharp')
# Изменение расширения выходного пути на .jpg
output_path_jpg = output_path.with_suffix('.jpg')
# Сохранение стереоизображения
stereo_images[0].save(output_path_jpg, format='JPEG', quality=100)
except AssertionError as e:
print(f"Ошибка при обработке файла {output_path}: {e}")
To ensure correctness and robustness in the script, you can make the following improvements:
Check File Existence: Ensure that you handle cases where a matching depth map is not found by adding a check for None in process_images.
Ensure Consistent Paths: Verify that all paths used with Path objects are handled correctly.
Error Handling in Image Loading: Catch exceptions when loading images to prevent the program from crashing.
Output Path Handling: Use consistent Pathlib methods for creating paths and checking their existence.
Here's the improved version of the script:
python
User
как мне добавить входной аргумент, при передаче которого будет сохраняться только правая половина изображения
Assistant
To add an input argument that controls whether only the right half of the stereo image should be saved, you can modify the script to include an additional command-line argument. This argument will act as a flag to indicate whether the right half should be saved. Here's how you can implement this:
Add an argument to your argument parser to control the saving behavior.
Modify the image processing and saving logic to account for this argument.
Here's the updated code:
python
User
напиши пример бат файла с передачей нового параметра
Assistant
Certainly! To include the new --save_right_only parameter in your batch file, simply add it as an additional argument when calling the Python script. I'll show you how the batch file would look like both with and without the use of this parameter.
Here's an example of a batch file incorporating the --save_right_only parameter:
batch
@echo off
:: Activate the conda environment
call conda activate nvidia_gpu
:: First stage - Execute run.py script (assuming this is also required before your stereo image generation)
python run.py ^
--Final ^
--data_dir C:/Developing/Python/Network/static/uploads/images ^
--output_dir C:/Developing/Python/Network/static/uploads/images/vr ^
--depthNet 2
:: Second stage - Execute stereo_image_generator.py script with --save_right_only
python stereo_image_generator.py ^
--images_dir C:/Developing/Python/Network/static/uploads/images ^
--depth_maps_dir C:/Developing/Python/Network/static/uploads/images/vr ^
--output_dir C:/Developing/Python/Network/static/uploads/images/stereo ^
--divergence 4 ^
--separation 0 ^
--save_right_only
:: Pause to review any command output before the window closes
pause
Explanation of the Batch File:
Environment Activation: This begins with activating the nvidia_gpu conda environment necessary for running your scripts.
First Stage: Executes run.py, as set up in your prior example.
Second Stage:
The stereo_image_generator.py is run with several key arguments.
Images, Depth, and Output Directories: Paths provided for images, depth maps, and the target output directory.
--save_right_only: This additional flag tells the script to save only the right half of the resulting stereo images.
User
и еще один флаг нужен при передаче которого обработанная карта глубины будет удалена
Assistant
To add a new flag that will delete the processed depth map after the stereo image is created, you can introduce another command-line argument to your script. This argument will determine whether to delete the depth maps after processing. Here’s how you can modify the script and the batch file:
Modifications in the Script:
Add an additional command-line argument for the deletion flag.
Implement logic to delete the depth map file if the flag is set.
# Обработка изображений и создание стереоизображений с отображением прогресса
for image_file in tqdm(image_files, desc="Обработка изображений"):
matching_depth_map = get_matching_depth_map(image_file, depth_map_files)
input_image = Image.open(image_file)
depth_map = np.array(Image.open(matching_depth_map))
output_path = output_dir / Path(image_file.name)
# Проверка существования файла в выходной папке
if not os.path.exists(output_path):
create_stereo_images(input_image, depth_map, output_path, divergence, separation)
def main():
parser = argparse.ArgumentParser(description="Создание стереоизображений из изображений и карт глубины.")
parser.add_argument("--images_dir", required=True, help="Путь к директории с оригинальными изображениями")
parser.add_argument("--depth_maps_dir", required=True, help="Путь к директории с картами глубины")
parser.add_argument("--output_dir", required=True, help="Выходной путь для сохранения стереоизображений")
parser.add_argument("--divergence", type=float, default=2.5, help="Степень расхождения между левым и правым изображениями (по умолчанию: 2.5)")
parser.add_argument("--separation", type=int, default=0, help="Расстояние между левым и правым изображениями (по умолчанию: 0)")
from stereoimage_generation import create_stereoimages
from tqdm import tqdm
import argparse
from pathlib import Path
from PIL import Image
import numpy as np
import os
def invert_depth_map(depth_map):
# Инвертирование карты глубины
inverted_depth_map = depth_map * -1
return inverted_depth_map
def get_matching_depth_map(image_file, depth_map_files):
base_image_name = Path(image_file).stem
# Find all matching depth maps
matching_depth_maps = [f for f in depth_map_files if base_image_name in str(f)]
# Check if we found any matches
if matching_depth_maps:
return matching_depth_maps[0]
else:
# Handle the case where no matching depth map is found
print(f"Warning: No matching depth map found for {base_image_name}.")
return None
def create_stereo_images(input_image, depth_map, output_path, divergence, separation):
try:
# Инвертирование карты глубины для модели leres
inverted_depth_map = invert_depth_map(depth_map)
# Создание стереоизображения
stereo_images = create_stereoimages(input_image, inverted_depth_map, divergence=divergence, separation=separation, modes=['left-right'], fill_technique='polylines_sharp')
# Изменение расширения выходного пути на .jpg
output_path_jpg = output_path.with_suffix('.jpg')
# Сохранение стереоизображения
stereo_images[0].save(output_path_jpg, format='JPEG', quality=100)
except AssertionError as e:
print(f"Ошибка при обработке файла {output_path}: {e}")
def process_images(images_dir, depth_maps_dir, output_dir, divergence, separation):
# Получение списка файлов изображений и карт глубины
image_files = sorted(Path(images_dir).glob("*.jpg"))
depth_map_files = sorted(Path(depth_maps_dir).glob("*.png"))
output_dir_path = Path(output_dir)
output_dir_path.mkdir(parents=True, exist_ok=True)
# Обработка изображений и создание стереоизображений с отображением прогресса
for image_file in tqdm(image_files, desc="Обработка изображений"):
matching_depth_map = get_matching_depth_map(image_file, depth_map_files)
if matching_depth_map is None:
continue # Skip processing if no matching depth map is found
try:
input_image = Image.open(image_file)
depth_map = np.array(Image.open(matching_depth_map))
except (IOError, ValueError) as e:
print(f"Ошибка при открытии файла {image_file} или соответствующей карты глубины: {e}")
continue
output_path = output_dir_path / image_file.name
# Проверка существования файла в выходной папке
if not output_path.with_suffix('.jpg').exists():
create_stereo_images(input_image, depth_map, output_path, divergence, separation)
def main():
parser = argparse.ArgumentParser(description="Создание стереоизображений из изображений и карт глубины.")
parser.add_argument("--images_dir", required=True, help="Путь к директории с оригинальными изображениями")
parser.add_argument("--depth_maps_dir", required=True, help="Путь к директории с картами глубины")
parser.add_argument("--output_dir", required=True, help="Выходной путь для сохранения стереоизображений")
parser.add_argument("--divergence", type=float, default=2.5, help="Степень расхождения между левым и правым изображениями (по умолчанию: 2.5)")
parser.add_argument("--separation", type=int, default=0, help="Расстояние между левым и правым изображениями (по умолчанию: 0)")
args = parser.parse_args()
process_images(args.images_dir, args.depth_maps_dir, args.output_dir, args.divergence, args.separation)
if __name__ == "__main__":
main()
Key Changes:
Existence Check: Added a check in process_images to skip further processing if get_matching_depth_map returns None.
Error Handling: Included exception handling for image loading to ensure that a problematic file doesn't stop the whole batch processing.
Directory and File Path Handling: Consistently using Path from the pathlib module to manage directories and file paths, which is more robust and cleaner for cross-platform handling.
from stereoimage_generation import create_stereoimages
from tqdm import tqdm
import argparse
from pathlib import Path
from PIL import Image
import numpy as np
import os
def invert_depth_map(depth_map):
# Инвертирование карты глубины
inverted_depth_map = depth_map * -1
return inverted_depth_map
def get_matching_depth_map(image_file, depth_map_files):
base_image_name = Path(image_file).stem
matching_depth_maps = [f for f in depth_map_files if base_image_name in str(f)]
if matching_depth_maps:
return matching_depth_maps[0]
else:
print(f"Warning: No matching depth map found for {base_image_name}.")
return None
def create_stereo_images(input_image, depth_map, output_path, divergence, separation, save_right_only):
try:
inverted_depth_map = invert_depth_map(depth_map)
stereo_images = create_stereoimages(input_image, inverted_depth_map, divergence=divergence, separation=separation, modes=['left-right'], fill_technique='polylines_sharp')
# If requested, save only the right half of the stereo image
if save_right_only:
width, height = stereo_images[0].size
right_half = stereo_images[0].crop((width // 2, 0, width, height))
output_image = right_half
else:
output_image = stereo_images[0]
output_path_jpg = output_path.with_suffix('.jpg')
output_image.save(output_path_jpg, format='JPEG', quality=100)
except AssertionError as e:
print(f"Ошибка при обработке файла {output_path}: {e}")
def process_images(images_dir, depth_maps_dir, output_dir, divergence, separation, save_right_only):
image_files = sorted(Path(images_dir).glob("*.jpg"))
depth_map_files = sorted(Path(depth_maps_dir).glob("*.png"))
output_dir_path = Path(output_dir)
output_dir_path.mkdir(parents=True, exist_ok=True)
for image_file in tqdm(image_files, desc="Обработка изображений"):
matching_depth_map = get_matching_depth_map(image_file, depth_map_files)
if matching_depth_map is None:
continue
try:
input_image = Image.open(image_file)
depth_map = np.array(Image.open(matching_depth_map))
except (IOError, ValueError) as e:
print(f"Ошибка при открытии файла {image_file} или соответствующей карты глубины: {e}")
continue
output_path = output_dir_path / image_file.name
if not output_path.with_suffix('.jpg').exists():
create_stereo_images(input_image, depth_map, output_path, divergence, separation, save_right_only)
def main():
parser = argparse.ArgumentParser(description="Создание стереоизображений из изображений и карт глубины.")
parser.add_argument("--images_dir", required=True, help="Путь к директории с оригинальными изображениями")
parser.add_argument("--depth_maps_dir", required=True, help="Путь к директории с картами глубины")
parser.add_argument("--output_dir", required=True, help="Выходной путь для сохранения стереоизображений")
parser.add_argument("--divergence", type=float, default=2.5, help="Степень расхождения между левым и правым изображениями (по умолчанию: 2.5)")
parser.add_argument("--separation", type=int, default=0, help="Расстояние между левым и правым изображениями (по умолчанию: 0)")
parser.add_argument("--save_right_only", action='store_true', help="Сохранять только правую половину изображения")
args = parser.parse_args()
process_images(args.images_dir, args.depth_maps_dir, args.output_dir, args.divergence, args.separation, args.save_right_only)
if __name__ == "__main__":
main()
Explanation
New Argument: Added --save_right_only to the argument parser. It's a boolean flag activated with the presence of --save_right_only in the command-line input.
Saving Logic: Inside create_stereo_images, the program checks the save_right_only flag. If true, it crops the right half of the stereo image using PIL.Image.crop() and saves it.
Flag Handling: The store_true action for --save_right_only means that when this flag is present, args.save_right_only will be True. If the flag is not provided, the default value will be False.
This setup provides flexibility, allowing users to selectively save the stereo images in a desired format based on their specific use case.
Pause: Keeps the window open after execution for reviewing output or errors.
Without the New Parameter:
If you don't want to apply the --save_right_only argument, simply omit the last line of the second stage command:
Add or remove this --save_right_only parameter based on the desired behavior of your stereo image processing. Adjust paths to reflect actual directory structures as necessary.
from stereoimage_generation import create_stereoimages
from tqdm import tqdm
import argparse
from pathlib import Path
from PIL import Image
import numpy as np
import os
def invert_depth_map(depth_map):
inverted_depth_map = depth_map * -1
return inverted_depth_map
def get_matching_depth_map(image_file, depth_map_files):
base_image_name = Path(image_file).stem
matching_depth_maps = [f for f in depth_map_files if base_image_name in str(f)]
if matching_depth_maps:
return matching_depth_maps[0]
else:
print(f"Warning: No matching depth map found for {base_image_name}.")
return None
def create_stereo_images(input_image, depth_map, output_path, divergence, separation, save_right_only):
try:
inverted_depth_map = invert_depth_map(depth_map)
stereo_images = create_stereoimages(input_image, inverted_depth_map, divergence=divergence, separation=separation, modes=['left-right'], fill_technique='polylines_sharp')
if save_right_only:
width, height = stereo_images[0].size
right_half = stereo_images[0].crop((width // 2, 0, width, height))
output_image = right_half
else:
output_image = stereo_images[0]
output_path_jpg = output_path.with_suffix('.jpg')
output_image.save(output_path_jpg, format='JPEG', quality=100)
except AssertionError as e:
print(f"Ошибка при обработке файла {output_path}: {e}")
def process_images(images_dir, depth_maps_dir, output_dir, divergence, separation, save_right_only, delete_depth_maps):
image_files = sorted(Path(images_dir).glob("*.jpg"))
depth_map_files = sorted(Path(depth_maps_dir).glob("*.png"))
output_dir_path = Path(output_dir)
output_dir_path.mkdir(parents=True, exist_ok=True)
for image_file in tqdm(image_files, desc="Обработка изображений"):
matching_depth_map = get_matching_depth_map(image_file, depth_map_files)
if matching_depth_map is None:
continue
try:
input_image = Image.open(image_file)
depth_map = np.array(Image.open(matching_depth_map))
except (IOError, ValueError) as e:
print(f"Ошибка при открытии файла {image_file} или соответствующей карты глубины: {e}")
continue
output_path = output_dir_path / image_file.name
if not output_path.with_suffix('.jpg').exists():
create_stereo_images(input_image, depth_map, output_path, divergence, separation, save_right_only)
# Delete the depth map if the flag is set
if delete_depth_maps:
try:
os.remove(matching_depth_map)
except Exception as e:
print(f"Не удалось удалить карту глубины {matching_depth_map}: {e}")
def main():
parser = argparse.ArgumentParser(description="Создание стереоизображений из изображений и карт глубины.")
parser.add_argument("--images_dir", required=True, help="Путь к директории с оригинальными изображениями")
parser.add_argument("--depth_maps_dir", required=True, help="Путь к директории с картами глубины")
parser.add_argument("--output_dir", required=True, help="Выходной путь для сохранения стереоизображений")
parser.add_argument("--divergence", type=float, default=2.5, help="Степень расхождения между левым и правым изображениями (по умолчанию: 2.5)")
parser.add_argument("--separation", type=int, default=0, help="Расстояние между левым и правым изображениями (по умолчанию: 0)")
parser.add_argument("--save_right_only", action='store_true', help="Сохранять только правую половину изображения")
parser.add_argument("--delete_depth_maps", action='store_true', help="Удалять обработанные карты глубины после создания стереоизображений")
args = parser.parse_args()
process_images(args.images_dir, args.depth_maps_dir, args.output_dir, args.divergence, args.separation, args.save_right_only, args.delete_depth_maps)
if __name__ == "__main__":
main()
Batch File Example:
Here’s how you can create a batch file to include both the --save_right_only and --delete_depth_maps parameters:
batch
@echo off
:: Activate the conda environment
call conda activate nvidia_gpu
:: Execute stereo_image_generator.py script with --save_right_only and --delete_depth_maps
python stereo_image_generator.py ^
--images_dir C:/Developing/Python/Network/static/uploads/images ^
--depth_maps_dir C:/Developing/Python/Network/static/uploads/images/vr ^
--output_dir C:/Developing/Python/Network/static/uploads/images/stereo ^
--divergence 4 ^
--separation 0 ^
--save_right_only ^
--delete_depth_maps
:: Pause to review any command output before the window closes
pause
Key Points:
Command-line Argument: The new --delete_depth_maps argument is a boolean flag that triggers the deletion of the processed depth map if it’s set.
Code Handling: After successful creation of the stereo image, the script checks if the delete_depth_maps flag is set and, if so, attempts to delete the corresponding depth map file.
Batch File: The batch file uses the new flags to instruct the script to save only the right side of images and to delete depth maps after processing. Adjust paths according to your setup.