Computer Vision
Implement computer vision tasks including image classification, object detection, segmentation, and pose estimation using PyTorch and TensorFlow
What this skill does
# Computer Vision
## Overview
Computer vision enables machines to understand visual information from images and videos, powering applications like autonomous driving, medical imaging, and surveillance.
## When to Use
- Image classification and object recognition tasks
- Object detection and localization in images
- Semantic or instance segmentation projects
- Pose estimation and human activity recognition
- Face recognition and biometric systems
- Medical imaging analysis and diagnostics
## Computer Vision Tasks
- **Image Classification**: Categorizing images into classes
- **Object Detection**: Locating and classifying objects in images
- **Semantic Segmentation**: Pixel-level classification
- **Instance Segmentation**: Detecting individual object instances
- **Pose Estimation**: Identifying human body joints
- **Face Recognition**: Identifying individuals in images
## Popular Architectures
- **Classification**: ResNet, VGG, EfficientNet, Vision Transformer
- **Detection**: YOLO, Faster R-CNN, SSD, RetinaNet
- **Segmentation**: U-Net, DeepLab, Mask R-CNN
- **Pose**: OpenPose, PoseNet, HRNet
## Python Implementation
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image, ImageDraw
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
from torchvision import transforms, models, datasets
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import cv2
from sklearn.metrics import accuracy_score, confusion_matrix
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
print("=== 1. Image Classification CNN ===")
# Define image classification model
class ImageClassifierCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.BatchNorm2d(32),
nn.MaxPool2d(2, 2),
nn.Conv2d(32, 64, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.BatchNorm2d(64),
nn.MaxPool2d(2, 2),
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.BatchNorm2d(128),
nn.MaxPool2d(2, 2),
)
self.classifier = nn.Sequential(
nn.Linear(128 * 4 * 4, 256),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(256, num_classes)
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
model = ImageClassifierCNN(num_classes=10)
print(f"Model parameters: {sum(p.numel() for p in model.parameters()):,}")
# 2. Object Detection setup
print("\n=== 2. Object Detection Framework ===")
class ObjectDetector(nn.Module):
def __init__(self):
super().__init__()
# Backbone
self.backbone = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
nn.Conv2d(32, 64, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2, 2),
)
# Bounding box regression
self.bbox_head = nn.Sequential(
nn.Linear(64 * 8 * 8, 128),
nn.ReLU(),
nn.Linear(128, 4) # x, y, w, h
)
# Class prediction
self.class_head = nn.Sequential(
nn.Linear(64 * 8 * 8, 128),
nn.ReLU(),
nn.Linear(128, 10) # 10 classes
)
def forward(self, x):
features = self.backbone(x)
features_flat = features.view(features.size(0), -1)
bboxes = self.bbox_head(features_flat)
classes = self.class_head(features_flat)
return bboxes, classes
detector = ObjectDetector()
print(f"Detector parameters: {sum(p.numel() for p in detector.parameters()):,}")
# 3. Semantic Segmentation
print("\n=== 3. Semantic Segmentation U-Net ===")
class UNet(nn.Module):
def __init__(self, num_classes=5):
super().__init__()
# Encoder
self.enc1 = self._conv_block(3, 32)
self.pool1 = nn.MaxPool2d(2, 2)
self.enc2 = self._conv_block(32, 64)
self.pool2 = nn.MaxPool2d(2, 2)
# Bottleneck
self.bottleneck = self._conv_block(64, 128)
# Decoder
self.upconv2 = nn.ConvTranspose2d(128, 64, 2, stride=2)
self.dec2 = self._conv_block(128, 64)
self.upconv1 = nn.ConvTranspose2d(64, 32, 2, stride=2)
self.dec1 = self._conv_block(64, 32)
# Final output
self.out = nn.Conv2d(32, num_classes, 1)
def _conv_block(self, in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True)
)
def forward(self, x):
enc1 = self.enc1(x)
enc2 = self.enc2(self.pool1(enc1))
bottleneck = self.bottleneck(self.pool2(enc2))
dec2 = self.dec2(torch.cat([self.upconv2(bottleneck), enc2], 1))
dec1 = self.dec1(torch.cat([self.upconv1(dec2), enc1], 1))
return self.out(dec1)
unet = UNet(num_classes=5)
print(f"U-Net parameters: {sum(p.numel() for p in unet.parameters()):,}")
# 4. Transfer Learning
print("\n=== 4. Transfer Learning with Pre-trained Models ===")
try:
# Load pre-trained ResNet18
pretrained_model = models.resnet18(pretrained=True)
num_ftrs = pretrained_model.fc.in_features
pretrained_model.fc = nn.Linear(num_ftrs, 10)
print(f"Pre-trained ResNet18 adapted for 10 classes")
print(f"Parameters: {sum(p.numel() for p in pretrained_model.parameters()):,}")
except:
print("Pre-trained models not available")
# 5. Image preprocessing and augmentation
print("\n=== 5. Image Preprocessing and Augmentation ===")
transform_basic = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
transform_augmented = transforms.Compose([
transforms.RandomRotation(20),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.2, contrast=0.2),
transforms.RandomAffine(degrees=0, translate=(0.1, 0.1)),
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
print("Augmentation transforms defined")
# 6. Synthetic image data
print("\n=== 6. Synthetic Image Data Creation ===")
def create_synthetic_images(num_images=100, img_size=32):
"""Create synthetic images with shapes"""
images = []
labels = []
for _ in range(num_images):
img = np.ones((img_size, img_size, 3)) * 255
# Randomly draw shapes
shape_type = np.random.randint(0, 3)
if shape_type == 0: # Circle
center = (np.random.randint(5, img_size-5), np.random.randint(5, img_size-5))
radius = np.random.randint(3, 10)
cv2.circle(img, center, radius, (0, 0, 0), -1)
labels.append(0)
elif shape_type == 1: # Rectangle
pt1 = (np.random.randint(0, img_size-10), np.random.randint(0, img_size-10))
pt2 = (pt1[0] + np.random.randint(5, 15), pt1[1] + np.random.randint(5, 15))
cv2.rectangle(img, pt1, pt2, (0, 0, 0), -1)
labels.append(1)
else: # Triangle
pts = np.array([[np.random.randint(0, img_size), np.random.randint(0, img_size)],
[np.random.randint(0, img_size), np.random.randint(0, img_size)],
[np.random.randint(0, img_size), np.random.randint(0, img_size)]])
cv2.drawContours(img, [pts], 0, Related in Image & Video
watch
IncludedWatch a video (URL or local path). Downloads with yt-dlp, extracts auto-scaled frames with ffmpeg, pulls the transcript from captions (or Whisper API fallback), and hands the result to Claude so it can answer questions about what's in the video.
physical-ai-defect-image-generation
IncludedUse when the user wants to orchestrate defect image generation, run associated setup, or handle outputs on OSMO. The Day 0 path handles cold-start with USD-to-ROI, image-edit augmentation, and AnomalyGen to create initial PCBA datasets. The Day 1 path performs inference and labeling on real images. This skill helps with first-time asset setup, creation of finetuning checkpoints, and configuring deployment. Trigger keywords: defect image generation, dig workflow, dig pipeline, defect image detection workflow, aoi pipeline, aoi anomalygen, usd2roi anomalygen, day 0 pcba, day 1 pcba, day 1 real-photo alignment, day 1 manual roi, metal surface anomaly, glass defect, anomalygen finetune, setup_pcb, setup_metal, setup_glass, setup_pretrained, dig setup, dig datasets, dig pretrained checkpoint, dig image-edit endpoint.
accelint-react-best-practices
IncludedReact performance optimization and best practices. ALWAYS use this skill when working with any React code - writing components, hooks, JSX; refactoring; optimizing re-renders, memoization, state management; reviewing for performance; fixing hydration mismatches; debugging infinite re-renders, stale closures, input focus loss, animations restarting; preventing remounting; implementing transitions, lazy initialization, effect dependencies. Even simple React tasks benefit from these patterns. Covers React 19+ (useEffectEvent, Activity, ref props). Triggers - useEffect, useState, useMemo, useCallback, memo, inline components, nested components, components inside components, re-render, performance, hydration, SSR, Next.js, useDeferredValue, combined hooks.
elevenlabs-agents
IncludedBuild conversational AI voice agents with ElevenLabs Platform using React, JavaScript, React Native, or Swift SDKs. Configure agents, tools (client/server/MCP), RAG knowledge bases, multi-voice, and Scribe real-time STT. Use when: building voice chat interfaces, implementing AI phone agents with Twilio, configuring agent workflows or tools, adding RAG knowledge bases, testing with CLI "agents as code", or troubleshooting deprecated @11labs packages, Android audio cutoff, CSP violations, dynamic variables, or WebRTC config. Keywords: ElevenLabs Agents, ElevenLabs voice agents, AI voice agents, conversational AI, @elevenlabs/react, @elevenlabs/client, @elevenlabs/react-native, @elevenlabs/elevenlabs-js, @elevenlabs/agents-cli, elevenlabs SDK, voice AI, TTS, text-to-speech, ASR, speech recognition, turn-taking model, WebRTC voice, WebSocket voice, ElevenLabs conversation, agent system prompt, agent tools, agent knowledge base, RAG voice agents, multi-voice agents, pronunciation dictionary, voice speed control, elevenlabs scribe, @11labs deprecated, Android audio cutoff, CSP violation elevenlabs, dynamic variables elevenlabs, case-sensitive tool names, webhook authentication
humanizer
IncludedHumanize AI-generated text by detecting and removing patterns typical of LLM output. Rewrites text to sound natural, specific, and human. Uses 28 pattern detectors, 560+ AI vocabulary terms across 3 tiers, and statistical analysis (burstiness, type-token ratio, readability) for comprehensive detection. Use when asked to humanize text, de-AI writing, make content sound more natural/human, review writing for AI patterns, score text for AI detection, or improve AI-generated drafts. Covers content, language, style, communication, and filler categories.
generating-mermaid-diagrams
IncludedSalesforce architecture diagrams using Mermaid with ASCII fallback. Use this skill when generating text-based diagrams for Salesforce architecture, OAuth flows, ERDs, integration sequences, or Agentforce structure. TRIGGER when: user says "diagram", "visualize", "ERD", or asks for sequence diagrams, flowcharts, class diagrams, or architecture visualizations in Mermaid. DO NOT TRIGGER when: user wants PNG/SVG image output (use generating-visual-diagrams), or asks about non-Salesforce systems.