本文目录导读:

- JavaScript (浏览器环境)
- Python (使用 OpenCV)
- Python (使用 pycam)
- 命令行脚本 (PowerShell/Windows)
- Node.js (使用 puppeteer)
- 注意事项
JavaScript (浏览器环境)
async function getCameraList() {
try {
const devices = await navigator.mediaDevices.enumerateDevices();
const cameras = devices.filter(device => device.kind === 'videoinput');
const cameraList = cameras.map((camera, index) => ({
id: camera.deviceId,
label: camera.label || `摄像头 ${index + 1}`,
groupId: camera.groupId
}));
return cameraList;
} catch (error) {
console.error('获取摄像头列表失败:', error);
return [];
}
}
// 使用示例
getCameraList().then(cameras => {
console.log('摄像头列表:', cameras);
});
Python (使用 OpenCV)
import cv2
def get_camera_list():
camera_list = []
# 测试0-9号摄像头
for i in range(10):
cap = cv2.VideoCapture(i, cv2.CAP_DSHOW) # Windows用DSHOW,Linux用CAP_V4L2
if cap.isOpened():
camera_list.append({
'index': i,
'name': f'摄像头 {i}',
'width': int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
'height': int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
})
cap.release()
return camera_list
# 使用示例
cameras = get_camera_list()
print('摄像头列表:', cameras)
Python (使用 pycam)
import cv2
import re
import subprocess
import sys
def get_camera_list_advanced():
cameras = []
if sys.platform == 'win32':
# Windows下使用DirectShow
for i in range(10):
cap = cv2.VideoCapture(i, cv2.CAP_DSHOW)
if cap.isOpened():
# 获取更详细的信息
name = f'Camera {i} (DSHOW)'
if hasattr(cap, 'get'):
name = cap.get(cv2.CAP_PROP_DEVICE_DESCRIPTION) or name
cameras.append({
'index': i,
'name': name
})
cap.release()
return cameras
命令行脚本 (PowerShell/Windows)
# Get-WmiObject Win32_PnPEntity | Where-Object { $_.PNPClass -eq "Camera" }
# 或者使用更现代的方法
Add-Type -AssemblyName System.Windows.Forms
$manager = New-Object System.Windows.Forms.AxHost
$devices = $manager.GetConnectedDevices()
$cameras = @()
foreach ($device in $devices) {
if ($device.DeviceCategory -eq 'VideoInputDevice') {
$cameras += [PSCustomObject]@{
Name = $device.DeviceName
ID = $device.DeviceID
}
}
}
Write-Host "摄像头列表:"
$cameras | Format-Table
Node.js (使用 puppeteer)
const puppeteer = require('puppeteer');
async function getCameraList() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('about:blank');
const cameraList = await page.evaluate(async () => {
const devices = await navigator.mediaDevices.enumerateDevices();
return devices
.filter(device => device.kind === 'videoinput')
.map(camera => ({
id: camera.deviceId,
label: camera.label || 'Unknown'
}));
});
await browser.close();
return cameraList;
}
// 使用示例
getCameraList().then(console.log);
注意事项
- 权限问题:浏览器脚本需要用户授权才能访问摄像头设备
- 跨平台差异:不同操作系统对摄像头的识别方式不同
- 虚拟摄像头:某些软件(如OBS)会创建虚拟摄像头,也会被检测到
- 性能考虑:反复打开/关闭摄像头可能会导致系统资源占用
选择适合你需求的脚本即可,如果需要在特定平台获取更详细信息,建议使用原生API或专门的库。