- Opencv python camera settings
- Playing Video from file
- Saved searches
- Use saved searches to filter your results more quickly
- License
- VincentGuigui/opencv-python-camera-settings
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Setting Camera Parameters in OpenCV/Python
- OpenCV, Python, Web Camera.
- Установка.
- Web Camera.
- Настройки камеры.
- Запись видео с Вебки.
- 4 Replies to “ OpenCV, Python, Web Camera. ”
- Добавить комментарий Отменить ответ
- Рубрики
Opencv python camera settings
Often, we have to capture live stream with a camera. OpenCV provides a very simple interface to do this. Let’s capture a video from the camera (I am using the built-in webcam on my laptop), convert it into grayscale video and display it. Just a simple task to get started.
To capture a video, you need to create a VideoCapture object. Its argument can be either the device index or the name of a video file. A device index is just the number to specify which camera. Normally one camera will be connected (as in my case). So I simply pass 0 (or -1). You can select the second camera by passing 1 and so on. After that, you can capture frame-by-frame. But at the end, don’t forget to release the capture.
cap.read() returns a bool ( True / False ). If the frame is read correctly, it will be True . So you can check for the end of the video by checking this returned value.
Sometimes, cap may not have initialized the capture. In that case, this code shows an error. You can check whether it is initialized or not by the method cap.isOpened(). If it is True , OK. Otherwise open it using cap.open().
You can also access some of the features of this video using cap.get(propId) method where propId is a number from 0 to 18. Each number denotes a property of the video (if it is applicable to that video). Full details can be seen here: cv::VideoCapture::get(). Some of these values can be modified using cap.set(propId, value). Value is the new value you want.
For example, I can check the frame width and height by cap.get(cv.CAP_PROP_FRAME_WIDTH) and cap.get(cv.CAP_PROP_FRAME_HEIGHT) . It gives me 640×480 by default. But I want to modify it to 320×240. Just use ret = cap.set(cv.CAP_PROP_FRAME_WIDTH,320) and ret = cap.set(cv.CAP_PROP_FRAME_HEIGHT,240) .
Note If you are getting an error, make sure your camera is working fine using any other camera application (like Cheese in Linux).
Playing Video from file
Playing video from file is the same as capturing it from camera, just change the camera index to a video file name. Also while displaying the frame, use appropriate time for cv.waitKey() . If it is too less, video will be very fast and if it is too high, video will be slow (Well, that is how you can display videos in slow motion). 25 milliseconds will be OK in normal cases.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Here is the shortest python project to change your camera settings (focus, exposure, contrast, brightness) using OpenCV
License
VincentGuigui/opencv-python-camera-settings
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Set your Camera settings using Python and OpenCV
Here is the shortest python project to change your camera settings (focus, exposure, contrast, brightness) using OpenCV. It will let you play with all the values to find the right one for your camera model.
- Based on OpenCV implementation and the camera/webcam driver for your operating system, some settings (called Capabilities) may not be available and adjustable.
- Settings values (direction and range) are highly dependant of the camera manufacturer and model.
So you will have to use a trial/error strategy to find the right values for your camera.- ie: Higher brightness value could mean brigher or darker image on another camera.
- ie: contrast=0 could be mean ‘normal’ contrast or ‘very low’ contrast on another camera.
pip install opencv-python==4.4.0.40
Start opencv-camera_settings.py All settings values are shown is the console for you to reuse in other OpenCV project.
Shortcut Action S Open DirectShow Camera settings B Increase brightness b Decrease brightness E Increase exposure e Decrease exposure C Increase contrast c Decrease contrast F Increase focus f Decrease focus 0 — N Switch camera (0 is the default main camera) L Enable live view (Camera will be reserved by this script) l Disable live view (Camera will be usable by other apps while still allowing settings) Camera model Brightness Exposure Contrast Focus Surface book 2 Front camera -130 to +130 -2 to 11 -130 to +130 Not available Surface book 2 Rear camera -130 to +130 -9 to -3.5 -130 to +130 600 (close) to 0 (far) Logitech C270 0 to 255 0 to -6 0 to 255 Not available About
Here is the shortest python project to change your camera settings (focus, exposure, contrast, brightness) using OpenCV
Setting Camera Parameters in OpenCV/Python
I am using OpenCV (2.4) and Python (2.7.3) with a USB camera from Thorlabs (DC1545M). I am doing some image analysis on a video stream and I would like to be able to change some of the camera parameters from my video stream. The confusing thing is that I am able to change some of the camera properties but not all of them, and I am unsure of what I am doing wrong. Here is the code, using the cv2 bindings in Python, and I can confirm that it runs:
import cv2 #capture from camera at location 0 cap = cv2.VideoCapture(0) #set the width and height, and UNSUCCESSFULLY set the exposure time cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 1280) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 1024) cap.set(cv2.cv.CV_CAP_PROP_EXPOSURE, 0.1) while True: ret, img = cap.read() cv2.imshow("input", img) #cv2.imshow("thresholded", imgray*thresh2) key = cv2.waitKey(10) if key == 27: break cv2.destroyAllWindows() cv2.VideoCapture(0).release()
For reference, the first argument in the cap.set() command refers to the enumeration of the camera properties, listed below:
0. CV_CAP_PROP_POS_MSEC Current position of the video file in milliseconds. 1. CV_CAP_PROP_POS_FRAMES 0-based index of the frame to be decoded/captured next. 2. CV_CAP_PROP_POS_AVI_RATIO Relative position of the video file 3. CV_CAP_PROP_FRAME_WIDTH Width of the frames in the video stream. 4. CV_CAP_PROP_FRAME_HEIGHT Height of the frames in the video stream. 5. CV_CAP_PROP_FPS Frame rate. 6. CV_CAP_PROP_FOURCC 4-character code of codec. 7. CV_CAP_PROP_FRAME_COUNT Number of frames in the video file. 8. CV_CAP_PROP_FORMAT Format of the Mat objects returned by retrieve() . 9. CV_CAP_PROP_MODE Backend-specific value indicating the current capture mode. 10. CV_CAP_PROP_BRIGHTNESS Brightness of the image (only for cameras). 11. CV_CAP_PROP_CONTRAST Contrast of the image (only for cameras). 12. CV_CAP_PROP_SATURATION Saturation of the image (only for cameras). 13. CV_CAP_PROP_HUE Hue of the image (only for cameras). 14. CV_CAP_PROP_GAIN Gain of the image (only for cameras). 15. CV_CAP_PROP_EXPOSURE Exposure (only for cameras). 16. CV_CAP_PROP_CONVERT_RGB Boolean flags indicating whether images should be converted to RGB. 17. CV_CAP_PROP_WHITE_BALANCE Currently unsupported 18. CV_CAP_PROP_RECTIFICATION Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently)
(Please note, as commenter Markus Weber pointed out below, in OpenCV 4 you have to remove the «CV» prefix from the property name, eg cv2.CV_CAP_PROP_FRAME_HEIGHT -> cv2.CAP_PROP_FRAME_HEIGHT ) My questions are: Is it possible to set camera exposure time (or the other camera parameters) through python/opencv? If not, how would I go about setting these parameters? Note: There is C++ code provided by the camera manufacturer showing how to do this, but I’m not an expert (by a long shot) in C++ and would appreciate any python-based solution.
OpenCV, Python, Web Camera.
Начинаем серию статей про работу с фото и видео в Питоне. Мы будем использовать библиотеку OpenCV постепенно разбираясь с ее многочисленными функциями.
OpenCV (Open Source Computer Vision Library) одна из самых известных, бесплатных и современных библиотек машинного зрения. Но не только зрения , там огромный набор методов для работы с графикой и видео. Но все по порядку.
Установка.
Первым делом нам потребуется библиотека Numpy , если она не стоит то ставим:
Далее ставим из репозитория OpenCV, вы так же можете собрать и из исходников, ссылка.
pip install opencv-python # Только основные методы pip install opencv-contrib-python # Все методы если не ошибаюсь
Web Camera.
Мне нужна была вебка , по этому я начал с этого. Оказалось все очень просто, сразу к коду:
import cv2 cap = cv2.VideoCapture(0) while True: ret, img = cap.read() cv2.imshow("camera", img) if cv2.waitKey(10) == 27: # Клавиша Esc break cap.release() cv2.destroyAllWindows()
Подключаемся ( захватываем) нашу веб камеру. 0 — это индекс камеры, если их несколько то будет 0 или 1 и т.д.
Читаем с устройства кадр(картинку) , метод возвращает флаг ret (True , False) и img — саму картинку ( массив numpy) .
Функция imshow отображает изображение в указанном окне. Если окно не было создано, то создается новое. «camera» — имя окна , img — массив картинки.
По сути мы получаем картинку(кадр) с камеры и показываем его.
Как понятно из названия, ожидает нажатия клавиши в мсек. Возвращает код клавиши или -1 если ничего не было нажато.
Настройки камеры.
Все отлично, но хотелось бы немного более тонко настроить вебку :
Можем даже немного поиграть с цветами :
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("camera", gray) # Будет показывать в оттенках серого.
cv2.cvtColor() — метод преобразует изображение из одного цветового пространства в другое. cv2.COLOR_BGR2GRAY — преобразование между RGB / BGR и оттенками серого . Но это все уже работа с изображением.
Запись видео с Вебки.
С записью видео тоже ничего сложного, сразу код:
import cv2 cap = cv2.VideoCapture(0) codec = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('captured.avi',codec, 25.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if cv2.waitKey(1) & 0xFF == or ('q') or ret == False: break cv2.imshow('frame', frame) out.write(frame) out.release() cap.release() cv2.destroyAllWindows()
Данный метод просто передает индификатор кодека, которым будем кодировать видео. Вы можете использовать и другие: MJPG , X264 .
- out = cv2.VideoWriter(‘captured.avi’,codec, 25.0, (640,480))
- cv2.VideoWriter(filename, fourcc, fps, frameSize)
Тут мы создаем объект в который по сути будет записываться видео кадр за кадром.
Записываем очередной кадр. Все кадры хранятся в памяти , теперь нам надо закрыть запить и сохранить все в файл :
На этом мы маленький наш обзор заканчиваем. Весь код писался на Python 3.7 , во второй версии может отличаться.
Ошибка в тексте? Выделите её и нажмите «Ctrl + Enter»
4 Replies to “ OpenCV, Python, Web Camera. ”
Добрый день! Код не работает, выдаёт ошибку: [ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-j8nxabm_\opencv\modules\videoio\src\cap_msmf.cpp (677) CvCapture_MSMF::initStream Failed to set mediaType (stream 0, (640×480 @ 30) MFVideoFormat_RGB24(codec not found) Python 3.8 и 3.7, без разницы.
Python: cv.CAP_DSHOW — DirectShow (via videoInput) . У меня в Windows все работает без этого флага. Но кому-то может пригодиться )
Не работает на линуксе:
zsh: segmentation fault python3 camera.py на секунду лампочка мигает и выскакивает ошибкаДобавить комментарий Отменить ответ
Рубрики
- Arduino (15)
- Coding (41)
- Exploits (20)
- Hack.me (25)
- Keras (7)
- Linux (67)
- NodeMSU/ESP8266 (5)
- Reverse engineering (4)
- Web (18)
- Windows Server (6)
- WordPress (9)
- Без рубрики (1)
Ошибка в тексте? Выделите её и нажмите «Ctrl + Enter»