Работа с камерой мобильного телефона в Python
В прошлой статье мы рассмотрели установку Python для S60 и работу в интерактивной консоли, сегодня мы рассмотрим возможности работы Python с камерой мобильного телефона.
Итак, приступим.
Для работы с камерой в Python существует специальный модуль camera . Для начала получим разрешения фото поддерживаемые камерой:
import camera
sizes = camera.image_sizes()
Причем если мы просто напишем в консоли camera.image_sizes то получим весьма странные результаты – что разрешение камеры не больше 2-х мегапикселей. Для того чтобы была возможность получать фото во всю “мощь” камеры необходимо первоначально перевести приложение в пейзажный режим (горизонтальный).
Для этого перед подключением камеры нам необходимо добавить строку appuifw.app.orientation = ‘landscape’ .
Для того чтобы включить превью камеры необходимо получить канвас нашей формы, для этого: canvas = appuifw.Canvas()
Также предварительно необходимо подготовить небольшую функцию для инициализации превью:
def cam_finder(im):
canvas.blit(im)
Ну и теперь мы смело можем запускать предпросмотрщик:
camera.start_finder(cam_finder, size=(320,240))
здесь указаны размера окна предпросмотра – они могут быть произвольного размера.
Теперь же нам необходимо сделать снимок с камеры, для этого добавим к центральной кнопке возможность делать фото:
canvas.bind(key_codes.EKeySelect, take_picture)
здесь:
EKeySelect – это центральная кнопка джойстика,
take_picture – это функция которая будет выполняться при нажатии кнопки, напишем ее:
для начала необходимо отключить предпросмотр:
camera.stop_finder()
затем самое главное – получить фото с камеры, для этого служит функция camera.take_photo, которая может принимать множество параметров, таких как zoom, использование вспышки, размер фото и другие. Мы задаем лишь размер фото.
pic = camera.take_photo(size = (cur_w,cur_h))
Вот собственно и то чего мы и добавались – получить фото с камеры. В результате мы имеем объект класса Image который поддерживает основные операции, такие как – ресайзинг, сохранение, добавление текста, рисование простых фигур и другие.
Для того чтобы сохранить полученное изображение используется функция save, которая принимает имя файла и степень качества jpeg от 1 до 99
pic.save(filename, quality=75)
Ниже представлена небольшая программа с возможностью выбора разрешения фото и подробными комментариями.
Исходный код сюда не смог написать, так как хабр съедает все пробелы в начале строк, а для питона это критично, так что смотрим исходник с комментариями тут
Как получить доступ к камере телефона python
Prerequisites: OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human.
Many a time, while doing Computer Vision or Image Processing using our PC’s webcam is not a very option. Maybe we want to increase the camera quality of our webcam, or we want to create some image processing applications which will use an android camera as the medium.
This article uses Windows to do this. But the basics of the code will be same on other Operating systems too.
Connect android camera to Python using OpenCV
![]()
This blog is a simple, very short tutorial on how to connect your android phone camera to OpenCV. This may be very helpful for those who are planning to create some image processing applications which will use an android camera as the medium. I will be using Python 3.6 on an Ubuntu 18.04 machine, but don’t worry my Window user friends the process will also be the same (I hope). Without further ado let’s start the tutorial.
Before we start make sure to install the following libraries:
- opencv-python
- numpy
To install using pip, just type the following:
Next is to download and install IP Webcam application on your mobile phones. This will be used to make a communication between your android phone and PC.
After installing the app make sure that your phone and PC is connected to the same network. Run the app on your phone and click Start server.
Tip: scroll down, it’s at the very bottom.
After this, your camera will open up with an IP address at the bottom.
Take note of these URLs cause we will use it later.
Let’s start coding!
Of course use the URL shown in your IP Webcam interface, replace it then run the code. In just a few moments a cv window will show and will do it’s magic. To close the window just press any key.
That’s basically how to connect android phones to your Python application. The next steps will be unto you. It may involve real-time image classification, image segmentation, object detection or face recognition the possibilities are almost limitless. Goodluck and I hope you the very best on your projects.
Name already in use
Work fast with our official CLI. Learn more about the CLI.
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
SEE «ORIGINAL» BRANCH FOR CUI VERSION
Control camera on your Android from PC with Python3 (Perhaps, iPhone too. Not tested yet.)
You need «DroidCam» app for this in your Android phone.
If you just want to try how it works, please check the release too. Windows executable file is available.
Clone this repo git clone https://github.com/AiueoABC/Play_with_DroidCam.git
Move to the cloned directory cd Play_with_DroidCam
Install requirements python -m pip install -r requirements.txt
Download DroidCam app on your phone and check IP and PORT.
Run capture.py to access your Android’s camera. python capture.py App will ask your IP and PORT.
In case of you using same IP and PORT all the time, you can use «capture_setting.dat».
Set «ask_settings=False» to skip IP/PORT settings on the App.
You can control your camera with pushing buttons on a video window.
Save Photo button will save the frame shown in app.