Last Updated on 27/11/2026 by Eran Feit
Qwen3-VL object detection lets you locate and label any item in an image using plain English prompts instead of spending days collecting and annotating custom datasets. In this complete Python tutorial, you will build a local, zero-shot object detection pipeline powered by Qwen3-VL-2B-Instruct, PyTorch, Hugging Face Transformers, and Roboflow Supervision—engineered to run smoothly on an 8GB VRAM consumer GPU.
Traditional detectors like YOLO require hundreds of manually labeled bounding boxes and hours of GPU training every time you need to recognize a new class. By shifting to Qwen3-VL object detection , you eliminate the entire dataset annotation bottleneck and gain open-vocabulary flexibility right out of the box, saving massive engineering time while keeping sensitive visual data 100% private on your own machine.
To achieve this, we break the implementation down into seven modular, copy-paste Python steps. First, you will configure a clean Conda environment with CUDA-accelerated PyTorch and load Qwen3-VL-2B-Instruct in memory-efficient bfloat16 precision with dynamic patch resolution limits (MIN_PIXELS and MAX_PIXELS).
Next, you will write a dedicated inference wrapper using qwen_vl_utils to send images and structured text prompts to the GPU, build a custom JSON parser that rescales Qwen’s normalized 0–1000 bbox_2d coordinates into exact pixel dimensions, and render crisp, publication-ready bounding boxes with supervision on real test images.
How Does Qwen3-VL Object Detection Work Without Any Custom Training? Qwen3-VL object detection relies on a Vision-Language Model (VLM) architecture that fuses visual understanding with natural language reasoning inside a single unified neural network. Instead of passing an image through fixed convolutional detection heads trained only on rigid categories like the 80 COCO classes, Qwen3-VL splits the input image into dynamic 32x32 visual patches, encodes them alongside your text instructions, and generates structured spatial coordinates directly as text tokens.
At a high level, the pipeline operates as an end-to-end multimodal translation engine. When you pass an image paired with a prompt asking the model to locate specific objects in JSON format, Qwen3-VL attends to both the visual features and the semantic meaning of your words—allowing it to find common items, fine-grained attributes, or niche objects it was never explicitly fine-tuned to detect in your specific environment. The model outputs normalized coordinates on a 0 to 1000 grid (bbox_2d), which your Python code converts back to original image pixels and hands off to supervision for rendering.
Feature Traditional YOLO Detection Qwen3-VL Object Detection (Zero-Shot) Training & Dataset Prep Requires hundreds or thousands of manually labeled bounding boxes and GPU training runs. Zero training or labeling required; works immediately out of the box. Target Class Flexibility Locked to the fixed classes defined during model training. Open-vocabulary; change target objects anytime simply by editing your text prompt. Output Format Raw numerical tensors (xyxy pixel arrays and integer class IDs). Structured JSON strings containing bbox_2d coordinates (0–1000 scale) and text label names. Hardware Requirement Lightweight and runs fast on low-end GPUs or CPUs. Qwen3-VL-2B-Instruct runs comfortably on a local 8GB VRAM GPU using bfloat16 precision.Best Use Case High-speed real-time video streams (60+ FPS) with fixed object categories. Rapid prototyping, dynamic prompt-based search, and automating dataset auto-labeling without prior training data.
AI Object Detection Without Training: How Qwen3-VL Replaces YOLO in Python 11 How the Python Pipeline Turns Text Prompts into Annotated Bounding Boxes How does the code convert Qwen3-VL text responses into visual bounding boxes on your local GPU? The Python script bridges natural language reasoning and standard computer vision visualization by pairing Qwen/Qwen3-VL-2B-Instruct with Roboflow’s supervision library inside a clean, modular workflow. Rather than relying on pre-trained detection heads that output fixed class IDs, the code treats object detection as a multimodal prompt-and-parse pipeline that runs completely locally on an 8GB VRAM GPU using bfloat16 precision.
In the first half of the script, we configure a dedicated Conda environment with CUDA-accelerated PyTorch and initialize AutoProcessor alongside AutoModelForImageTextToText. By constraining dynamic patch resolution between MIN_PIXELS (256 * 32 * 32) and MAX_PIXELS (1280 * 32 * 32), the code prevents out-of-memory crashes on high-resolution images while preserving enough spatial detail for accurate localization. The run_qwen_vl_inference function then formats the input image and your custom prompt via process_vision_info, executes generation inside torch.inference_mode(), and trims prompt tokens so only the model’s raw JSON prediction remains.
Because Qwen3-VL outputs spatial coordinates on a normalized 0 to 1000 grid rather than raw image pixels, the parse_qwen_detections function acts as the critical translator between the Vision-Language Model and traditional computer vision tools. It strips Markdown code fences from the model’s response, decodes the JSON payload, scales every bbox_2d coordinate (x1, y1, x2, y2) against the input image’s true width and height, and packages the results into a standard sv.Detections object.
Finally, the annotate_image and detect_and_visualize functions tie the entire pipeline together into a single reusable entry point. Using sv.BoxAnnotator and sv.LabelAnnotator with resolution-aware line thickness and text scaling, the script draws crisp bounding boxes and smart-positioned labels onto a copy of the original RGB image, saves the final output file to disk, and displays a side-by-side comparison plot with Matplotlib.
Link to the tutorial here
Download the code for the tutorial here or here
Link for Medium users here
Master Computer Vision
Follow my latest tutorials and AI insights on my
Personal Blog .
Beginner Complete CV Bootcamp
Foundation via PyTorch & TF.
Get Started → Interactive Deep Learning with PyTorch
Hands-on interactive practice.
Start Learning → Advanced Modern CV: GPT & OpenCV4
Vision GPT production models.
Go Advanced → AI Object Detection Without Training: How Qwen3-VL Replaces YOLO in Python 12 How Do You Build a Conflict-Free Python Environment for Qwen3-VL Object Detection? Why must you pin specific PyTorch, Transformers, and NumPy versions before running Qwen3-VL? Vision-Language Models like Qwen3-VL-2B-Instruct rely on newly introduced Hugging Face model architectures (AutoModelForImageTextToText) and specific vision tokenization utilities (qwen-vl-utils) that break immediately if your environment mixes incompatible NumPy 2.x arrays or mismatched CUDA wheels.
Setting up a clean, isolated environment is the single most important step before writing a single line of Qwen3-VL object detection code. Many developers jump straight into pip install transformers on their global Python installation, only to hit cryptic CUDA DLL errors, numpy binary incompatibilities with OpenCV, or missing Qwen3-VL architecture classes.
By starting inside WSL (Windows Subsystem for Linux) and creating a dedicated Anaconda environment running Python 3.11, you guarantee a reproducible Linux-native runtime that handles PyTorch GPU acceleration cleanly. Checking your local CUDA toolkit version with nvcc --version ensures that the PyTorch 2.6.0 wheels (cu126) match your NVIDIA driver stack without silent CPU fallbacks.
Next, pinning transformers>=4.57.0,<5.0.0 alongside accelerate>=1.3.0 and qwen-vl-utils>=0.0.10 gives Python native support for Qwen3-VL’s dynamic resolution processor. At the same time, locking "opencv-python-headless<4.10", "numpy<2.0.0", and "pandas<2.3.0" prevents the notorious NumPy 2.0 ABI crash that breaks compiled computer vision libraries.
Even though our current script focuses on zero-shot Qwen3-VL object detection , the installation block also includes fine-tuning packages such as peft, bitsandbytes, trl, and datasets. Having those libraries pre-installed means your environment is already future-proofed if you ever decide to fine-tune Qwen3-VL on specialized domain imagery later on.
### Launch Windows Subsystem for Linux (WSL) from PowerShell for a native Linux environment. wsl ### Create a dedicated Conda environment named 'qwen' with Python 3.11. conda create -n qwen python= 3.11 ### Activate the newly created 'qwen' Conda environment. conda activate qwen ### Verify the installed NVIDIA CUDA compiler version on your system. nvcc --version ### Install PyTorch 2.6.0, TorchVision, and TorchAudio compiled for CUDA 12.6. pip install torch== 2.6 .0 torchvision== 0.21 .0 torchaudio== 2.6 .0 --index-url https://download.pytorch.org/whl/cu126 ### Install Hugging Face Transformers (v4.57+) to support the Qwen3-VL architecture. pip install " transformers>=4.57.0,<5.0.0 " ### Install Accelerate to enable automatic GPU device mapping and low-VRAM loading. pip install " accelerate>=1.3.0 " ### Install Qwen's official vision utilities for dynamic image and video tensor preprocessing. pip install " qwen-vl-utils>=0.0.10 " ### Install Roboflow Supervision for bounding box parsing and clean visual annotations. pip install " supervision>=0.26.0 " ### Install Pillow for opening, converting, and saving RGB image files. pip install " pillow>=10.0.0 " ### Install headless OpenCV alongside pinned NumPy (<2.0) and Pandas (<2.3) to avoid ABI conflicts. pip install " opencv-python-headless<4.10 " " numpy<2.0.0 " " pandas<2.3.0 " ### Install PEFT for parameter-efficient LoRA fine-tuning support. pip install " peft>=0.14.0 " ### Install bitsandbytes for 4-bit and 8-bit quantization support on low-VRAM GPUs. pip install " bitsandbytes>=0.45.0 " ### Install TRL (Transformer Reinforcement Learning) for supervised fine-tuning workflows. pip install " trl>=0.14.0 " ### Install Hugging Face Datasets for loading structured vision-language training data. pip install " datasets>=3.2.0 " ### Pin PyArrow, Pandas, and NumPy versions for stable dataset serialization. pip install " pyarrow<18.0.0 " " pandas<2.3.0 " " numpy<2.0.0 " ### Enforce upper version bounds across datasets, TRL, and PyArrow to prevent dependency drift. pip install " datasets>=3.2.0,<4.0.0 " " trl>=0.14.0,<0.20.0 " " pyarrow<18.0.0 " " pandas<2.3.0 " " numpy<2.0.0 " ### Launch Visual Studio Code in the current project directory. code . ### Alternatively, launch the Antigravity IDE in the current project directory. antigravity-ide . Summary: You now have an isolated Python 3.11 Conda environment with CUDA 12.6 PyTorch, Hugging Face Transformers, Qwen vision utilities, and Roboflow Supervision ready for local Qwen3-VL object detection .
How Can You Run a 2-Billion-Parameter Vision-Language Model on an 8GB VRAM GPU? What do MIN_PIXELS, MAX_PIXELS, and dtype=torch.bfloat16 actually control during model initialization? They cap the number of 32x32 visual patch tokens generated from high-resolution images and cut model weight memory in half using bfloat16 floating-point precision so Qwen3-VL-2B-Instruct fits comfortably inside 8GB of GPU memory without crashing.
Loading a modern Vision-Language Model on consumer hardware often fails because unoptimized FP32 weights and oversized images rapidly exhaust VRAM. In this stage of our Qwen3-VL object detection pipeline, we import our core Python stack—including torch, supervision, PIL.Image, AutoModelForImageTextToText, AutoProcessor, and process_vision_info—and configure memory-safe loading parameters.
First, we target "Qwen/Qwen3-VL-2B-Instruct", a compact yet remarkably accurate 2-billion-parameter model capable of spatial grounding and JSON coordinate generation. Rather than feeding raw 4K photos into the vision encoder and triggering an out-of-memory error, we define MIN_PIXELS = 256 * 32 * 32 and MAX_PIXELS = 1280 * 32 * 32.
Because Qwen3-VL processes images as grids of 32x32 patches, setting shortest_edge and longest_edge in multiples of 32 * 32 lets the AutoProcessor dynamically resize any input photo while preserving aspect ratio and fine object boundaries. Finally, calling AutoModelForImageTextToText.from_pretrained with dtype=torch.bfloat16 and device_map="auto" loads the model directly onto your NVIDIA GPU in half-precision (~4.5GB VRAM footprint), leaving plenty of headroom for image activations.
### Import operating system utilities for file path operations. import os ### Import the built-in JSON library to parse bounding box coordinates from model text output. import json ### Import warnings module to manage or suppress non-critical runtime alerts. import warnings ### Import Optional type hinting for clean, self-documenting function signatures. from typing import Optional ### Import NumPy for fast numerical array conversions required by Supervision. import numpy as np ### Import PyTorch for GPU tensor operations and bfloat16 inference. import torch ### Import Roboflow Supervision for bounding box data structures and visual annotators. import supervision as sv ### Import Matplotlib to render side-by-side original and detected image comparisons. import matplotlib . pyplot as plt ### Import Pillow's Image class for loading and saving RGB images. from PIL import Image ### Import Hugging Face's multimodal model and processor classes for Qwen3-VL. from transformers import AutoModelForImageTextToText , AutoProcessor ### Import Qwen's helper utility to extract image and video inputs from chat message payloads. from qwen_vl_utils import process_vision_info ### Select the lightweight 2B Qwen3-VL Instruct model that fits easily inside 8GB VRAM. MODEL_ID = " Qwen/Qwen3-VL-2B-Instruct " ### Define the minimum visual token budget in multiples of 32x32 image patches. MIN_PIXELS = 256 * 32 * 32 ### Define the maximum visual token budget in multiples of 32x32 patches to prevent VRAM spikes. MAX_PIXELS = 1280 * 32 * 32 ### Initialize the Qwen3-VL processor with dynamic resolution bounds for tokenization and resizing. processor = AutoProcessor . from_pretrained ( MODEL_ID , size = { " shortest_edge " : MIN_PIXELS , " longest_edge " : MAX_PIXELS } ) ### Load Qwen3-VL-2B-Instruct in bfloat16 precision and automatically map layers to the CUDA GPU. model = AutoModelForImageTextToText . from_pretrained ( MODEL_ID , dtype = torch . bfloat16 , device_map = " auto " ) Summary: With AutoProcessor bounded by 32x32 patch limits and Qwen3-VL-2B-Instruct loaded in bfloat16 on CUDA, your local GPU is primed for fast, memory-safe Qwen3-VL object detection .
How Does Qwen3-VL Turn Plain English Prompts into Structured JSON Detections? Why do we slice generated_ids using out_ids[len(in_ids):] before decoding the model response? Hugging Face’s model.generate() returns the original input prompt tokens concatenated with the newly generated answer tokens, so slicing off len(in_ids) isolates only the clean JSON detection string.
Once the model is sitting in GPU memory, we need a clean, reusable inference wrapper that combines an input PIL.Image with a natural language detection request. In run_qwen_vl_inference, we structure the request using the standard multimodal chat format (role: "user") containing two content items: the image object and your text instruction.
If you pass an optional system_message, the function prepends a "system" role dictionary so you can enforce strict formatting rules across multiple runs. Next, processor.apply_chat_template injects Qwen3-VL’s special vision boundary tokens into the prompt string, while process_vision_info(messages) extracts and preprocesses the visual tensors.
After moving the tokenized inputs to "cuda", we wrap model.generate() inside with torch.inference_mode(): to disable gradient tracking—cutting inference latency and memory consumption even further. Finally, trimming the prompt prefix from generated_ids and running processor.batch_decode(..., skip_special_tokens=True) returns a pure text string containing the model’s JSON bounding box array.
### Define the zero-shot inference function taking the model, processor, image, and text prompt. def run_qwen_vl_inference ( model , processor , image : Image . Image , prompt : str , system_message : Optional [ str ] = None , max_new_tokens : int = 1024 , ) -> str : ### Initialize the chat message list and optionally prepend a system instruction. messages = [] if system_message : messages . append ({ " role " : " system " , " content " : system_message }) ### Append the user turn pairing the PIL Image with the natural language detection prompt. messages . append ({ " role " : " user " , " content " : [ { " type " : " image " , " image " : image }, { " type " : " text " , " text " : prompt }, ], }) ### Apply Qwen3-VL's multimodal chat template without tokenizing yet. text = processor . apply_chat_template ( messages , tokenize =False , add_generation_prompt =True ) ### Extract preprocessed image and video tensor payloads from the messages structure. image_inputs , video_inputs = process_vision_info ( messages ) ### Tokenize the formatted text and visual inputs into PyTorch tensors on the CUDA GPU. inputs = processor ( text = [ text ], images = image_inputs , videos = video_inputs , padding =True , return_tensors = " pt " , ). to ( " cuda " ) ### Run autoregressive token generation with gradient calculation disabled for speed and low VRAM. with torch . inference_mode (): generated_ids = model . generate ( ** inputs , max_new_tokens = max_new_tokens ) ### Remove the input prompt tokens from each generated sequence to isolate new output tokens. generated_ids_trimmed = [ out_ids [ len ( in_ids ):] for in_ids , out_ids in zip ( inputs . input_ids , generated_ids ) ] ### Decode the trimmed output token IDs back into a clean human-readable JSON string. response = processor . batch_decode ( generated_ids_trimmed , skip_special_tokens =True , clean_up_tokenization_spaces =False )[ 0 ] ### Return the raw string response containing Qwen3-VL's predicted bounding boxes. return response Summary: run_qwen_vl_inference packages any image and plain-English prompt into Qwen3-VL’s chat format, runs fast GPU inference, and returns a clean JSON response string.
How Do You Convert Qwen3-VL’s 0–1000 Coordinates into Real Image Pixels? Why does parse_qwen_detections divide each bbox_2d value by 1000.0 before multiplying by image width and height? Qwen3-VL always predicts bounding box coordinates on a resolution-independent 0 to 1000 normalized scale, so dividing by 1000.0 and multiplying by (w, h) maps every box back onto your original image’s exact pixel dimensions.
Unlike YOLO, which outputs raw pixel tensors directly, a Vision-Language Model speaks in text—meaning its response often arrives wrapped in Markdown formatting like ```json ... ```. If you pass that raw string straight into json.loads(), Python will throw a JSONDecodeError and halt your pipeline.
That is why parse_qwen_detections begins by stripping Markdown code fences ("```json" and "```") and guarding the json.loads() call inside a try/except block that safely returns sv.Detections.empty() if a response is malformed. Once parsed into a Python list of dictionaries, the function iterates through every detected item and inspects its "bbox_2d" key ([x1, y1, x2, y2]).
Using the tuple resolution_wh unpacked into w and h, each normalized coordinate is rescaled via (x1 / 1000.0) * w and (y1 / 1000.0) * h to recover exact pixel coordinates. Finally, the function converts the coordinate list into a np.float32 array and wraps both xyxy boxes and class_name labels inside a standard Roboflow sv.Detections object.
### Define the parser to convert Qwen3-VL's JSON string output into a Supervision Detections object. def parse_qwen_detections ( response : str , resolution_wh : tuple [ int , int ] ) -> sv . Detections : ### Strip Markdown JSON code fences and whitespace from the raw model response. clean_json = response . replace ( " ```json " , "" ). replace ( " ``` " , "" ). strip () ### Safely parse the cleaned JSON string and return an empty detection object on syntax errors. try : data = json . loads ( clean_json ) except json . JSONDecodeError : print ( " Error parsing JSON from model response: " , response ) return sv . Detections . empty () ### Return an empty Detections object if the model found zero matching objects. if not data : return sv . Detections . empty () ### Unpack original image width and height and initialize lists for pixel boxes and text labels. w , h = resolution_wh xyxy = [] labels = [] ### Loop through each JSON detection entry and rescale normalized 0-1000 coordinates to pixels. for item in data : if " bbox_2d " in item and len ( item [ " bbox_2d " ]) == 4 : x1 , y1 , x2 , y2 = item [ " bbox_2d " ] xyxy . append ([ ( x1 / 1000.0 ) * w , ( y1 / 1000.0 ) * h , ( x2 / 1000.0 ) * w , ( y2 / 1000.0 ) * h ]) labels . append ( item . get ( " label " , " object " )) ### Return an empty Detections object if no valid 4-coordinate bounding boxes were extracted. if not xyxy : return sv . Detections . empty () ### Package the rescaled pixel boxes and class labels into a standardized Supervision Detections object. return sv . Detections ( xyxy = np . array ( xyxy , dtype = np . float32 ), data = { " class_name " : np . array ( labels )} ) Summary: parse_qwen_detections sanitizes Qwen3-VL’s JSON output, converts normalized 0–1000 coordinates into exact image pixels, and returns a drop-in sv.Detections object.
How Do You Draw Resolution-Aware Bounding Boxes with Roboflow Supervision? How does annotate_image prevent tiny unreadable text labels on high-resolution images? It dynamically computes proportional font sizes and stroke widths from the image’s exact (width, height) dimensions using sv.calculate_optimal_text_scale and sv.calculate_optimal_line_thickness before drawing any boxes.
Hardcoding thickness=2 and font_scale=0.5 is one of the fastest ways to ruin computer vision visualizations: boxes look bloated on small thumbnails and microscopic on high-resolution photos. In annotate_image, we avoid hardcoded styling completely by letting Roboflow supervision calculate geometry-aware proportions from annotated.size.
First, we clone the input PIL.Image with image.copy() so the original image buffer stays untouched in memory. Next, we instantiate sv.BoxAnnotator with color_lookup=sv.ColorLookup.INDEX, which automatically assigns distinct, high-contrast colors to every detected object even when all items share the same "chair" label.
Alongside the boxes, sv.LabelAnnotator renders clean black text over color-matched pill backgrounds with smart_position=True. Enabling smart_position=True automatically shifts overlapping text tags so adjacent labels never collide or obscure neighboring detections.
### Define the visualization helper to draw bounding boxes and labels onto a PIL Image. def annotate_image ( image : Image . Image , detections : sv . Detections ) -> Image . Image : ### Clone the input image to avoid mutating the original image buffer in place. annotated = image . copy () ### Calculate proportional font scale based on the image's pixel resolution. text_scale = sv . calculate_optimal_text_scale ( resolution_wh = annotated . size ) ### Calculate proportional bounding box border thickness based on image dimensions. thickness = sv . calculate_optimal_line_thickness ( resolution_wh = annotated . size ) ### Initialize Supervision's BoxAnnotator with per-index color assignment. box_annotator = sv . BoxAnnotator ( color_lookup = sv . ColorLookup . INDEX , thickness = thickness ) ### Initialize Supervision's LabelAnnotator with smart label positioning to prevent overlaps. label_annotator = sv . LabelAnnotator ( color_lookup = sv . ColorLookup . INDEX , text_color = sv . Color . BLACK , text_scale = text_scale , text_thickness = max ( 1 , thickness - 1 ), smart_position =True ) ### Draw the bounding box rectangles onto the image copy. annotated = box_annotator . annotate ( annotated , detections ) ### Draw the text class labels onto the annotated image copy. annotated = label_annotator . annotate ( annotated , detections ) ### Return the fully annotated PIL Image. return annotated Summary: annotate_image pairs sv.BoxAnnotator and sv.LabelAnnotator with automatic resolution scaling and smart label placement to produce clean, legible Qwen3-VL object detection visuals.
How Do You Connect the Entire Zero-Shot Pipeline and Test It on Real Images? Why does detect_and_visualize call .convert("RGB") immediately after opening image_path? PNG screenshots frequently contain a 4th alpha transparency channel (RGBA), and converting to strict 3-channel RGB prevents channel-mismatch tensor errors inside Qwen3-VL’s vision processor.
Now that our inference, coordinate parsing, and visualization blocks are built, detect_and_visualize orchestrates all five execution stages behind a single clean function call. It opens the target image from disk, forces 3-channel RGB mode, captures image.size, and invokes run_qwen_vl_inference to retrieve Qwen3-VL’s raw JSON coordinates.
Immediately afterward, it passes that JSON string into parse_qwen_detections to generate an sv.Detections object, feeds the detections into annotate_image, saves the resulting JPEG/PNG if output_path is provided, and renders a side-by-side Matplotlib comparison window. Inside the if __name__ == "__main__": entry point, we put the complete Qwen3-VL object detection pipeline to the test on "chairs.PNG".
Notice how expressive and natural the prompt is: "Locate every chair in the image and output their coordinates in JSON format with 'bbox_2d' and 'label'." Without training a single weight or labeling a single bounding box beforehand, Qwen3-VL locates all three office chairs—mesh ergonomic chair, yellow armchair, and black executive chair—and saves the annotated output to "output_chairs.jpg".
Here is the “chairs” image :
AI Object Detection Without Training: How Qwen3-VL Replaces YOLO in Python 13
### Define the end-to-end orchestration function combining inference, parsing, saving, and plotting. def detect_and_visualize ( image_path : str , prompt : str , system_message : Optional [ str ] = None , output_path : Optional [ str ] = None , show_plot : bool = True ) -> Image . Image : ### Open the target image from disk and convert to 3-channel RGB to strip any alpha channel. image = Image . open ( image_path ). convert ( " RGB " ) ### Extract the (width, height) pixel dimensions of the input image. resolution_wh = image . size ### Run Step 3 to send the image and text prompt to Qwen3-VL and retrieve raw JSON output. response = run_qwen_vl_inference ( model = model , processor = processor , image = image , prompt = prompt , system_message = system_message ) ### Print the raw JSON string returned by Qwen3-VL to the console for inspection. print ( " Model response: \n " , response ) ### Run Step 4 to parse JSON and rescale normalized 0-1000 boxes into pixel coordinates. detections = parse_qwen_detections ( response = response , resolution_wh = resolution_wh ) ### Run Step 5 to draw bounding boxes and labels onto the image using Supervision. annotated_image = annotate_image ( image = image , detections = detections ) ### Save the annotated output image to disk if an output file path was specified. if output_path : annotated_image . save ( output_path ) print ( f "Saved to { output_path } " ) ### Display the original and annotated images side-by-side in a Matplotlib figure if enabled. if show_plot : fig , axes = plt . subplots ( 1 , 2 , figsize = ( 14 , 7 )) axes [ 0 ]. imshow ( image ) axes [ 0 ]. set_title ( " Original " ) axes [ 0 ]. axis ( " off " ) axes [ 1 ]. imshow ( annotated_image ) axes [ 1 ]. set_title ( " Qwen3-VL Detections " ) axes [ 1 ]. axis ( " off " ) plt . tight_layout () plt . show () ### Return the annotated PIL Image object for further programmatic use. return annotated_image ### Execute the full zero-shot object detection pipeline when running the script directly. if __name__ == " __main__ " : ### Run detection on 'chairs.PNG' using a plain-English JSON prompt and save 'output_chairs.jpg'. detect_and_visualize ( image_path = " chairs.PNG " , prompt = ( " Locate every chair in the image and output their coordinates " " in JSON format with 'bbox_2d' and 'label'. " ), output_path = " output_chairs.jpg " , show_plot =True ) Summary: Calling detect_and_visualize executes the entire Qwen3-VL object detection workflow in one pass—reading "chairs.PNG", printing the JSON coordinates, rendering bounding boxes with Supervision, and saving "output_chairs.jpg".
Here is the Result :
AI Object Detection Without Training: How Qwen3-VL Replaces YOLO in Python 14 Frequently Asked Questions (FAQ) Can I run Qwen3-VL object detection on an 8GB VRAM GPU like an RTX 3060 Ti or RTX 4060? Yes. Loading Qwen/Qwen3-VL-2B-Instruct with dtype=torch.bfloat16 and device_map=”auto” uses roughly 4.5GB to 5.5GB of VRAM, leaving enough memory headroom for image token processing on any 8GB NVIDIA GPU.
Why does Qwen3-VL output bounding box coordinates on a 0 to 1000 scale instead of actual pixels? Vision-Language Models normalize spatial coordinates onto a fixed 0 to 1000 grid so the language head can predict consistent numbers regardless of an image’s original resolution. You divide each coordinate by 1000.0 and multiply by the image’s width and height to recover exact pixel coordinates.
Do I need to label a dataset or fine-tune Qwen3-VL before detecting custom objects? No. Because Qwen3-VL-2B-Instruct is a zero-shot, open-vocabulary Vision-Language Model, you can detect new object categories immediately just by changing the target description inside your text prompt.
Why do we set MIN_PIXELS = 256 * 32 * 32 and MAX_PIXELS = 1280 * 32 * 32 in AutoProcessor? Qwen3-VL divides input images into 32×32 visual patches. Capping MAX_PIXELS prevents high-resolution photos from generating excessive visual tokens that would otherwise trigger a CUDA out-of-memory error on 8GB GPUs.
How does Qwen3-VL object detection compare to YOLOv8 or YOLO11? YOLO models run much faster for real-time 60+ FPS video streams, but they only detect fixed classes they were trained on. Qwen3-VL offers open-vocabulary flexibility, letting you locate arbitrary objects with plain English prompts and zero dataset preparation.
What happens if Qwen3-VL wraps its JSON response in Markdown triple backticks? Our parse_qwen_detections helper explicitly strips “`json and “` tags before calling json.loads(), and wraps parsing in a try/except block so malformed text never crashes your script.
Why must we pin numpy<2.0.0 and opencv-python-headless<4.10 during installation? Several compiled computer vision packages built against NumPy 1.x crash with binary ABI incompatibility errors when NumPy 2.0 or newer is installed. Pinning numpy<2.0.0 guarantees clean compatibility across PyTorch, OpenCV, and Supervision.
Can I detect multiple different object classes in a single Qwen3-VL prompt? Yes. You can ask Qwen3-VL to locate multiple categories at once in JSON format with ‘bbox_2d’ and ‘label’, and Supervision will automatically color-code each detected instance.
Why does the pipeline convert input images using .convert(“RGB”)? PNG files frequently include a fourth alpha transparency channel (RGBA). Converting images to 3-channel RGB ensures consistent tensor shapes for Qwen3-VL’s image processor and avoids channel-dimension errors.
Can I use Qwen3-VL object detection to auto-label datasets for training a faster YOLO model later? Absolutely. Because parse_qwen_detections converts Qwen3-VL’s output directly into a Roboflow sv.Detections object, you can export those detections straight into YOLO or Pascal VOC annotation files using Supervision’s dataset utilities.
Conclusion: Moving Beyond Rigid Datasets with Local Qwen3-VL Object Detection Building a local Qwen3-VL object detection pipeline fundamentally changes how you prototype and deploy computer vision projects. Instead of spending days collecting edge-case photos, drawing thousands of manual bounding boxes, and waiting on custom YOLO training runs every time your project requirements shift, you now have a single Python pipeline that locates any object on demand using natural language prompts.
By combining Qwen/Qwen3-VL-2B-Instruct in bfloat16 precision with bounded 32x32 patch resolutions, a resilient 0–1000 JSON coordinate parser, and Roboflow supervision annotators, you can run accurate, private, zero-shot detection directly on an 8GB VRAM GPU. Whether you use this workflow to inspect images locally, build smart visual search tools, or automatically generate clean training annotations for real-time YOLO models, you now hold a complete, production-ready foundation you can adapt to any visual domain in seconds.
Connect : ☕ Buy me a coffee — https://ko-fi.com/eranfeit
🖥️ Email : feitgemel@gmail.com
🌐 https://eranfeit.net
🤝 Fiverr : https://www.fiverr.com/s/mB3Pbb
Enjoy,
Eran