Salta para o conteúdo

Ultralytics Extensão de código VS


Snippet Prediction Preview
Executa um código de exemplo utilizando Ultralytics YOLO em menos de 20 segundos! 🚀

Caraterísticas e vantagens

✅ Are you a data scientist or machine learning engineer building computer vision applications with Ultralytics?

Não gostas de escrever os mesmos blocos de código repetidamente?

✅ Are you always forgetting the arguments or default values for the export, predict, train, track, or val methods?

✅ Looking to get started with Ultralytics and wish you had an easier way to reference or run code examples?

Queres acelerar o teu ciclo de desenvolvimento quando trabalhas com Ultralytics?

Se usas o Visual Studio Code e respondeste "sim" a qualquer uma das perguntas acima, então a extensão Ultralytics-snippets para o VS Code está aqui para ajudar! Continua a ler para saberes mais sobre a extensão, como a instalar e como a utilizar.

Inspirado pela comunidade Ultralytics

A inspiração para criar esta extensão veio da comunidade Ultralytics . As perguntas da Comunidade sobre tópicos e exemplos semelhantes alimentaram o desenvolvimento deste projeto. Além disso, como alguns membros da equipa Ultralytics também utilizam o VS Code, também o utilizamos como uma ferramenta para acelerar o nosso trabalho ⚡.

Porquê o VS Code?

Visual Studio Code is extremely popular with developers worldwide and has ranked most popular by the Stack Overflow Developer Survey in 2021, 2022, 2023, and 2024. Due to VS Code's high level of customization, built-in features, broad compatibility, and extensibility, it's no surprise that so many developers are using it. Given the popularity in the wider developer community and within the Ultralytics Discord, Discourse, Reddit, and GitHub Communities, it made sense to build a VS Code extension to help streamline your workflow and boost your productivity.

Want to let us know what you use for developing code? Head over to our Discourse community poll and let us know! While you're there, maybe check out some of our favorite computer vision, machine learning, AI, and developer memes, or even post your favorite!

Instalar a extensão

Nota

Any code environment that will allow for installing VS Code extensions should be compatible with the Ultralytics-snippets extension. After publishing the extension, it was discovered that neovim can be made compatible with VS Code extensions. To learn more see the neovim install section of the Readme in the Ultralytics-Snippets repository.

Instalar no código VS

  1. Navigate to the Extensions menu in VS Code or use the shortcut Ctrl+Shift ⇑+x, and search for Ultralytics-snippets.

  2. Click the Install button.


VS Code extension menu

Instalar a partir do VS Code Extension Marketplace

  1. Visit the VS Code Extension Marketplace and search for Ultralytics-snippets or go straight to the extension page on the VS Code marketplace.

  2. Click the Install button and allow your browser to launch a VS Code session.

  3. Segue as instruções para instalar a extensão.


VS Code marketplace extension install
Visual Studio Code Extension Marketplace page for Ultralytics-Snippets

Utilizar a extensão Ultralytics-Snippets

  • 🧠 Intelligent Code Completion: Write code faster and more accurately with advanced code completion suggestions tailored to the Ultralytics API.

  • Increased Development Speed: Save time by eliminating repetitive coding tasks and leveraging pre-built code block snippets.

  • 🔬 Improved Code Quality: Write cleaner, more consistent, and error-free code with intelligent code completion.

  • 💎 Streamlined Workflow: Stay focused on the core logic of your project by automating common tasks.

Visão geral

The extension will only operate when the Language Mode is configured for Python 🐍. This is to avoid snippets from being inserted when working on any other file type. All snippets have prefix starting with ultrae digita simplesmente ultra in your editor after installing the extension, will display a list of possible snippets to use. You can also open the VS Code Command Palette usando Ctrl+Shift ⇑+p and running the command Snippets: Insert Snippet.

Campos de snippet de código

Many snippets have "fields" with default placeholder values or names. For instance, output from the prevê method could be saved to a Python variable named r, results, detections, preds or whatever else a developer chooses, which is why snippets include "fields". Using Tab ⇥ on your keyboard after a snippet is inserted, your cursor will move between fields quickly. Once a field is selected, typing a new variable name will change that instance, but also every other instance in the snippet code for that variable!


Multi-update field and options
Depois de inserir o snippet, renomeia model como world_model updates all instances. Pressing Tab ⇥ moves to the next field, which opens a dropdown menu and allows for selection of a model scale, and moving to the next field provides another dropdown to choose either world ou worldv2 variante do modelo.

Conclusões de snippets de código

Even Shorter Shortcuts

It's not required to type the full prefix of the snippet, or even to start typing from the start of the snippet. See example in the image below.

The snippets are named in the most descriptive way possible, but this means there could be a lot to type and that would be counterproductive if the aim is to move faster. Luckily VS Code lets users type ultra.example-yolo-predict, example-yolo-predict, yolo-predictou mesmo ex-yolo-p and still reach the intended snippet option! If the intended snippet was actually ultra.example-yolo-predict-kwords, then just using your keyboard arrows ou to highlight the desired snippet and pressing Enter ↵ ou Tab ⇥ will insert the correct block of code.


Incomplete Snippet Example
Dactilografar ex-yolo-p will still arrive at the correct snippet.

Categorias de snippets

These are the current snippet categories available to the Ultralytics-snippets extension. More will be added in the future, so make sure to check for updates and to enable auto-updates for the extension. You can also request additional snippets to be added if you feel there's any missing.

CategoryStarting PrefixDescrição
Exemplosultra.examplesExample code to help learn or for getting started with Ultralytics. Examples are copies of or similar to code from documentation pages.
Kwargsultra.kwargsSpeed up development by adding snippets for train, track, predict, and val methods with all keyword arguments and default values.
Importsultra.importsSnippets to quickly import common Ultralytics objects.
Modelosultra.yoloInsert code blocks for initializing various modelos (yolo, sam, rtdetr, etc.), including dropdown configuration options.
Resultadosultra.resultCode blocks for common operations when working with inference results.
Utilidadesultra.utilProvides quick access to common utilities that are built into the Ultralytics package, learn more about these on the Simple Utilities page.

Aprende com exemplos

O ultra.examples snippets are to useful for anyone looking to learn how to get started with the basics of working with Ultralytics YOLO. Example snippets are intended to run once inserted (some have dropdown options as well). An example of this is shown at the animation at the top of this page, where after the snippet is inserted, all code is selected and run interactively using Shift ⇑+Enter ↵.

Exemplo

Just like the animation shows at the top of this page, you can use the snippet ultra.example-yolo-predict para inserires o seguinte exemplo de código. Uma vez inserido, a única opção configurável é a escala do modelo, que pode ser qualquer uma das seguintes: n, s, m, l, ou x.

from ultralytics import ASSETS, YOLO

model = YOLO("yolo11n.pt", task="detect")
results = model(source=ASSETS / "bus.jpg")

for result in results:
    print(result.boxes.data)
    # result.show()  # uncomment to view each result image

Acelerar o desenvolvimento

O objetivo para os snippets que não o ultra.examples servem para tornar o desenvolvimento mais fácil e mais rápido quando trabalhas com Ultralytics. Um bloco de código comum a ser utilizado em muitos projectos consiste em iterar a lista de Results returned from using the model prevê method. The ultra.result-loop pode ajudar-te com isto.

Exemplo

Utilizar o ultra.result-loop insere o seguinte código predefinido (incluindo comentários).

# reference https://docs.ultralytics.com/modes/predict/#working-with-results

for result in results:
    result.boxes.data  # torch.Tensor array

However, since Ultralytics supports numerous tasks, when working with inference results there are other Results attributes that you may wish to access, which is where the snippet fields will be powerful.


Results Loop Options
Uma vez selecionado o separador boxes aparece um menu pendente para permitir a seleção de outro atributo, se necessário.

Palavras-chave Argumentos

There are over 💯 keyword arguments for all of the various Ultralytics tasks e modes! That's a lot to remember and it can be easy to forget if the argument is save_frame ou save_frames (é definitivamente save_frames a propósito). É aqui que o ultra.kwargs Os snippets podem ajudar-te!

Exemplo

To insert the prevê method, including all argumentos de inferência, use ultra.kwargs-predict, que irá inserir o seguinte código (incluindo comentários).

model.predict(
    source=src,  # (str, optional) source directory for images or videos
    imgsz=640,  # (int | list) input images size as int or list[w,h] for predict
    conf=0.25,  # (float) minimum confidence threshold
    iou=0.7,  # (float) intersection over union (IoU) threshold for NMS
    vid_stride=1,  # (int) video frame-rate stride
    stream_buffer=False,  # (bool) buffer incoming frames in a queue (True) or only keep the most recent frame (False)
    visualize=False,  # (bool) visualize model features
    augment=False,  # (bool) apply image augmentation to prediction sources
    agnostic_nms=False,  # (bool) class-agnostic NMS
    classes=None,  # (int | list[int], optional) filter results by class, i.e. classes=0, or classes=[0,2,3]
    retina_masks=False,  # (bool) use high-resolution segmentation masks
    embed=None,  # (list[int], optional) return feature vectors/embeddings from given layers
    show=False,  # (bool) show predicted images and videos if environment allows
    save=True,  # (bool) save prediction results
    save_frames=False,  # (bool) save predicted individual video frames
    save_txt=False,  # (bool) save results as .txt file
    save_conf=False,  # (bool) save results with confidence scores
    save_crop=False,  # (bool) save cropped images with results
    stream=False,  # (bool) for processing long videos or numerous images with reduced memory usage by returning a generator
    verbose=True,  # (bool) enable/disable verbose inference logging in the terminal
)

Este snippet tem campos para todos os argumentos da palavra-chave, mas também para model e src no caso de teres utilizado uma variável diferente no teu código. Em cada linha que contém um argumento de palavra-chave, inclui uma breve descrição para referência.

Todos os snippets de código

The best way to find out what snippets are available is to download and install the extension and try it out! If you're curious and want to take a look at the list beforehand, you can visit the repo or extension page on the VS Code marketplace to view the tables for all available snippets.

Conclusão

The Ultralytics-Snippets extension for VS Code is designed to empower data scientists and machine learning engineers to build computer vision applications using Ultralytics YOLO more efficiently. By providing pre-built code snippets and useful examples, we help you focus on what matters most: creating innovative solutions. Please share your feedback by visiting the extension page on the VS Code marketplace and leaving a review. ⭐

FAQ

Como posso pedir um novo snippet?

New snippets can be requested using the Issues on the Ultralytics-Snippets repo.

Quanto custa o Ultralytics-Extension?

É 100% gratuito!

Porque é que não vejo uma pré-visualização do fragmento de código?

VS Code uses the key combination Ctrl+Space to show more/less information in the preview window. If you're not seeing a snippet preview when you type in a code snippet prefix, using this key combination should restore the preview.

Como posso desativar a recomendação de extensão em Ultralytics?

Se utilizas o VS Code e começaste a ver uma mensagem a pedir-te para instalares a extensão Ultralytics-snippets e não queres ver mais a mensagem, existem duas formas de a desativar.

  1. Instala o Ultralytics-snippets e a mensagem deixará de ser apresentada 😆!

  2. Podes utilizar o yolo settings vscode_msg False to disable the message from showing without having to install the extension. You can learn more about the Ultralytics Definições on the quickstart page if you're unfamiliar.

Tenho uma ideia para um novo fragmento de código Ultralytics . Como posso adicioná-lo?

Visit the Ultralytics-snippets repo and open an Issue or Pull Request!

Como é que desinstalo a extensão Ultralytics-Snippets?

Como qualquer outra extensão do VS Code, podes desinstalá-la navegando até ao menu Extensões no VS Code. Encontra a extensão Ultralytics-snippets no menu e clica no ícone de engrenagem (⚙) e, em seguida, clica em "Desinstalar" para remover a extensão.


VS Code extension menu

📅 Created 2 months ago ✏️ Updated 1 month ago

Comentários