惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Stack Overflow Blog
Stack Overflow Blog
Recent Announcements
Recent Announcements
Microsoft Security Blog
Microsoft Security Blog
L
LINUX DO - 最新话题
P
Privacy & Cybersecurity Law Blog
Google DeepMind News
Google DeepMind News
Security Archives - TechRepublic
Security Archives - TechRepublic
云风的 BLOG
云风的 BLOG
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - Franky
PCI Perspectives
PCI Perspectives
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Attack and Defense Labs
Attack and Defense Labs
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Proofpoint News Feed
小众软件
小众软件
A
Arctic Wolf
C
Cybersecurity and Infrastructure Security Agency CISA
F
Fortinet All Blogs
T
Threatpost
Security Latest
Security Latest
V
Vulnerabilities – Threatpost
B
Blog RSS Feed
MongoDB | Blog
MongoDB | Blog
WordPress大学
WordPress大学
Forbes - Security
Forbes - Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
C
CERT Recently Published Vulnerability Notes
AI
AI
博客园 - 三生石上(FineUI控件)
T
Threat Research - Cisco Blogs
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
Schneier on Security
I
Intezer
The GitHub Blog
The GitHub Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
V
V2EX
aimingoo的专栏
aimingoo的专栏
量子位
NISL@THU
NISL@THU
N
News and Events Feed by Topic
O
OpenAI News
Microsoft Azure Blog
Microsoft Azure Blog
C
Check Point Blog
Schneier on Security
Schneier on Security
S
Secure Thoughts
The Cloudflare Blog
J
Java Code Geeks

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building a Real-Time Camera Classifier
Jasmanbir Si · 2026-05-21 · via DEV Community

Building a Real-Time Camera Classifier

Ever wonder how modern interactive displays in malls identify objects, like glasses or accessories, in real-time? These systems rely on computer vision models to classify live video input into predefined categories. This paper outlines the architecture and implementation of a custom camera-based object classifier.

Usage of Camera Classifier

Camera classifiers are instrumental in scenarios where automated visual identification is required without human intervention. Common use cases include:

Retail Analytics: Identifying products or accessories a customer is trying on.

Security & Surveillance: Detecting specific items or prohibited objects.

Human-Computer Interaction: Enabling gesture or item-based control interfaces.

Quality Control: Automatically sorting objects on an assembly line based on visual appearance.

Famous Examples of Camera Classifiers

Google Lens: A sophisticated classifier that identifies objects, plants, and text in real-time.

Self-Driving Car Vision Systems: Used to classify road signs, pedestrians, and other vehicles to ensure safe navigation.

Smart Home Appliances: Cameras on refrigerators or ovens that identify food items to suggest recipes.

Prerequisites

To ensure this code executes correctly and avoids common runtime exceptions, please verify the following requirements before running the script:

  • Hardware: A functional webcam must be physically connected to your system and recognized by your operating system.

  • System Permissions:

    • macOS/Linux: If you are running this code via a terminal or an IDE (such as VS Code or PyCharm), ensure that the application has been granted explicit Camera Access in your system settings.
    • Common Troubleshooting: If you encounter a PermissionError or an OSError: [Errno 16] Device or resource busy, it is typically because the webcam is already being utilized by another application (e.g., Zoom, Microsoft Teams, or a browser tab). Please close all other applications that may be accessing the camera and try again.

Note: If you are working within a virtual environment or a containerized system (like Docker), ensure that the device path (e.g., /dev/video0) is correctly mapped and accessible to the environment.

Implementation

Step 1: Environment Setup

To build this project, you need the necessary libraries for image processing, GUI creation, and deep learning. Install them using the following command in terminal:

pip install opencv-python tensorflow pillow numpy

Enter fullscreen mode Exit fullscreen mode

Project Directory Structure

Use the following structure for your dataset so that tf.keras.utils.image_dataset_from_directory can automatically infer the labels from the folder names:

/your_project_folder
├── 1/
│   ├── frame1.jpg
│   └── frame2.jpg
├── 2/
│   ├── frame1.jpg
│   └── frame2.jpg
├── camera.py
├── model.py
└── app.py

Enter fullscreen mode Exit fullscreen mode

Step 2: Creating the Camera Module (camera.py)

The camera.py file serves as the interface between your physical hardware and the software. Below is the implementation broken down by function to ensure you understand how video data is handled.

Sub-Step 2.1: Initialization (__init__)

This function initializes the connection to your webcam. It attempts to open the default camera (index 0) and captures the video feed dimensions, which are necessary for setting the GUI canvas size later.

Sub-Step 2.2: Clean Shutdown (__del__)

This is a destructor method. It ensures that the camera hardware is properly released when the Camera object is destroyed or the application is closed, preventing the camera from remaining "busy" or locked.

Sub-Step 2.3: Frame Acquisition (get_frame)

This is the core functional unit. It captures an individual image frame from the video stream and converts the color space from BGR (OpenCV default) to RGB (required for display and processing).

Implementation Code

import cv2 as cv

class Camera:
    # Sub-Step 2.1: Initialize the hardware connection
    def __init__(self):
        self.camera = cv.VideoCapture(0)
        if not self.camera.isOpened():
            raise ValueError('Unable to open camera.')

        # Fetching properties for GUI scaling
        self.width = self.camera.get(cv.CAP_PROP_FRAME_WIDTH)
        self.height = self.camera.get(cv.CAP_PROP_FRAME_HEIGHT)

    # Sub-Step 2.2: Ensure proper resource release
    def __del__(self):
        if self.camera.isOpened():
            self.camera.release()

    # Sub-Step 2.3: Process and return the current frame
    def get_frame(self):
        if self.camera.isOpened():
            ret, frame = self.camera.read()

            if ret:
                # Convert BGR to RGB for standard image processing
                return (ret, cv.cvtColor(frame, cv.COLOR_BGR2RGB))
            else:
                return (ret, None)
        else:
            return None

Enter fullscreen mode Exit fullscreen mode

Step 3: Creating the Model Module (model.py)

The model.py file acts as the intelligence core of your application. It manages data ingestion, neural network architecture, and the lifecycle of your classifier (training, saving, and inference).

Sub-Step 3.1:

Data Preparation (load_data)This function reads your images from disk. It creates a tf.data.Dataset, applies a normalization layer (scaling pixel values to a $[0, 1]$ range), and splits the data into training and validation sets.
#### Sub-Step 3.2:
Architecture Design (create_model)Here, we define a Convolutional Neural Network (CNN). We use Conv2D layers to extract visual features and MaxPooling2D to reduce dimensionality, ending with a Dense layer to output the final classification probability.

Sub-Step 3.3:

Training Procedure (train)This function invokes the data loader and model creator. It executes the training process over multiple epochs, saving the final trained weights to a file so you don't have to retrain every time you open the app.

Sub-Step 3.4:

Loading and Inference (load_trained_model & predict)load_trained_model checks for existing files to resume work. predict processes a raw frame by resizing and reshaping it to match the neural network's expected input format, then returns the class index.

Implementation Code

import tensorflow as tf
from tensorflow.keras import layers, models
import os
import numpy as np

# Global configurations
Image_size = (64, 64)
Batch_size = 16
MODEL_PATH = 'Camera_classifier.keras'
DATA_DIR = r"YOUR_PATH_HERE" # Update this to your local directory

# Sub-Step 3.1: Load and normalize images
def load_data():
    train_ds = tf.keras.utils.image_dataset_from_directory(
        DATA_DIR, image_size=Image_size, batch_size=Batch_size, color_mode="grayscale"
    )
    # Scale pixel values
    normalization_layer = layers.Rescaling(1./255)
    train_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))

    val_size = int(len(train_ds) * 0.2)
    val_ds = train_ds.take(val_size)
    train_ds = train_ds.skip(val_size)
    return train_ds.prefetch(tf.data.AUTOTUNE), val_ds.prefetch(tf.data.AUTOTUNE)

# Sub-Step 3.2: Define CNN structure
def create_model():
    model = models.Sequential([
        layers.Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 1)),
        layers.MaxPooling2D(2, 2),
        layers.Conv2D(64, (3, 3), activation='relu'),
        layers.MaxPooling2D(2, 2),
        layers.Flatten(),
        layers.Dense(64, activation='relu'),
        layers.Dense(2, activation='softmax')
    ])
    model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
    return model

# Sub-Step 3.3: Train and Save
def train():
    train_ds, val_ds = load_data()
    model = create_model()
    model.fit(train_ds, epochs=10, validation_data=val_ds)
    model.save(MODEL_PATH)
    return model

# Sub-Step 3.4: Helper functions for loading and prediction
def load_trained_model():
    return tf.keras.models.load_model(MODEL_PATH) if os.path.exists(MODEL_PATH) else None

def predict(frame, model):
    img = tf.image.resize(frame, Image_size)
    img = np.expand_dims(img, axis=[0, -1]) / 255.0 # Reshape and normalize
    return np.argmax(model.predict(img), axis=1)[0]

Enter fullscreen mode Exit fullscreen mode

Step 4: Creating the Application Interface (app.py)

The app.py file serves as the command center. It integrates the Camera module for data acquisition and the model module for intelligence, presenting them through a Graphical User Interface (GUI) built with tkinter.

Sub-Step 4.1: Setup and Initialization (__init__)

This function initializes the window, sets up the camera and model instances, and prompts the user for class names. It also kicks off the update loop to keep the UI responsive.

Sub-Step 4.2: Building the GUI (init_gui)

This defines the layout. It creates the canvas for video display and populates the window with buttons to capture training data, train the model, trigger predictions, and reset the environment.

Sub-Step 4.3: Data Collection (save_for_class)

When a button is clicked, this function pulls a frame from the camera and saves it into the corresponding folder (/1 or /2). This is how you generate your training dataset.

Sub-Step 4.4: Model Management & Reset (train_model & reset)

train_model calls the training routine from model.py. The reset function purges existing image files and resets counters, allowing you to start a new classification task from scratch.

Sub-Step 4.5: The Runtime Loop (update)

This is the heartbeat of the app. It runs every 15ms, refreshing the canvas with the latest camera frame and, if enabled, automatically running the prediction model to display the current class.

Implementation Code

import tkinter as tk
from tkinter import simpledialog
import cv2 as cv
import os
import PIL.Image, PIL.ImageTk
import Camera, model

class App:
    # Sub-Step 4.1: Initialize App state
    def __init__(self, window=tk.Tk(), window_title="Camera Classifier"):
        self.window = window
        self.window.title(window_title)
        self.counters = [1, 1]
        self.auto_predict = False
        self.camera = Camera.Camera()
        self.model = model.load_trained_model()
        self.classname_one = simpledialog.askstring("Class 1", "Enter name:")
        self.classname_two = simpledialog.askstring("Class 2", "Enter name:")
        self.init_gui()
        self.update()
        self.window.mainloop()

    # Sub-Step 4.2: Construct the UI layout
    def init_gui(self):
        self.canvas = tk.Canvas(self.window, width=self.camera.width, height=self.camera.height)
        self.canvas.pack()
        tk.Button(self.window, text="Toggle Auto", command=self.auto_predict_toggle).pack()
        tk.Button(self.window, text=self.classname_one, command=lambda: self.save_for_class(1)).pack()
        tk.Button(self.window, text=self.classname_two, command=lambda: self.save_for_class(2)).pack()
        tk.Button(self.window, text="Train Model", command=self.train_model).pack()
        self.class_label = tk.Label(self.window, text="CLASS", font=("Arial", 20))
        self.class_label.pack()

    # Sub-Step 4.3: Save frames for training
    def save_for_class(self, class_num):
        ret, frame = self.camera.get_frame()
        if not os.path.exists(str(class_num)): os.mkdir(str(class_num))
        cv.imwrite(f'{class_num}/frame{self.counters[class_num-1]}.jpg', cv.cvtColor(frame, cv.COLOR_RGB2BGR))
        self.counters[class_num-1] += 1

    # Sub-Step 4.4: Train and Reset functionality
    def train_model(self): self.model = model.train()

    def reset(self):
        for d in ['1', '2']: 
            for f in os.listdir(d): os.unlink(os.path.join(d, f))
        self.counters = [1, 1]

    # Sub-Step 4.5: Main UI refresh loop
    def update(self):
        ret, frame = self.camera.get_frame()
        if ret:
            self.photo = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(frame))
            self.canvas.create_image(0, 0, image=self.photo, anchor=tk.NW)
        if self.auto_predict and self.model:
            class_idx = model.predict(cv.cvtColor(frame, cv.COLOR_RGB2GRAY), self.model)
            name = self.classname_one if class_idx == 0 else self.classname_two
            self.class_label.config(text=f"CLASS: {name}")
        self.window.after(15, self.update)

if __name__ == "__main__": App()

Enter fullscreen mode Exit fullscreen mode

Watchout Section

  • Path Alignment: Ensure the DATA_DIR in model.py matches the absolute location where your training folders (1 and 2) are stored.

  • Directory Structure: The image dataset must be organized in folders labeled 1 and 2 for tf.keras.utils.image_dataset_from_directory to function correctly.

  • Consistency: Always retrain the model after adding significant new training data to ensure the saved .keras file remains accurate.

Wrap Up

You have now built a functional, real-time image classifier! By bridging hardware capture with deep learning, you can expand this prototype into sophisticated computer vision applications. Keep experimenting with different model architectures or by increasing the number of classes to see how the system performs!

What specific application or object category are you planning to train your model to identify first?