脚本如何读取摄像头画面

wen 实用脚本 26

本文目录导读:

脚本如何读取摄像头画面

  1. Python + OpenCV(最常用)
  2. JavaScript + Web API(浏览器端)
  3. Node.js + node-webcam
  4. Bash + fswebcam(Linux命令行)
  5. Windows PowerShell + MediaCapture
  6. 注意事项:

Python + OpenCV(最常用)

import cv2
# 打开摄像头(0表示默认摄像头)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print("无法打开摄像头")
    exit()
while True:
    # 逐帧读取
    ret, frame = cap.read()
    if not ret:
        print("无法接收帧")
        break
    # 显示画面
    cv2.imshow('摄像头画面', frame)
    # 按'q'键退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# 释放资源
cap.release()
cv2.destroyAllWindows()

JavaScript + Web API(浏览器端)

const video = document.getElementById('camera');
const constraints = { video: { width: 640, height: 480 } };
async function startCamera() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        video.srcObject = stream;
        video.play();
        // 可以添加拍照功能等
        document.getElementById('snapshot').addEventListener('click', () => {
            const canvas = document.createElement('canvas');
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0);
            // 获取截图数据
            const imageData = canvas.toDataURL('image/png');
        });
    } catch (err) {
        console.error('摄像头访问失败:', err);
    }
}
startCamera();

Node.js + node-webcam

const NodeWebcam = require('node-webcam');
const fs = require('fs');
const opts = {
    width: 1280,
    height: 720,
    quality: 100,
    delay: 0,
    saveShots: true,
    output: 'jpeg',
    device: false,
    callbackReturn: 'location',
    verbose: false
};
const Webcam = NodeWebcam.create(opts);
// 拍摄单张照片
Webcam.capture('photo', (err, data) => {
    if (err) {
        console.error('拍摄失败:', err);
        return;
    }
    console.log('照片已保存为 photo.jpg');
});
// 实时流(需要额外处理)

Bash + fswebcam(Linux命令行)

#!/bin/bash
# 安装:sudo apt-get install fswebcam
# 拍摄单张照片
fswebcam -r 640x480 --no-banner image.jpg
# 连续拍摄(每秒一张)
while true; do
    filename="capture_$(date +%Y%m%d_%H%M%S).jpg"
    fswebcam -r 640x480 --no-banner $filename
    sleep 1
done

Windows PowerShell + MediaCapture

# 需要Windows 10/11和PowerShell 5.1+
Add-Type -AssemblyName System.Runtime.WindowsRuntime
# 使用Windows.Media.Capture API
$mediaCapture = [Windows.Media.Capture.MediaCapture]::new()
await $mediaCapture.InitializeAsync()
# 预览和拍照功能需要更多代码实现

注意事项:

  1. 权限问题

    • 浏览器:需要HTTPS或localhost环境
    • 桌面应用:需要摄像头访问权限
  2. 性能优化

    # OpenCV性能优化示例
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)  # 降低分辨率
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    cap.set(cv2.CAP_PROP_FPS, 30)  # 设置帧率
  3. 错误处理

    # 多摄像头尝试
    for i in range(3):  # 尝试前3个摄像头
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            break
  4. 跨平台注意

    • Linux可能需要 v4l-utils
    • macOS需要摄像头权限许可
    • Windows需要DirectShow支持

选择哪种方式取决于你的应用场景:

  • 本地桌面应用:推荐Python+OpenCV
  • 网页应用:使用JavaScript Web API
  • 服务器端处理:Node.js或Python后台
  • 简单的自动化脚本:Bash命令行方案

抱歉,评论功能暂时关闭!