Buckets:

hf-doc-build/doc / transformers /main /ru /tasks /zero_shot_object_detection.html
mishig's picture
download
raw
61.6 kB
<meta charset="utf-8" /><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Обнаружение объектов в режиме zero-shot&quot;,&quot;local&quot;:&quot;zero-shot-object-detection&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Пайплайн обнаружения объектов в режиме zero-shot&quot;,&quot;local&quot;:&quot;zero-shot-object-detection-pipeline&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Ручная детекция объектов в режиме zero-shot по текстовому промпту&quot;,&quot;local&quot;:&quot;text-prompted-zero-shot-object-detection-by-hand&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Пакетная обработка&quot;,&quot;local&quot;:&quot;batch-processing&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Обнаружение объектов с использованием изображений&quot;,&quot;local&quot;:&quot;image-guided-object-detection&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/>
<link href="/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DSYYoqAA.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/BovLmb3z.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/WyYpyc-L.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DYBfcveH.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DOLBYqcr.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/DsnmJJEf.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/0.ByO_lNbj.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/ZtBhN-Ei.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/nodes/771.CK0RudaY.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/D-dvW--N.js" rel="modulepreload">
<link href="/docs/transformers/main/en/_app/immutable/chunks/Bz_scJS3.js" rel="modulepreload">
<!--vki5pd--><meta name="hf:doc:metadata" content="{&quot;title&quot;:&quot;Zero-shot object detection&quot;,&quot;local&quot;:&quot;zero-shot-object-detection&quot;,&quot;sections&quot;:[{&quot;title&quot;:&quot;Zero-shot object detection pipeline&quot;,&quot;local&quot;:&quot;zero-shot-object-detection-pipeline&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Text-prompted zero-shot object detection by hand&quot;,&quot;local&quot;:&quot;text-prompted-zero-shot-object-detection-by-hand&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Batch processing&quot;,&quot;local&quot;:&quot;batch-processing&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2},{&quot;title&quot;:&quot;Image-guided object detection&quot;,&quot;local&quot;:&quot;image-guided-object-detection&quot;,&quot;sections&quot;:[],&quot;depth&quot;:2}],&quot;depth&quot;:1}"/><!---->
<link href="/docs/transformers/main/en/_app/immutable/assets/0.tn0RQdqM.css" rel="modulepreload"> <!--[--><!--[0--><!--[--><!--[0--><!--[--><p></p> <div class="items-center shrink-0 min-w-[100px] max-sm:min-w-[50px] justify-end ml-auto flex" style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;"><div dir="ltr" class="inline-flex rounded-md max-sm:rounded-sm"><button class="inline-flex items-center gap-1 h-7 max-sm:h-7 px-2 max-sm:px-1.5 text-sm font-medium text-gray-800 border border-r-0 rounded-l-md max-sm:rounded-l-sm border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-live="polite"><span class="inline-flex items-center justify-center rounded-md p-0.5 max-sm:p-0 hover:text-gray-800 dark:hover:text-gray-200"><svg class="sm:size-3.5 size-3" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----></span> <span dir="auto">Copy page</span></button> <button class="inline-flex items-center justify-center w-6 max-sm:w-5 h-7 max-sm:h-7 disabled:pointer-events-none text-sm text-gray-500 hover:text-gray-700 dark:hover:text-white rounded-r-md max-sm:rounded-r-sm border border-l transition border-gray-200 bg-white hover:shadow-inner dark:border-gray-850 dark:bg-gray-950 dark:text-gray-200 dark:hover:bg-gray-800" aria-haspopup="menu" aria-expanded="false" aria-label="Open copy menu"><svg class="transition-transform text-gray-400 overflow-visible sm:size-3.5 size-3 rotate-0" width="1em" height="1em" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1 1L6 6L11 1" stroke="currentColor"></path></svg><!----></button></div> <!--[-1--><!--]--></div><!----> <div class="flex space-x-1 " style="float: inline-end; margin-inline-start: 10px; display: inline-flex; position: relative; z-index: 10;" dir="ltr"><!----> <!--[1--><div class="relative colab-dropdown "><button class=" " type="button"><!--[0--><!--[-1--><img alt="Open In Colab" class="!m-0" src="https://colab.research.google.com/assets/colab-badge.svg"/><!--]--><!----><!--]--></button> <!--[-1--><!--]--></div><!--]--> <!--[1--><div class="relative colab-dropdown "><button class=" " type="button"><!--[0--><!--[-1--><img alt="Open In Studio Lab" class="!m-0" src="https://studiolab.sagemaker.aws/studiolab.svg"/><!--]--><!----><!--]--></button> <!--[-1--><!--]--></div><!--]--></div><!----> <!--[0--><h1 class="relative group"><a id="zero-shot-object-detection" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#zero-shot-object-detection"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Обнаружение объектов в режиме zero-shot<!----></span></h1><!--]--><!----> <p>Традиционно модели, используемые для <a href="object_detection">обнаружения объектов</a>, требуют размеченных наборов данных изображений для обучения и ограничены обнаружением набора классов, присутствующих в обучающих данных.</p> <p>Zero-shot object detection — это задача компьютерного зрения, состоящая в обнаружении объектов и их классов на изображениях без какого-либо предварительного обучения или знаний о классах. Модели zero-shot object detection принимают на вход изображение, а также список кандидатов классов, и на выходе предоставляют ограничивающие рамки (bounding boxes) и метки, где были обнаружены объекты.</p> <blockquote class="note"><p>Hugging Face содержит множество таких <a href="https://huggingface.co/models?pipeline_tag=zero-shot-object-detection" rel="nofollow">детекторов объектов с открытым словарём и нулевой настройкой</a>.</p></blockquote> <p>В этом руководстве вы узнаете, как использовать такие модели:</p> <ul><li>для обнаружения объектов на основе текстовых запросов</li> <li>для пакетного обнаружения объектов</li> <li>для обнаружения объектов с использованием изображений</li></ul> <p>Прежде чем начать, убедитесь, что у вас установлены все необходимые библиотеки:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-bash "><!---->pip install -q transformers<!----></pre></div><!----> <!--[1--><h2 class="relative group"><a id="zero-shot-object-detection-pipeline" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#zero-shot-object-detection-pipeline"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Пайплайн обнаружения объектов в режиме zero-shot<!----></span></h2><!--]--><!----> <p>Самый простой способ попробовать инференс с моделями — использовать его в <a href="/docs/transformers/main/ru/main_classes/pipelines#transformers.pipeline">pipeline()</a>. Создайте экземпляр пайплайна для zero-shot обнаружения объектов из <a href="https://huggingface.co/models?pipeline_tag=zero-shot-object-detection" rel="nofollow">чекпоинта на Hugging Face Hub</a>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-python "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> pipeline
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-comment"># Use any checkpoint from the hf.co/models?pipeline_tag=zero-shot-object-detection</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>checkpoint = <span class="hljs-string">&quot;iSEE-Laboratory/llmdet_large&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>detector = pipeline(model=checkpoint, task=<span class="hljs-string">&quot;zero-shot-object-detection&quot;</span>)<!----></pre></div><!----> <p>Далее выберите изображение, на котором нужно обнаружить объекты. Здесь мы будем использовать изображение астронавта Айлин Коллинз, входящее в состав набора данных <a href="https://www.nasa.gov/multimedia/imagegallery/index.html" rel="nofollow">NASA</a> Great Images.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers.image_utils <span class="hljs-keyword">import</span> load_image
<span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">&quot;https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_1.png&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image = load_image(url)
<span class="hljs-meta">&gt;&gt;&gt; </span>image<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_1.png" alt="Astronaut Eileen Collins"/></div> <p>Передайте в конвейер изображение и метки объектов, которые нужно найти.
Здесь мы передаём изображение напрямую; другие допустимые варианты — локальный путь к изображению или URL изображения. Также мы передаём текстовые описания всех объектов, по которым хотим выполнить запрос к изображению.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>predictions = detector(
<span class="hljs-meta">... </span> image,
<span class="hljs-meta">... </span> candidate_labels=[<span class="hljs-string">&quot;human face&quot;</span>, <span class="hljs-string">&quot;rocket&quot;</span>, <span class="hljs-string">&quot;nasa badge&quot;</span>, <span class="hljs-string">&quot;star-spangled banner&quot;</span>],
<span class="hljs-meta">... </span> threshold=<span class="hljs-number">0.45</span>,
<span class="hljs-meta">... </span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>predictions
[{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.8409242033958435</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;human face&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">179</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">74</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">272</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">179</span>}},
{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.7380027770996094</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;rocket&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">353</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">0</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">466</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">284</span>}},
{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.5850900411605835</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;star-spangled banner&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">0</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">0</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">96</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">511</span>}},
{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.5697067975997925</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;human face&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">18</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">15</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">366</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">511</span>}},
{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.47813931107521057</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;star-spangled banner&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">353</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">0</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">459</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">274</span>}},
{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.46597740054130554</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;nasa badge&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">353</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">0</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">462</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">279</span>}},
{<span class="hljs-string">&#x27;score&#x27;</span>: <span class="hljs-number">0.4585932493209839</span>,
<span class="hljs-string">&#x27;label&#x27;</span>: <span class="hljs-string">&#x27;nasa badge&#x27;</span>,
<span class="hljs-string">&#x27;box&#x27;</span>: {<span class="hljs-string">&#x27;xmin&#x27;</span>: <span class="hljs-number">132</span>, <span class="hljs-string">&#x27;ymin&#x27;</span>: <span class="hljs-number">348</span>, <span class="hljs-string">&#x27;xmax&#x27;</span>: <span class="hljs-number">208</span>, <span class="hljs-string">&#x27;ymax&#x27;</span>: <span class="hljs-number">423</span>}}]<!----></pre></div><!----> <p>Визуализируем предсказания:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> ImageDraw
<span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(image)
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> prediction <span class="hljs-keyword">in</span> predictions:
<span class="hljs-meta">... </span> box = prediction[<span class="hljs-string">&quot;box&quot;</span>]
<span class="hljs-meta">... </span> label = prediction[<span class="hljs-string">&quot;label&quot;</span>]
<span class="hljs-meta">... </span> score = prediction[<span class="hljs-string">&quot;score&quot;</span>]
<span class="hljs-meta">... </span> xmin, ymin, xmax, ymax = box.values()
<span class="hljs-meta">... </span> draw.rectangle((xmin, ymin, xmax, ymax), outline=<span class="hljs-string">&quot;red&quot;</span>, width=<span class="hljs-number">1</span>)
<span class="hljs-meta">... </span> draw.text((xmin, ymin), <span class="hljs-string">f&quot;<span class="hljs-subst">{label}</span>: <span class="hljs-subst">{<span class="hljs-built_in">round</span>(score,<span class="hljs-number">2</span>)}</span>&quot;</span>, fill=<span class="hljs-string">&quot;white&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>image<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_2.png" alt="Visualized predictions on NASA image"/></div> <!--[1--><h2 class="relative group"><a id="text-prompted-zero-shot-object-detection-by-hand" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#text-prompted-zero-shot-object-detection-by-hand"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Ручная детекция объектов в режиме zero-shot по текстовому промпту<!----></span></h2><!--]--><!----> <p>Теперь, когда вы узнали, как использовать конвейер zero-shot обнаружения объектов, давайте воспроизведем тот же результат вручную.</p> <p>Начните с загрузки модели и соответствующего процессора из <a href="https://hf.co/iSEE-Laboratory/llmdet_large" rel="nofollow">чекпоинта на Hugging Face Hub</a>.
Здесь мы будем использовать тот же чекпоинт, что и ранее:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, AutoModelForZeroShotObjectDetection
<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForZeroShotObjectDetection.from_pretrained(checkpoint, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>processor = AutoProcessor.from_pretrained(checkpoint)<!----></pre></div><!----> <p>Возьмём другое изображение, чтобы немного сменить обстановку.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">&quot;https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_3.png&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image = load_image(url)
<span class="hljs-meta">&gt;&gt;&gt; </span>image<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_3.png" alt="Beach photo"/></div> <p>Используйте processor для подготовки входных данных для модели.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>text_labels = [<span class="hljs-string">&quot;hat&quot;</span>, <span class="hljs-string">&quot;book&quot;</span>, <span class="hljs-string">&quot;sunglasses&quot;</span>, <span class="hljs-string">&quot;camera&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>inputs = processor(text=text_labels, images=image, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>).to(model.device)<!----></pre></div><!----> <p>Передайте входные данные в модель, выполните постобработку и визуализируйте результаты. Поскольку процессор изображений изменил размер изображений перед их передачей в модель, необходимо использовать метод <code>post_process_object_detection</code>, чтобы убедиться, что предсказанные ограничивающие рамки имеют правильные координаты относительно исходного изображения:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> torch
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> torch.inference_mode():
<span class="hljs-meta">... </span> outputs = model(**inputs)
<span class="hljs-meta">&gt;&gt;&gt; </span>results = processor.post_process_grounded_object_detection(
<span class="hljs-meta">... </span> outputs, threshold=<span class="hljs-number">0.50</span>, target_sizes=[(image.height, image.width)], text_labels=text_labels,
<span class="hljs-meta">... </span>)[<span class="hljs-number">0</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(image)
<span class="hljs-meta">&gt;&gt;&gt; </span>scores = results[<span class="hljs-string">&quot;scores&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>text_labels = results[<span class="hljs-string">&quot;text_labels&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>boxes = results[<span class="hljs-string">&quot;boxes&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> box, score, text_label <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(boxes, scores, text_labels):
<span class="hljs-meta">... </span> xmin, ymin, xmax, ymax = box
<span class="hljs-meta">... </span> draw.rectangle((xmin, ymin, xmax, ymax), outline=<span class="hljs-string">&quot;red&quot;</span>, width=<span class="hljs-number">1</span>)
<span class="hljs-meta">... </span> draw.text((xmin, ymin), <span class="hljs-string">f&quot;<span class="hljs-subst">{text_label}</span>: <span class="hljs-subst">{<span class="hljs-built_in">round</span>(score.item(),<span class="hljs-number">2</span>)}</span>&quot;</span>, fill=<span class="hljs-string">&quot;white&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>image<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_4.png" alt="Beach photo with detected objects"/></div> <!--[1--><h2 class="relative group"><a id="batch-processing" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#batch-processing"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Пакетная обработка<!----></span></h2><!--]--><!----> <p>Вы можете передавать несколько наборов изображений и текстовых запросов, чтобы искать разные (или одинаковые) объекты на нескольких изображениях.
Используем вместе изображение астронавта и изображение пляжа.
Для пакетной обработки текстовые запросы следует передавать процессору в виде вложенного списка, а изображения — в виде списков изображений PIL, тензоров PyTorch или массивов NumPy.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>url1 = <span class="hljs-string">&quot;https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_1.png&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>url2 = <span class="hljs-string">&quot;https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_3.png&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>images = [load_image(url1), load_image(url2)]
<span class="hljs-meta">&gt;&gt;&gt; </span>text_queries = [
<span class="hljs-meta">... </span> [<span class="hljs-string">&quot;human face&quot;</span>, <span class="hljs-string">&quot;rocket&quot;</span>, <span class="hljs-string">&quot;nasa badge&quot;</span>, <span class="hljs-string">&quot;star-spangled banner&quot;</span>],
<span class="hljs-meta">... </span> [<span class="hljs-string">&quot;hat&quot;</span>, <span class="hljs-string">&quot;book&quot;</span>, <span class="hljs-string">&quot;sunglasses&quot;</span>, <span class="hljs-string">&quot;camera&quot;</span>, <span class="hljs-string">&quot;can&quot;</span>],
<span class="hljs-meta">... </span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>inputs = processor(text=text_queries, images=images, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>, padding=<span class="hljs-literal">True</span>)<!----></pre></div><!----> <p>Ранее для постобработки вы передавали размер одного изображения в виде тензора, но также можно передать кортеж, а в случае нескольких изображений — список кортежей. Создадим предсказания для двух примеров и визуализируем второй (<code>image_idx = 1</code>).</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> torch.no_grad():
<span class="hljs-meta">&gt;&gt;&gt; </span> outputs = model(**inputs)
<span class="hljs-meta">&gt;&gt;&gt; </span>target_sizes = [(image.height, image.width) <span class="hljs-keyword">for</span> image <span class="hljs-keyword">in</span> images]
<span class="hljs-meta">&gt;&gt;&gt; </span>results = processor.post_process_grounded_object_detection(
<span class="hljs-meta">... </span> outputs, threshold=<span class="hljs-number">0.3</span>, target_sizes=target_sizes, text_labels=text_labels,
<span class="hljs-meta">... </span>)<!----></pre></div><!----> <p>Визуализируем результаты:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>image_idx = <span class="hljs-number">1</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(images[image_idx])
<span class="hljs-meta">&gt;&gt;&gt; </span>scores = results[image_idx][<span class="hljs-string">&quot;scores&quot;</span>].tolist()
<span class="hljs-meta">&gt;&gt;&gt; </span>text_labels = results[image_idx][<span class="hljs-string">&quot;text_labels&quot;</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>boxes = results[image_idx][<span class="hljs-string">&quot;boxes&quot;</span>].tolist()
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> box, score, text_label <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(boxes, scores, text_labels):
<span class="hljs-meta">&gt;&gt;&gt; </span> xmin, ymin, xmax, ymax = box
<span class="hljs-meta">&gt;&gt;&gt; </span> draw.rectangle((xmin, ymin, xmax, ymax), outline=<span class="hljs-string">&quot;red&quot;</span>, width=<span class="hljs-number">1</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span> draw.text((xmin, ymin), <span class="hljs-string">f&quot;<span class="hljs-subst">{text_label}</span>: <span class="hljs-subst">{<span class="hljs-built_in">round</span>(score,<span class="hljs-number">2</span>)}</span>&quot;</span>, fill=<span class="hljs-string">&quot;white&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>images[image_idx]<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_4.png" alt="Beach photo with detected objects"/></div> <!--[1--><h2 class="relative group"><a id="image-guided-object-detection" class="header-link block pr-1.5 text-lg no-hover:hidden with-hover:absolute with-hover:p-1.5 with-hover:opacity-0 with-hover:group-hover:opacity-100 with-hover:right-full" href="#image-guided-object-detection"><span><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 256"><path d="M167.594 88.393a8.001 8.001 0 0 1 0 11.314l-67.882 67.882a8 8 0 1 1-11.314-11.315l67.882-67.881a8.003 8.003 0 0 1 11.314 0zm-28.287 84.86l-28.284 28.284a40 40 0 0 1-56.567-56.567l28.284-28.284a8 8 0 0 0-11.315-11.315l-28.284 28.284a56 56 0 0 0 79.196 79.197l28.285-28.285a8 8 0 1 0-11.315-11.314zM212.852 43.14a56.002 56.002 0 0 0-79.196 0l-28.284 28.284a8 8 0 1 0 11.314 11.314l28.284-28.284a40 40 0 0 1 56.568 56.567l-28.285 28.285a8 8 0 0 0 11.315 11.314l28.284-28.284a56.065 56.065 0 0 0 0-79.196z" fill="currentColor"></path></svg><!----></span></a> <span><!---->Обнаружение объектов с использованием изображений<!----></span></h2><!--]--><!----> <p>Помимо обнаружения объектов в режиме zero-shot по текстовым запросам, такие модели, как <a href="https://huggingface.co/collections/ariG23498/owlvit-689b0d0872a7634a6ea17ae7" rel="nofollow">OWL-ViT</a> и <a href="https://huggingface.co/collections/ariG23498/owlv2-689b0d27bd7d96ba3c7f7530" rel="nofollow">OWLv2</a>, поддерживают обнаружение объектов по образцу изображения. Это позволяет использовать изображение в качестве запроса для поиска похожих объектов на целевом изображении.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> transformers <span class="hljs-keyword">import</span> AutoProcessor, AutoModelForZeroShotObjectDetection
<span class="hljs-meta">&gt;&gt;&gt; </span>checkpoint = <span class="hljs-string">&quot;google/owlv2-base-patch16-ensemble&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>model = AutoModelForZeroShotObjectDetection.from_pretrained(checkpoint, device_map=<span class="hljs-string">&quot;auto&quot;</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>processor = AutoProcessor.from_pretrained(checkpoint)<!----></pre></div><!----> <p>В отличие от текстовых запросов, допускается только одно изображение-пример.</p> <p>Возьмём в качестве целевого изображения картинку с двумя кошками на диване, а в качестве запроса — изображение одной кошки:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">&quot;http://images.cocodataset.org/val2017/000000039769.jpg&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>image_target = Image.<span class="hljs-built_in">open</span>(requests.get(url, stream=<span class="hljs-literal">True</span>).raw)
<span class="hljs-meta">&gt;&gt;&gt; </span>query_url = <span class="hljs-string">&quot;http://images.cocodataset.org/val2017/000000524280.jpg&quot;</span>
<span class="hljs-meta">&gt;&gt;&gt; </span>query_image = Image.<span class="hljs-built_in">open</span>(requests.get(query_url, stream=<span class="hljs-literal">True</span>).raw)<!----></pre></div><!----> <p>Давайте кратко рассмотрим изображения:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> matplotlib.pyplot <span class="hljs-keyword">as</span> plt
<span class="hljs-meta">&gt;&gt;&gt; </span>fig, ax = plt.subplots(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>ax[<span class="hljs-number">0</span>].imshow(image_target)
<span class="hljs-meta">&gt;&gt;&gt; </span>ax[<span class="hljs-number">1</span>].imshow(query_image)
<span class="hljs-meta">&gt;&gt;&gt; </span>fig.show()<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_5.png" alt="Cats"/></div> <p>На этапе предобработки вместо текстовых запросов теперь необходимо использовать <code>query_images</code>:</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span>inputs = processor(images=image_target, query_images=query_image, return_tensors=<span class="hljs-string">&quot;pt&quot;</span>)<!----></pre></div><!----> <p>Для предсказаний вместо передачи входных данных в модель передайте их в <a href="/docs/transformers/main/ru/model_doc/owlvit#transformers.OwlViTForObjectDetection.image_guided_detection">image_guided_detection()</a>. Отрисуйте предсказания так же, как и раньше, только теперь без меток.</p> <div class="code-block relative "><div class="absolute top-2.5 right-4"><button class="inline-flex items-center relative text-sm focus:text-green-500 cursor-pointer focus:outline-none transition duration-200 ease-in-out opacity-0 mx-0.5 text-gray-600 " title="code excerpt" type="button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z" transform="translate(0)"></path><path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)"></path><rect fill="none" width="32" height="32"></rect></svg><!----> <div class=" absolute pointer-events-none transition-opacity bg-black text-white py-1 px-2 leading-tight rounded font-normal shadow left-1/2 top-full transform -translate-x-1/2 translate-y-2 opacity-0 "><div class="absolute bottom-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-black border-4 border-t-0" style="border-left-color: transparent; border-right-color: transparent;"></div> Скопировано</div><!----></button><!----></div> <pre class="language-py "><!----><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> torch.no_grad():
<span class="hljs-meta">... </span> outputs = model.image_guided_detection(**inputs)
<span class="hljs-meta">... </span> target_sizes = torch.tensor([image_target.size[::-<span class="hljs-number">1</span>]])
<span class="hljs-meta">... </span> results = processor.post_process_image_guided_detection(outputs=outputs, target_sizes=target_sizes)[<span class="hljs-number">0</span>]
<span class="hljs-meta">&gt;&gt;&gt; </span>draw = ImageDraw.Draw(image_target)
<span class="hljs-meta">&gt;&gt;&gt; </span>scores = results[<span class="hljs-string">&quot;scores&quot;</span>].tolist()
<span class="hljs-meta">&gt;&gt;&gt; </span>boxes = results[<span class="hljs-string">&quot;boxes&quot;</span>].tolist()
<span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">for</span> box, score <span class="hljs-keyword">in</span> <span class="hljs-built_in">zip</span>(boxes, scores):
<span class="hljs-meta">... </span> xmin, ymin, xmax, ymax = box
<span class="hljs-meta">... </span> draw.rectangle((xmin, ymin, xmax, ymax), outline=<span class="hljs-string">&quot;white&quot;</span>, width=<span class="hljs-number">4</span>)
<span class="hljs-meta">&gt;&gt;&gt; </span>image_target<!----></pre></div><!----> <div class="flex justify-center"><img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/zero-sh-obj-detection_6.png" alt="Cats with bounding boxes"/></div> <a class="!text-gray-400 !no-underline text-sm flex items-center not-prose mt-4" href="https://github.com/huggingface/transformers/blob/main/docs/source/en/tasks/zero_shot_object_detection.md" target="_blank"><svg class="mr-1" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" fill="currentColor" focusable="false" role="img" width="1em" height="1em" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path d="M31,16l-7,7l-1.41-1.41L28.17,16l-5.58-5.59L24,9l7,7z"></path><path d="M1,16l7-7l1.41,1.41L3.83,16l5.58,5.59L8,23l-7-7z"></path><path d="M12.419,25.484L17.639,6.552l1.932,0.518L14.351,26.002z"></path></svg><!----> <span><span class="underline">Update</span> on GitHub</span></a><!----> <p></p><!--]--><!----><!--]--><!--]--><!--]--> <!--[-1--><!--]--><!--]-->
<script>
{
__sveltekit_1m6yd5j = {
base: "/docs/transformers/main/en",
assets: "/docs/transformers/main/en"
};
const element = document.currentScript.parentElement;
Promise.all([
import("/docs/transformers/main/en/_app/immutable/entry/start.DYIO-UII.js"),
import("/docs/transformers/main/en/_app/immutable/entry/app.D2_KizbC.js")
]).then(([kit, app]) => {
kit.start(app, element, {
node_ids: [0, 771],
data: [null,null],
form: null,
error: null
});
});
}
</script>

Xet Storage Details

Size:
61.6 kB
·
Xet hash:
1eb383d7239c5808b1285729f6b170ade72144b5b6241bc3bafc8965ca943a3a

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.