# Copyright (c) 2023, Teriks
#
# dgenerate is distributed under the following BSD 3-Clause License
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import PIL.Image
import dgenerate.extras.controlnet_aux as _cna
import dgenerate.extras.controlnet_aux.util as _cna_util
import cv2
import numpy
import torch
import dgenerate.hfhub as _hfhub
import dgenerate.image as _image
import dgenerate.textprocessing as _textprocessing
import dgenerate.types as _types
from dgenerate.imageprocessors import imageprocessor as _imageprocessor
[docs]
class LeresDepthProcessor(_imageprocessor.ImageProcessor):
"""
LeReS depth detector.
The "threshold-near" argument is the near threshold, think the low threshold of canny.
The "threshold-far" argument is the far threshold, think the high threshold of canny.
The "boost" argument determines if monocular depth boost is used.
The "detect-resolution" argument is the resolution the image is resized to internal to the processor before
detection is run on it. It should be a single dimension for example: "detect-resolution=512" or the X/Y dimensions
seperated by an "x" character, like so: "detect-resolution=1024x512". If you do not specify this argument,
the detector runs on the input image at its full resolution. After processing the image will be resized to
whatever you have requested dgenerate resize it to via --output-size or --resize/--align in the case of the
image-process sub-command, if you have not requested any resizing the output will be resized back to the original
size of the input image.
The "detect-aspect" argument determines if the image resize requested by "detect-resolution" before
detection runs is aspect correct, this defaults to true.
The "pre-resize" argument determines if the processing occurs before or after dgenerate resizes the image.
This defaults to False, meaning the image is processed after dgenerate is done resizing it.
"""
NAMES = ['leres']
[docs]
def __init__(self,
threshold_near: int = 0,
threshold_far: int = 0,
boost: bool = False,
detect_resolution: str | None = None,
detect_aspect: bool = True,
pre_resize: bool = False,
**kwargs):
"""
:param threshold_near: argument is the near threshold, think the low threshold of canny
:param threshold_far: argument is the far threshold, think the high threshold of canny
:param boost: argument determines if monocular depth boost is used
:param detect_resolution: the input image is resized to this dimension before being processed,
providing ``None`` indicates it is not to be resized. If there is no resize requested during
the processing action via ``resize_resolution`` it will be resized back to its original size.
:param detect_aspect: if the input image is resized by ``detect_resolution`` or ``detect_align``
before processing, will it be an aspect correct resize?
:param detect_align: the input image is forcefully aligned to this amount of pixels
before being processed.
:param pre_resize: process the image before it is resized, or after? default is ``False`` (after).
:param kwargs: forwarded to base class
"""
super().__init__(**kwargs)
self._detect_aspect = detect_aspect
self._pre_resize = pre_resize
self._boost = boost
self._threshold_near = threshold_near
self._threshold_far = threshold_far
if detect_resolution is not None:
try:
self._detect_resolution = _textprocessing.parse_image_size(detect_resolution)
except ValueError as e:
raise self.argument_error(
f'Could not parse the "detect-resolution" argument as an image dimension: {e}') from e
else:
self._detect_resolution = None
# this is the size of res101.pth['depth_model'] + latest_net_G.pth in bytes
self.set_size_estimate(780273156)
with (_hfhub.with_hf_errors_as_model_not_found(),
_hfhub.offline_mode_context(self.local_files_only)):
self._leres = self.load_object_cached(
tag="lllyasviel/Annotators",
estimated_size=self.size_estimate,
method=lambda: _cna.LeresDetector.from_pretrained("lllyasviel/Annotators")
)
self.register_module(self._leres)
@torch.inference_mode()
def _process(self, image):
original_size = image.size
with image:
# must be aligned to 64 pixels, forcefully align
resized = _image.resize_image(
image,
self._detect_resolution,
aspect_correct=self._detect_aspect,
align=64
)
input_image = numpy.array(resized, dtype=numpy.uint8)
input_image = _cna_util.HWC3(input_image)
height, width, dim = input_image.shape
if self._boost:
depth = _cna.leres.estimateboost(
input_image, self._leres.model, 0,
self._leres.pix2pixmodel, max(width, height))
else:
depth = _cna.leres.estimateleres(input_image, self._leres.model, width, height)
numbytes = 2
depth_min = depth.min()
depth_max = depth.max()
max_val = (2 ** (8 * numbytes)) - 1
# check output before normalizing and mapping to 16 bit
if depth_max - depth_min > numpy.finfo("float").eps:
out = max_val * (depth - depth_min) / (depth_max - depth_min)
else:
out = numpy.zeros(depth.shape)
# single channel, 16 bit image
depth_image = out.astype("uint16")
# convert to uint8
depth_image = cv2.convertScaleAbs(depth_image, alpha=(255.0 / 65535.0))
# remove near
if self._threshold_near != 0:
threshold_near = ((self._threshold_near / 100) * 255)
depth_image = cv2.threshold(depth_image, threshold_near, 255, cv2.THRESH_TOZERO)[1]
# invert image
depth_image = cv2.bitwise_not(depth_image)
# remove bg
if self._threshold_far != 0:
threshold_far = ((self._threshold_far / 100) * 255)
depth_image = cv2.threshold(depth_image, threshold_far, 255, cv2.THRESH_TOZERO)[1]
detected_map = _cna_util.HWC3(depth_image)
detected_map = _image.cv2_resize_image(detected_map, original_size)
return PIL.Image.fromarray(detected_map)
[docs]
def impl_pre_resize(self, image: PIL.Image.Image, resize_resolution: _types.OptionalSize):
"""
Pre resize.
:param image: image to process
:param resize_resolution: resize resolution
:return: possibly a LeReS depth detected image, or the input image
"""
if self._pre_resize:
return self._process(image)
return image
[docs]
def impl_post_resize(self, image: PIL.Image.Image):
"""
Post resize.
:param image: image
:return: possibly a LeReS depth detected image, or the input image
"""
if not self._pre_resize:
return self._process(image)
return image
__all__ = _types.module_all()