# Depth Anything

صُمم [Depth Anything](https://huggingface.co/papers/2401.10891) ليكون نموذجًا أساسيًا لتقدير العمق أحادي العين (MDE). تم تدريبه بشكل مشترك على صور مُوسومة وحوالي 62 مليون صورة غير مُوسومة لتعزيز مجموعة البيانات. يستخدم نموذج [DINOv2](./dinov2) المُسبق التدريب كمشفر للصور لوراثة أساليبه الدلالية الغنية الموجودة مسبقًا، و[DPT](./dpt) كفكّك. يتم تدريب نموذج مُعلّم على الصور غير المُوسومة لإنشاء تسميات زائفة. يتم تدريب نموذج الطالب على مزيج من التسميات الزائفة والصور المُوسومة. لتحسين أداء نموذج الطالب، تُضاف اضطرابات قوية إلى الصور غير المُوسومة لتحدي نموذج الطالب على تعلم المزيد من المعرفة البصرية من الصورة.

يمكنك العثور على جميع نقاط التفتيش الأصلية لـ Depth Anything ضمن مجموعة [Depth Anything](https://huggingface.co/collections/LiheYoung/depth-anything-release-65b317de04eec72abf6b55aa).

> [!TIP]
> انقر على نماذج Depth Anything في الشريط الجانبي الأيمن لمزيد من الأمثلة حول كيفية تطبيق Depth Anything على مهام الرؤية المختلفة.

يُظهر المثال أدناه كيفية الحصول على خريطة عمق باستخدام [Pipeline](/docs/transformers/main/ar/main_classes/pipelines#transformers.Pipeline) أو فئة [AutoModel](/docs/transformers/main/ar/model_doc/auto#transformers.AutoModel).

```python
from transformers import pipeline

pipe = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf", device=0)
pipe("http://images.cocodataset.org/val2017/000000039769.jpg")["depth"]
```

```python
import requests
import torch
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForDepthEstimation

image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-base-hf")
model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-base-hf", device_map="auto")
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = image_processor(images=image, return_tensors="pt").to(model.device)

with torch.no_grad():
    outputs = model(**inputs)

post_processed_output = image_processor.post_process_depth_estimation(
    outputs,
    target_sizes=[(image.height, image.width)],
)
predicted_depth = post_processed_output[0]["predicted_depth"]
depth = (predicted_depth - predicted_depth.min()) / (predicted_depth.max() - predicted_depth.min())
depth = depth.detach().cpu().numpy() * 255
Image.fromarray(depth.astype("uint8"))
```

## ملاحظات

- [DepthAnythingV2](./depth_anything_v2)، الذي أُطلق في يونيو 2024، يستخدم نفس البنية المعمارية الخاصة بـ Depth Anything، وهو متوافق مع جميع أمثلة الأكواد وسير العمل الحالية. ويعتمد على بيانات اصطناعية ونموذج مُعلِّم بسعة أكبر لتحقيق تنبؤات عمق أدق وأكثر متانة.

## DepthAnythingConfig[[transformers.DepthAnythingConfig]]

#### transformers.DepthAnythingConfig[[transformers.DepthAnythingConfig]]

```python
transformers.DepthAnythingConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, patch_size: int | list[int] | tuple[int, int] = 14, initializer_range: float = 0.02, reassemble_hidden_size: int = 384, reassemble_factors: list[int | float] | tuple[int | float, ...] = (4, 2, 1, 0.5), neck_hidden_sizes: list[int] | tuple[int, ...] = (48, 96, 192, 384), fusion_hidden_size: int = 64, head_in_index: int = -1, head_hidden_size: int = 32, depth_estimation_type: str = 'relative', max_depth: int | None = 1)
```

[المصدر](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_anything/configuration_depth_anything.py#L25)

**المعاملات:**

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`، *اختياري*) : إعدادات نموذج الهيكل الأساسي.

patch_size (`Union[int, list[int], tuple[int, int]]`، *اختياري*، القيمة الافتراضية `14`) : حجم (دقة) كل رقعة.

initializer_range (`float`، *اختياري*، القيمة الافتراضية `0.02`) : الانحراف المعياري لـ truncated_normal_initializer المستخدم في تهيئة جميع مصفوفات الأوزان.

reassemble_hidden_size (`int`، *اختياري*، القيمة الافتراضية 384) : عدد قنوات الإدخال لطبقات إعادة التجميع.

reassemble_factors (`list[int]`، *اختياري*، القيمة الافتراضية `[4, 2, 1, 0.5]`) : عوامل التوسيع/التصغير لطبقات إعادة التجميع.

neck_hidden_sizes (`list[str]`، *اختياري*، القيمة الافتراضية `[48, 96, 192, 384]`) : أحجام الطبقات المخفية التي سيتم الإسقاط إليها لخرائط الميزات الخاصة بالهيكل العظمي.

fusion_hidden_size (`int`، *اختياري*، القيمة الافتراضية 64) : عدد القنوات قبل الدمج.

head_in_index (`int`، *اختياري*، القيمة الافتراضية -1) : فهرس الميزات المستخدمة في رأس تقدير العمق.

head_hidden_size (`int`، *اختياري*، القيمة الافتراضية 32) : عدد قنوات الإخراج في الالتفاف الثاني لرأس تقدير العمق.

depth_estimation_type (`str`، *اختياري*، القيمة الافتراضية `"relative"`) : نوع تقدير العمق المستخدم. يمكن أن يكون أحد `["relative", "metric"]`.

max_depth (`float`, *اختياري*) : الحد الأقصى للعمق المستخدم لرأس تقدير العمق "metric". يجب استخدام القيمة 20 للنماذج الداخلية و80 للنماذج الخارجية. أما في حالة تقدير العمق "relative"، فتُتجاهل هذه القيمة.

هذه فئة الإعدادات (configuration class) لتخزين إعدادات نموذج Depth AnythingModel. تُستخدم لاستحداث نموذج Depth Anything وفقاً للحجج المحددة، مع تعريف بنية النموذج. إن استحداث إعدادات باستخدام القيم الافتراضية سيؤدي إلى الحصول على إعدادات مشابهة لتلك الخاصة بـ [LiheYoung/depth-anything-small-hf](https://huggingface.co/LiheYoung/depth-anything-small-hf)

ترث كائنات الإعداد من [PreTrainedConfig](/docs/transformers/main/ar/main_classes/configuration#transformers.PreTrainedConfig) ويمكن استخدامها للتحكم في مخرجات النموذج. اقرأ التوثيق الخاص بـ [PreTrainedConfig](/docs/transformers/main/ar/main_classes/configuration#transformers.PreTrainedConfig) لمزيد من المعلومات.

مثال:

```python
>>> from transformers import DepthAnythingConfig, DepthAnythingForDepthEstimation

>>> # Initializing a DepthAnything small style configuration
>>> configuration = DepthAnythingConfig()

>>> # Initializing a model from the DepthAnything small style configuration
>>> model = DepthAnythingForDepthEstimation(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config
```

## DepthAnythingForDepthEstimation[[transformers.DepthAnythingForDepthEstimation]]

#### transformers.DepthAnythingForDepthEstimation[[transformers.DepthAnythingForDepthEstimation]]

```python
transformers.DepthAnythingForDepthEstimation(config: DepthAnythingConfig)
```

[المصدر](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_anything/modeling_depth_anything.py#L316)

**المعاملات:**

config ([DepthAnythingConfig](/docs/transformers/main/ar/model_doc/depth_anything#transformers.DepthAnythingConfig)) : فئة إعدادات النموذج التي تحتوي على جميع معاملات النموذج. عند التهيئة باستخدام ملف إعدادات، لا يتم تحميل الأوزان المرتبطة بالنموذج، بل الإعدادات فقط. راجع طريقة [from_pretrained()](/docs/transformers/main/ar/main_classes/model#transformers.PreTrainedModel.from_pretrained) لتحميل أوزان النموذج.

نموذج Depth Anything مع رأس لتقدير العمق في الأعلى (يتكون من 3 طبقات تلافيفية) على سبيل المثال لـ KITTI وNYUv2.

يرث هذا النموذج من [PreTrainedModel](/docs/transformers/main/ar/main_classes/model#transformers.PreTrainedModel). راجع توثيق الفئة الأصلية لمعرفة الطرق العامة التي تنفذها المكتبة لجميع نماذجها (مثل التنزيل أو الحفظ، وتغيير حجم تضمينات الإدخال، وقص الرؤوس، وما إلى ذلك).

هذا النموذج هو أيضاً فئة فرعية من [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) في PyTorch. استخدمه كوحدة PyTorch عادية، وارجع إلى توثيق PyTorch لكل ما يتعلق بالاستخدام العام والسلوك.

#### forward[[transformers.DepthAnythingForDepthEstimation.forward]]

```python
forward(pixel_values: Tensor, labels: typing.Optional[torch.LongTensor] = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[المصدر](https://github.com/huggingface/transformers/blob/main/src/transformers/models/depth_anything/modeling_depth_anything.py#L327)

**المعاملات:**

pixel_values (`torch.Tensor` من الشكل `(batch_size, num_channels, image_size, image_size)`) : المصفوفات المتناظرة مع الصور المدخلة. يمكن الحصول على قيم البكسل باستخدام [DPTImageProcessor](/docs/transformers/main/ar/model_doc/dpt#transformers.DPTImageProcessor). راجع [DPTImageProcessor.__call__()](/docs/transformers/main/ar/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__) للتفاصيل (`processor_class` يستخدم [DPTImageProcessor](/docs/transformers/main/ar/model_doc/dpt#transformers.DPTImageProcessor) لمعالجة الصور).

labels (`torch.LongTensor` من الشكل `(batch_size, height, width)`، *اختياري*) : خرائط تقدير العمق الصحيحة (Ground truth) لحساب الخسارة.

output_attentions (`bool`، *اختياري*) : ما إذا كان سيتم إرجاع مصفوفات الانتباه لجميع طبقات الانتباه. راجع `attentions` ضمن المصفوفات المُرجعة لمزيد من التفاصيل.

output_hidden_states (`bool`, *اختياري*) : ما إذا كان سيتم إرجاع الحالات المخفية لجميع الطبقات. راجع `hidden_states` ضمن الموترات المُرجعة لمزيد من التفاصيل.

return_dict (`bool`، *اختياري*) : ما إذا كان سيتم إرجاع [ModelOutput](/docs/transformers/main/ar/main_classes/output#transformers.utils.ModelOutput) بدلاً من tuple عادي.

**يعيد:** [DepthEstimatorOutput](/docs/transformers/main/ar/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) أو `tuple(torch.Tensor)`

[DepthEstimatorOutput](/docs/transformers/main/ar/main_classes/output#transformers.modeling_outputs.DepthEstimatorOutput) أو مجموعة (tuple) من `torch.Tensor` (في حال تمرير `return_dict=False` أو عندما يكون `config.return_dict=False`) وتتضمن عناصر مختلفة اعتماداً على الإعداد ([DepthAnythingConfig](/docs/transformers/main/ar/model_doc/depth_anything#transformers.DepthAnythingConfig)) والمدخلات.

تتجاوز طريقة [DepthAnythingForDepthEstimation](/docs/transformers/main/ar/model_doc/depth_anything#transformers.DepthAnythingForDepthEstimation) الخاصة بالتقدم (forward) الطريقة الخاصة `__call__`.

على الرغم من أنه يجب تعريف وصفة المرور الأمامي داخل هذه الدالة، إلا أنه ينبغي استدعاء كائن `Module` بدلاً من هذه الدالة، لأن الكائن يتولى تنفيذ خطوات المعالجة المسبقة والمعالجة اللاحقة، بينما تتجاهل الدالة هذه الخطوات بصمت.

- **loss** (`torch.Tensor` من الشكل `(1,)`, *اختياري*، يُعاد عند تقديم `labels`) -- خسارة التصنيف (أو الانحدار إذا كان config.num_labels==1).
- **predicted_depth** (`torch.Tensor` من الشكل `(batch_size, height, width)`) -- العمق المتوقع لكل بكسل.
- **hidden_states** (`tuple(torch.Tensor)`، *اختياري*، يُعاد عند تمرير `output_hidden_states=True` أو عند تعيين `config.output_hidden_states=True`) -- مجموعة من `torch.Tensor` (واحدة لمخرجات الطبقات المضمنة إذا كان النموذج يحتوي على طبقة تضمين، + واحدة لمخرجات كل طبقة) بأبعاد `(batch_size, num_channels, height, width)`.

  حالات النموذج المخفية عند مخرج كل طبقة بالإضافة إلى مخرجات التضمين الأولي الاختيارية.
- **attentions** (`tuple(torch.Tensor)`, *اختياري*, يُعاد عند تمرير `output_attentions=True` أو عند `config.output_attentions=True`) -- مجموعة مرتبة (Tuple) من `torch.Tensor` (واحدة لكل طبقة) بأبعاد `(batch_size, num_heads, patch_size, sequence_length)`.

  أوزان الانتباه بعد تطبيق دالة softmax على الانتباه، وتُستخدم لحساب المتوسط الموزون في رؤوس الانتباه الذاتي.

أمثلة:
```python
>>> from transformers import AutoImageProcessor, AutoModelForDepthEstimation
>>> import torch
>>> import numpy as np
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> image_processor = AutoImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
>>> model = AutoModelForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # interpolate to original size
>>> post_processed_output = image_processor.post_process_depth_estimation(
...     outputs,
...     target_sizes=[(image.height, image.width)],
... )

>>> # visualize the prediction
>>> predicted_depth = post_processed_output[0]["predicted_depth"]
>>> depth = predicted_depth * 255 / predicted_depth.max()
>>> depth = depth.detach().cpu().numpy()
>>> depth = Image.fromarray(depth.astype("uint8"))
```

