Linux usb camera device

How to check available webcams from the command line?

Is there a terminal command that lists all the webcams connected to my computer including the native one? Maybe using the ffmpeg package?

3 Answers 3

v4l2-ctl —list-devices

sudo apt-get install v4l-utils v4l2-ctl --list-devices 

Sample output with a single camera:

Integrated Camera (usb-0000:00:1a.0-1.6): /dev/video0 

video1 metadata device

On Ubuntu 19.10 Lenovo Thinkpad P51 however, it lists two such devices, video0 and video1 , but I only have one camera, and can only see images from video0 with ffplay . This has been asked at:

What happens is that /dev/video1 contains some kind of video metadata only and not the images as can been seen from:

sudo v4l2-ctl --device=/dev/video0 --all sudo v4l2-ctl --device=/dev/video1 --all 
 Device Caps : 0x04200001 Video Capture Device Caps : 0x04a00000 Metadata Capture 

How to see the camera image live

sudo apt install ffmpeg ffplay /dev/video0 

enter image description here

Another good one that shows only camera and nothing else:

sudo apt-get install guvcview guvcview 

Take a single picture from the command line

ffmpeg -f v4l2 -video_size 1280x720 -i /dev/video0 -frames 1 out.jpg 

Record a video from the command line

Parameters chosen based on «How to get camera parameters like resolution» below:

ffmpeg -f v4l2 -framerate 30 -video_size 1280x720 -input_format mjpeg -i /dev/video0 -c copy out.mkv 
Stream #0:0: Video: mjpeg (Baseline), yuvj422p(pc, bt470bg/unknown/unknown), 1280x720, 30 fps, 30 tbr, 1k tbn, 1k tbc (default) 

If you choose wrong parameters, the resolution might be slow. The camera already outputs a specific encoded format, and the simplest way to record is to just copy that format as above:

TODO If I replace -c copy out.mkv with out.ogv to try and record directly to an open format (unlike MJPEG), I got a low resolution video.

Interactive image/video capture with preview

Until I learn how to run ffplay preview on one shell and capture at the same time from another shell with ffmpeg (they fight over the video device), I’ll have to lower myself to this amazing GUI program:

Читайте также:  Linux remove all empty files

enter image description here

Read camera data from C/C++

A concrete C++ example that processes images from the camera on the GPU with OpenGL and shows it live: https://stackoverflow.com/questions/13693946/image-processing-with-glsl-shaders/40641014#40641014

How to get camera parameters like resolution

produces some good information:

ioctl: VIDIOC_ENUM_FMT Type: Video Capture [0]: 'YUYV' (YUYV 4:2:2) Size: Discrete 640x480 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 320x180 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 320x240 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 352x288 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 424x240 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 640x360 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 848x480 Interval: Discrete 0.050s (20.000 fps) Size: Discrete 960x540 Interval: Discrete 0.067s (15.000 fps) Size: Discrete 1280x720 Interval: Discrete 0.100s (10.000 fps) [1]: 'MJPG' (Motion-JPEG, compressed) Size: Discrete 640x480 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 320x180 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 320x240 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 352x288 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 424x240 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 640x360 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 848x480 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 960x540 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) Size: Discrete 1280x720 Interval: Discrete 0.033s (30.000 fps) Interval: Discrete 0.067s (15.000 fps) 

How to get the corresponding ffmpeg encodings

v4l2-ctl —list-formats-ext gives the Linux kernel name of things, e.g . YUYV 4:2:2 . But to do stuff with ffmpeg , you need to know the ffmpeg nama sometimes. You can do it like this:

ffmpeg -f v4l2 -list_formats all -i /dev/video0 
[video4linux2,v4l2 @ 0x555ba7267240] Raw : yuyv422 : YUYV 4:2:2 : 640x480 320x180 320x240 352x288 424x240 640x360 848x480 960x540 1280x720 [video4linux2,v4l2 @ 0x555ba7267240] Compressed: mjpeg : Motion-JPEG : 640x480 320x180 320x240 352x288 424x240 640x360 848x480 960x540 1280x720 

This for example told us that the ffmpeg name for YUYV 4:2:2 is yuyv422 .

Читайте также:  Линукс как серверная ос

Just having some fun at this point

python -m pip install -U yolov5==7.0.9 yolov5 detect --source 0 

Источник

Работа с usb видеокамерой в Linux. Часть 1

По популярности видеокамера, сегодня, стоит в одном ряду с микрофоном и наушниками. Она используется в различных направлениях, таких как распознавание объектов, дополненная реальность, видеоконференции и множество других. Но что же скрыто под капотом этих сложнейших программ? Как мы получаем картинку с видеокамеры? Этот цикл статей позволит взглянуть на простоту работы с видеокамерой на низком уровне, обработку полученного изображения.

Для начала, немного информации о работе с устройствами в системе Linux. Устройства в nix системах представляют собой файл. С некоторыми файлами-устройств мы можем работать как с обычными файлами. Например:

эта команда выведет на экран весь диск sda.

Есть устройства с которыми нельзя работать напрямую, к ним относится видеокамера.При попытке это сделать мы получим такую реакцию системы:

~$ cat: /dev/video0: Недопустимый аргумент

*Где /dev/video0 это файл-устройство найшей видеокамеры.

Для работы с ней нам понадобится системная функция ioctl детальнее о ней можно ознакомится [1]. Попробуем это применить. Вот код позволяющий считать информации с устройства (альтернатива команде cat для видеоустройств):

#include #include #include #include #include #include int main (int argc,char* argv[]) < /*Read Params*/ char *device_name; if(argc >1) < &nbsp&nbspdevice_name = argv[1]; >else < &nbsp&nbspdevice_name = "/dev/video0"; >/*Open Device*/ int file_device = open(device_name, O_RDWR, 0); if (file_device == -1) < &nbsp&nbspprintf ("%s error %d, %s\n",device_name, errno, strerror(errno)); &nbsp&nbspexit(EXIT_FAILURE); >/*Read Params From Device*/ struct v4l2_capability device_params; if (ioctl(file_device, VIDIOC_QUERYCAP, &device_params) == -1) < &nbsp&nbspprintf ("\"VIDIOC_QUERYCAP\" error %d, %s\n", errno, strerror(errno)); &nbsp&nbspexit(EXIT_FAILURE); >printf("driver : %s\n",device_params.driver); printf("card : %s\n",device_params.card); printf("bus_info : %s\n",device_params.bus_info); printf("version : %d.%d.%d\n",      ((device_params.version >> 16) & 0xFF),      ((device_params.version >> 8) & 0xFF),      (device_params.version & 0xFF)); printf("capabilities: 0x%08x\n", device_params.capabilities); printf("device capabilities: 0x%08x\n", device_params.device_caps); /* Close Device */ if (-1 == close (file_device)) < &nbsp&nbspprintf ("\"close\" error %d, %s\n", errno, strerror(errno)); &nbsp&nbspexit(EXIT_FAILURE); >file_device = -1; return 0; > 

В первых строках кода считываются параметры с которой запущено приложение. Если параметров нету то device_name принимает стандартоне значение «/dev/video0».

Читайте также:  Zip linux сжать папку

В блоке «Open Device» происходит открытие устройства системной функцией open (нужно подключить header fcntl.h). Обязательный параметр O_RDWR отвечает за открытие устройства считывания/записи. Если при подключении возникла ошибка, то функция open вернет -1.

Блок «Read Params From Device» — это сердце нашей маленькой программы. Для его использования надо подключить билиотеку

возможно прийдется её установить, у каждого дистрибутива свой пакет под эту библиотеку
Системная функция ioctl имеет три параметра:
file_device — дескриптор нашего устройства
VIDIOC_QUERYCAP — функция ядра, которую применяем для нашего устройства.
device_params — область памяти куда будет сброшен результат функции «VIDIOC_QUERYCAP».

device_params это структура состоящая из таких полей:

если возникла ошибка ioctl вернет -1

Блок «Close Device» закрывает дескриптор устройства.

Посмотрим программу в действии.

./catvd /dev/video0 /dev/video0 error 2, No such file or directory

устройство не определилось ядром либо не подключено уборщица опять ненужные провода дергала.
Подключаем и заново запуск. Получаем такую информацию:

 ./catvd /dev/video0 driver : uvcvideo card : UVC Camera (046d:0804) bus_info : usb-0000:00:12.2-3 version : 3.11.10 capabilities: 0x84000001 device capabilities: 0x04000001 

поле capabilities и device capabilities можно расшифровать благодаря константам из файла videodev2.h:

V4L2_CAP_DEVICE_CAPS 0x80000000 // устроство содержит поля для изменения параметров. V4L2_CAP_STREAMING 0x04000000 // это потоковое устройство i/o ioctls. V4L2_CAP_VIDEO_CAPTURE 0x00000001 // устроство имеет функцию видеозахвата. 

На этом вводная статья заканчивается. В следующих обзорах будут затронуты, такие темы как memory-mapping, виодеформаты изображения, настройка камеры, вывод изображения в текстуру, работа с несколькими камерами.

Ресурсы используемые в статье:

Источник

Оцените статью
Adblock
detector