from operator import getitem from torchvision.transforms import Compose from…
- User
from operator import getitem from torchvision.transforms import Compose from torchvision.transforms import transforms
OUR
from utils import ImageandPatchs, ImageDataset, generatemask, getGF_fromintegral, calculateprocessingres, rgb2gray,
applyGridpatchMIDAS
import midas.utils from midas.models.midas_net import MidasNet from midas.models.transforms import Resize, NormalizeImage, PrepareForNet
#AdelaiDepth from lib.multi_depth_model_woauxi import RelDepthModel from lib.net_tools import strip_prefix_if_present
PIX2PIX : MERGE NET
from pix2pix.options.test_options import TestOptions from pix2pix.models.pix2pix4depth_model import Pix2Pix4DepthModel
import time import os import torch import cv2 import numpy as np import argparse import warnings warnings.simplefilter('ignore', np.RankWarning)
select device
device = torch.device("cuda") print("device: %s" % device)
Global variables
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):
# 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") - Assistant
Чтобы написать отдельный скрипт, который использует указанный вами скрипт для обработки изображения и записи карты глубины в файл, вы можете создать новый Python файл. В этом новом файле вы будете импортировать необходимые функции и классы и затем использовать их для выполнения работы с заданными параметрами.
- User
мне нужен более глубокий доступ к коду что бы я мог получать изображение в байтах и настраивать логгирование
- Assistant