How I Built a Game Asset Search Engine Using CLIP and Qdrant (With Real Assets)
From the publisher’s feed, collected in the ZeroLabs newsroom.
A weekend project that turned into something I actually want to useSource: Image By AuthorI have been experimenting with vector databases for a while now. Most tutorials I found used the same examples like searching through movie descriptions or finding similar news articles. They’re okay for demonstrations, but they didn’t feel exciting enough to actually work on.Then one evening I was browsing free game asset packs on Kenney.nl, and I had a simple thought: what if a game developer could just type a term like “red car” and get every matching asset based on that query? No need for browsing multiple folders, no guessing file names. Just describe what you want and get it back.That question turned into this project.I built a semantic search engine over real game assets using CLIP for embeddings and Qdrant as the vector database. It supports three search modes namely text to asset, image to image, and asset to asset. The entire thing runs in Google Colab for free.This article will explain the code, explain what is happening and why, and is written so that even if you have never heard of vector search before, you will follow along.Why Qdrant?Before understanding the code, this question is worth answering properly because there are other vector databases out there such as Pinecone, Weaviate, Chroma, FAISS.I picked Qdrant for a few reasons. First, it has a clean Python client that does not require a running server for small projects. This means you can run it entirely in memory with one line. Second, it supports payload filtering, which means you can combine vector search with structured filters like “search only within the Fantasy category.” Third, it is open source, fast, and the documentation is actually readable.For this project, Qdrant runs in-memory inside Colab. No cloud account. No API key. No server to deal with. Just install the client and start using it.What we are buildingWe have three game asset packs from Kenney.nl:Car Kit — about 50 vehicle preview imagesFantasy Town Kit — 167 medieval buildings and props imagesGraveyard Kit — 91 graveyard environment imagesSource: Image By AuthorAll three packs come with rendered PNG images. We use only those preview images and not the 3D model files.The search engine we build will let you:Type a description like "stone tower" and get back the closest matching assetsPick an image from the library and find visually similar onesUpload any external image and find matching assetsThe entire pipeline is: load images → embed with CLIP → store in Qdrant → search.Part 1: Setup and Loading AssetsInstalling the libraries!pip install qdrant-client open-clip-torch Pillow matplotlib tqdm -qprint("All dependencies installed!")The main libraries used here:qdrant-client is the Python SDK for Qdrant. It handles creating collections, storing vectors, and performing searches.open-clip-torch is an open source implementation of OpenAI's CLIP model. CLIP is the model that converts both images and text into vectors. It is completely free and no API key needed.Pillow handles image loading and processing. matplotlib handles visualization. tqdm gives us progress bars when embedding hundreds of images.Uploading your asset ZIPimport osimport zipfilefrom google.colab import filesprint(" Upload your 'Game Images.zip' file...")uploaded = files.upload()zip_filename = list(uploaded.keys())[0]print(f" Uploaded: {zip_filename}")ASSETS_DIR = "/content/game_assets"os.makedirs(ASSETS_DIR, exist_ok=True)with zipfile.ZipFile(zip_filename, 'r') as zip_ref: zip_ref.extractall(ASSETS_DIR)print(f" Extracted to {ASSETS_DIR}")print("\n Extracted structure:")for root, dirs, files_list in os.walk(ASSETS_DIR): level = root.replace(ASSETS_DIR, '').count(os.sep) indent = ' ' * level folder_name = os.path.basename(root) if level print(f"{indent} {folder_name}/") if level == 1: img_count = len([f for f in files_list if f.lower().endswith(('.png', '.jpg', '.jpeg'))]) if img_count > 0: print(f"{indent} └── {img_count} images found")The asset packs are compressed into one ZIP file with this structure:Game Images/ Fantasy_Preview/ Graveyard_Preview/ Car_Preview/files.upload() opens a Colab file picker that allows the user to upload the asset files. After the user uploads the ZIP, we extract it to /content/game_assets. The loop at the end just prints what was found so you can confirm the structure is right.Discovering all assetsimport osimport pandas as pdfrom pathlib import Pathdef discover_assets(base_dir): assets = [] supported_formats = ('.png', '.jpg', '.jpeg', '.webp') for root, dirs, files in os.walk(base_dir): for file in files: if file.lower().endswith(supported_formats): filepath = os.path.join(root, file) parent_folder = os.path.basename(root) # Skip root-level folder if parent_folder.lower() in ['game_assets', 'game images', 'game-images']: continue # Clean category name category = parent_folder.replace('_Preview', '').replace('_preview', '') category = category.replace('_', ' ').strip() # Clean asset name name = Path(file).stem name = name.replace('_', ' ').replace('-', ' ').strip() tags = list(set([name.lower(), category.lower()] + name.lower().split())) assets.append({ 'id': len(assets), 'name': name, 'category': category, 'filename': file, 'filepath': filepath, 'tags': tags, 'description': f"{name} — {category} game asset" }) return assetsall_assets = discover_assets(ASSETS_DIR)df = pd.DataFrame(all_assets)print(f" Total assets discovered: {len(df)}")print("\n Assets per category:")print(df['category'].value_counts().to_string())print("\n Sample assets:")print(df[['name', 'category', 'filename']].head(10).to_string(index=False))Output:Total assets discovered: 308Assets per category:categoryFantasy 167Graveyard 91Car 50 Sample assets: name category filename gravestone round Graveyard gravestone-round.png stone wall curve Graveyard stone-wall-curve.png column large Graveyard column-large.png pillar small Graveyard pillar-small.png fence damaged Graveyard fence-damaged.png cross Graveyard cross.pngiron fence border Graveyard iron-fence-border.png gravestone roof Graveyard gravestone-roof.png lantern glass Graveyard lantern-glass.png lightpost single Graveyard lightpost-single.pngThis function goes through every folder and builds a catalogue of all images it finds.For each image, it extracts two important pieces of information. The category comes from the folder name i.e. Fantasy_Preview becomes Fantasy, Car_Preview becomes Car. The name comes from the filename i.e. suv.png becomes suv, stone tower.png becomes stone tower.We also build a tags list by splitting the name into individual words. So an asset named lightpost double gets tags ["lightpost", "double", "graveyard"]. This is stored as metadata alongside the vector in Qdrant.Everything goes in a pandas DataFrame so it is easy to work with before embedding.Previewing sample assetsimport matplotlib.pyplot as pltimport matplotlib.patches as patchesfrom PIL import Imageimport randomdef show_asset_grid(assets_df, n_per_category=4, title="Game Asset Library"): categories = assets_df['category'].unique() n_cats = len(categories) fig, axes = plt.subplots(n_cats, n_per_category, figsize=(n_per_category * 3, n_cats * 3)) fig.patch.set_facecolor('#1a1a2e') fig.suptitle(title, fontsize=18, fontweight='bold', color='white', y=1.02) if n_cats == 1: axes = [axes] for cat_idx, category in enumerate(categories): cat_assets = assets_df[assets_df['category'] == category].sample( min(n_per_category, len(assets_df[assets_df['category'] == category])) ) for img_idx in range(n_per_category): ax = axes[cat_idx][img_idx] ax.set_facecolor('#16213e') if img_idx asset = cat_assets.iloc[img_idx] try: img = Image.open(asset['filepath']).convert('RGBA') background = Image.new('RGBA', img.size, (22, 33, 62, 255)) background.paste(img, mask=img.split()[3] if img.mode == 'RGBA' else None) ax.imshow(background) ax.set_title(asset['name'][:15], fontsize=8, color='#a8dadc', pad=3) except Exception as e: ax.text(0.5, 0.5, '?', ha='center', va='center', color='white') ax.axis('off') if img_idx == 0: ax.set_ylabel(category, fontsize=11, color='#e63946', fontweight='bold', rotation=90, labelpad=10) ax.yaxis.set_label_position('left') plt.tight_layout() plt.show()show_asset_grid(df, n_per_category=4, title=" Game Asset Library — Kenney.nl")Output:Source: Image By AuthorBefore performing embedding, I just wanted to look at what we have. This function builds a grid, one row per category, four sample images per row. The Kenney assets have transparent backgrounds so we paste them onto a dark background before rendering, which makes them look much cleaner in the grid.Part 2: Embedding with CLIPThis is the the main part of the whole system. Understanding what happens here makes everything else make sense.What CLIP actually doesSource: Image By AuthorCLIP (Contrastive Language-Image Pretraining) is a model that was trained on hundreds of millions of image-text pairs from the internet. During training, it learned to map images and their descriptions to nearby locations in a shared 512-dimensional vector space.What this means is, if you embed a photo of a car and you also embed the text “car”, both end up as vectors that are close to each other in that 512-dimensional space. They do not need to be identical but just need to be in the same region.This is why the same search works for both text and image queries. Both get converted into the same kind of vector, and Qdrant compares them the same way.Loading the modelimport torchimport open_clipfrom PIL import Imageimport numpy as npprint("Loading CLIP model (1-2 mins on first run)...")MODEL_NAME = 'ViT-B-32'PRETRAINED = 'openai'model, _, preprocess = open_clip.create_model_and_transforms(MODEL_NAME, pretrained=PRETRAINED)tokenizer = open_clip.get_tokenizer(MODEL_NAME)device = "cuda" if torch.cuda.is_available() else "cpu"model = model.to(device)model.eval()EMBEDDING_DIM = 512print(f"CLIP loaded on: {device.upper()}")print(f" Model: {MODEL_NAME}")print(f" Embedding dimension: {EMBEDDING_DIM}")We are using ViT-B-32 — Vision Transformer Base with patch size 32. It is the smallest and fastest CLIP variant, which is why it works well on Colab's free CPU tier. The model downloads from Hugging Face and is cached, so the second run is super fast.tokenizer handles text i.e. it converts a string like "stone tower" into token IDs that the text encoder understands.model.eval() puts the model in inference mode, which disables things like dropout that are only needed during training.Embedding every assetfrom tqdm import tqdmdef embed_image(image_path, model, preprocess, device): try: img = Image.open(image_path).convert('RGB') img_tensor = preprocess(img).unsqueeze(0).to(device) with torch.no_grad(): features = model.encode_image(img_tensor) features = features / features.norm(dim=-1, keepdim=True) return features.cpu().numpy()[0].tolist() except Exception as e: print(f" Could not embed {image_path}: {e}") return Nonedef embed_text(text, model, tokenizer, device): tokens = tokenizer([text]).to(device) with torch.no_grad(): features = model.encode_text(tokens) features = features / features.norm(dim=-1, keepdim=True) return features.cpu().numpy()[0].tolist()print(f" Embedding {len(df)} assets with CLIP...")embeddings = []failed = []for idx, row in tqdm(df.iterrows(), total=len(df), desc=" Embedding"): embedding = embed_image(row['filepath'], model, preprocess, device) embeddings.append(embedding) if embedding is None: failed.append(idx)df['embedding'] = embeddingsdf_clean = df[df['embedding'].notna()].reset_index(drop=True)df_clean['id'] = range(len(df_clean))print(f"\n Successfully embedded: {len(df_clean)} assets")if failed: print(f" Failed: {len(failed)} assets")Two functions here: one for images, one for text. They both follow the same pattern:Prepare the input (preprocess image, or tokenize text)Run it through the model with torch.no_grad().This tells PyTorch not to track gradients since we are only doing inference, not trainingL2 normalize the output vectorThat normalization step at the end: features / features.norm() is important. It scales every vector to have length 1. When all vectors have the same length, measuring the angle between them (cosine similarity) is the same as measuring their dot product. Qdrant's cosine distance works correctly when vectors are normalized.After embedding, we store the vectors back into the DataFrame and drop any that failed. Each asset now has a 512-number vector attached to it.Part 3: Indexing in QdrantCreating the collection and storing vectorsfrom qdrant_client import QdrantClientfrom qdrant_client.models import ( Distance, VectorParams, PointStruct, Filter, FieldCondition, MatchValue)client = QdrantClient(":memory:")COLLECTION_NAME = "game_assets"client.create_collection( collection_name=COLLECTION_NAME, vectors_config=VectorParams(size=EMBEDDING_DIM, distance=Distance.COSINE))points = []for _, row in df_clean.iterrows(): points.append(PointStruct( id=int(row['id']), vector=row['embedding'], payload={ "name": row['name'], "category": row['category'], "filename": row['filename'], "filepath": row['filepath'], "tags": row['tags'], "description": row['description'] } ))client.upsert(collection_name=COLLECTION_NAME, points=points)info = client.get_collection(COLLECTION_NAME)print(f" Indexed {info.points_count} assets into Qdrant!")print(f" Collection: {COLLECTION_NAME}")print(f" Distance metric: Cosine Similarity")QdrantClient(":memory:") starts an in-memory Qdrant instance. No server. No port. It just works inside the current Python process.create_collection sets up a named collection. The two things you must specify are the vector size (512 for CLIP ViT-B-32) and the distance metric. We use COSINE which measures how similar the directions of two vectors are, irrespective of their magnitude.Each asset becomes a PointStruct with three parts: an integer id, the 512-number vector, and a payload dictionary. The payload is where we store the metadata: name, category, filepath, tags.Part 4: SearchThe search helper functionsimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport matplotlib.patches as patchesfrom qdrant_client.models import Filter, FieldCondition, MatchValue, RecommendInput, RecommendQueryCATEGORY_COLORS = { 'Fantasy': '#f4a261', 'Graveyard': '#a8dadc', 'Car': '#e63946', 'default': '#ffffff'}def get_category_color(category): for key in CATEGORY_COLORS: if key.lower() in category.lower(): return CATEGORY_COLORS[key] return CATEGORY_COLORS['default']def search_by_text(query_text, top_k=6, category_filter=None): """Search assets using a text description.""" query_vector = embed_text(query_text, model, tokenizer, device) search_filter = None if category_filter: search_filter = Filter(must=[FieldCondition(key="category", match=MatchValue(value=category_filter))]) results = client.query_points( collection_name=COLLECTION_NAME, query=query_vector, limit=top_k, query_filter=search_filter, with_payload=True ) return results.points # ← .points extracts the list from the response objectdef search_by_image(image_path, top_k=6, category_filter=None): """Search assets using an image as query.""" query_vector = embed_image(image_path, model, preprocess, device) search_filter = None if category_filter: search_filter = Filter(must=[FieldCondition(key="category", match=MatchValue(value=category_filter))]) results = client.query_points( collection_name=COLLECTION_NAME, query=query_vector, limit=top_k, query_filter=search_filter, with_payload=True ) return results.pointsdef search_by_asset_id(asset_id, top_k=6): """Find assets similar to an existing asset — 'More like this'.""" results = client.query_points( collection_name=COLLECTION_NAME, query=models.RecommendQuery( recommend=models.RecommendInput(positive=[asset_id]) ), limit=top_k, with_payload=True ) return results.pointsdef visualize_results(results, query_label, query_image_path=None, save_path=None): """Render search results as a styled image grid.""" n = len(results) if n == 0: print("No results found.") return has_query_img = query_image_path is not None cols = n + 1 if has_query_img else n fig = plt.figure(figsize=(cols * 2.8, 4.5)) fig.patch.set_facecolor('#0d0d1a') gs = gridspec.GridSpec(1, cols, figure=fig, wspace=0.08) col_offset = 0 if has_query_img: ax_q = fig.add_subplot(gs[0, 0]) ax_q.set_facecolor('#1a1a3e') try: qimg = Image.open(query_image_path).convert('RGB') ax_q.imshow(qimg) except: ax_q.text(0.5, 0.5, '', ha='center', va='center', fontsize=24, transform=ax_q.transAxes) ax_q.set_title("QUERY", fontsize=9, color='white', fontweight='bold', pad=4, bbox=dict(boxstyle='round,pad=0.3', facecolor='#e63946', alpha=0.9)) ax_q.axis('off') col_offset = 1 for i, hit in enumerate(results): ax = fig.add_subplot(gs[0, i + col_offset]) ax.set_facecolor('#16213e') payload = hit.payload score = hit.score category = payload.get('category', 'Unknown') name = payload.get('name', 'Unknown') cat_color = get_category_color(category) try: img = Image.open(payload['filepath']).convert('RGBA') bg = Image.new('RGBA', img.size, (22, 33, 62, 255)) bg.paste(img, mask=img.split()[3] if img.mode == 'RGBA' else None) ax.imshow(bg) except: ax.text(0.5, 0.5, '?', ha='center', va='center', color='white', fontsize=20, transform=ax.transAxes) # Score bar ax.add_patch(patches.Rectangle((0, 0), 1, 0.04, transform=ax.transAxes, color='#333344', alpha=0.5, zorder=9)) ax.add_patch(patches.Rectangle((0, 0), score, 0.04, transform=ax.transAxes, color=cat_color, alpha=0.85, zorder=10)) ax.set_title(f"{name[:14]}\n{score:.3f} similarity", fontsize=7.5, color='white', pad=3, linespacing=1.4) ax.text(0.02, 0.97, category, transform=ax.transAxes, fontsize=6, color='#0d0d1a', fontweight='bold', va='top', ha='left', bbox=dict(boxstyle='round,pad=0.2', facecolor=cat_color, alpha=0.95)) ax.text(0.97, 0.97, f"#{i+1}", transform=ax.transAxes, fontsize=8, color='white', fontweight='bold', va='top', ha='right') ax.axis('off') fig.text(0.5, 1.02, f' "{query_label}"', ha='center', va='bottom', fontsize=13, color='white', fontweight='bold', transform=fig.transFigure) plt.tight_layout() if save_path: plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor='#0d0d1a') plt.show() print(f"\n{'Rank': print("-" * 55) for i, hit in enumerate(results): p = hit.payload print(f"#{i+1:print(" Search functions ready!")Three search functions, all calling client.query_points which is the current Qdrant API (older versions used client.search which has since been removed).search_by_text takes a string, converts it to a vector using the CLIP text encoder, then asks Qdrant to find the closest stored vectors.search_by_image does the same thing but with an image path. The image gets encoded by the CLIP image encoder and that vector is used as the query.search_by_asset_id takes the ID of an asset already in the collection and finds similar ones.The optional category_filter in the first two functions lets you narrow results to one category.Visualizing resultsThe visualize_results function takes the search results and renders them as an image grid. If a query image was provided (for image-to-image search), it appears in the first column labeled “QUERY”. The remaining columns show the top matching assets in order of similarity.Part 5 : Running the SearchesDemo 1: Text to asset search# These are our queriesqueries = [ "police emergency vehicle", "dark spooky tombstone", "medieval castle tower"]for query in queries: print(f"\n{'='*55}") print(f" Query: '{query}'") results = search_by_text(query, top_k=6) visualize_results(results, query)Output:Source: Image By AuthorShort, descriptive keyword phrases work best with CLIP. "police emergency vehicle" will correctly select the police car and ambulance assets from the car pack. "dark spooky tombstone" pulls from the graveyard pack. "medieval castle tower" pulls fantasy buildings.CLIP was trained on image captions, and not conversational sentences, so short descriptive phrases give the best results.Demo 2: Image to image search# Picks a random asset from each category and finds similar onesfor category_keyword in ['Car', 'Fantasy', 'Graveyard']: cat_assets = df_clean[df_clean['category'].str.contains(category_keyword, case=False, na=False)] if len(cat_assets) == 0: print(f" No assets found for category: {category_keyword}") continue query_asset = cat_assets.sample(1).iloc[0] print(f"\n{'='*55}") print(f" Query: '{query_asset['name']}' from [{query_asset['category']}]") results = search_by_image(query_asset['filepath'], top_k=6) visualize_results( results, f"Similar to: {query_asset['name']}", query_image_path=query_asset['filepath'] )Source: Image By AuthorThis picks a random asset from each category and finds the top six similar assets. Because CLIP captures visual meaning, it groups things that are visually similar. Query with a car and you get vehicles. Query with a tombstone and you get other graveyard props.Demo 3: Upload your own imagefrom google.colab import files as colab_filesprint(" Upload any image to search with (concept art, screenshot, anything!)")uploaded_query = colab_files.upload()if uploaded_query: query_filename = list(uploaded_query.keys())[0] query_path = f"/content/{query_filename}" with open(query_path, 'wb') as f: f.write(uploaded_query[query_filename]) print(f"\n Searching with: {query_filename}\n") results = search_by_image(query_path, top_k=6) visualize_results(results, f"Uploaded: {query_filename}", query_image_path=query_path)Output:Source: Image By AuthorThis is the most powerful demo. Upload any image, it could be a screenshot from another game, or a reference photo and the system finds the closest matching assets in the library. Because CLIP understands visual concepts, even a rough sketch of a tower can pull up the right fantasy building assets.What this would look like in a real game studioThis notebook is a proof of concept. The core idea scales well where we would embed assets, store vectors, search by text or image. In a real production environment you would make a few changes.Instead of in-memory Qdrant you would run a persistent Qdrant instance, either self-hosted or on Qdrant Cloud.You would also embed more than just preview images. 3D model files in GLB format can be rendered from multiple angles. Motion capture files (BVH format) need a different encoder such as temporal CNN that processes the sequence of joint positions over time. Textures can be embedded directly as images using the same CLIP pipeline we built here.On the search interface side, you would build a proper UI like a web app or a plugin inside Unity or Unreal Engine, so artists can search directly from within their workflow.But the database layer, the embedding layer, and the search logic would remain exactly what we built here.Source: Image By AuthorReferencesGoogle Colab Notebook — Colab file consisting the codeQdrant — Vector database used in this projectQdrant Python Client DocumentationOpenCLIP — Open source CLIP implementationKenney.nl — Free game assets used in this projectQdrant query_points API referenceHow I Built a Game Asset Search Engine Using CLIP and Qdrant (With Real Assets) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.