Streaming DroidCam video to OpenCV Python in ANYWAY possible - android

I currently have the Droid cam Application installed on my android, it is being detected and is streaming on Skype through wifi (Droid Cam client). It is however not streaming to OpenCV, no matter what number I put in for the following.
cap=cv2.VideoCapture()
In addition to this, I have an IP address, so is there any way I can implement this so that OpenCV can read an process images wireless from my camera?
I know that it does not even begin to read the camera as I have tested it with the following code, which returns FALSE every time I run it.
cap=cv2.Videocapture(0) #Use default cam
i=0
while(i<50):
ret,frame=cap.read()
print ret
Keeps returning false, meaning camera isn't being recognized :L

You have to enter the ip address of the droidcam followed by the format.The following method worked flawlessly for me :
cap = cv2.VideoCapture('http://0.0.0.0:4747/mjpegfeed?640x480')
Make sure you open the client and do not access the camera feed elsewhere

Install Droid Cam
Enable USB Debugging
Connected camera via USB to your computer
Change IP address bellow
cap = cv2.VideoCapture('http://192.168.0.21:4747/mjpegfeed')

Its simple, droidcam app shows the url; just copy it and paste in the videocapture.
IP Cam Access:
http://192.168.29.201:4747/video
Paste the url like this :
import cv2
cap = cv2.VideoCapture('http://192.168.29.201:4747/video')
while True:
ret, frame = cap.read()
cv2.imshow("frame", frame)
cv2.waitKey(1)
Thats it. Opencv should take the feed from your droidcam.

DroidCam has an MJPEG endpoint you can try getting at,
http://ip:port/mjpegfeed
See: Reading stream from IP camera with cv2.VideoCapture()

Try
IP Webcam android app
and get frames from http://your-ip:8080/shot.jpg?

I just used the following instructions and worked for me.
Install Droidcam;
Enable USB Debugging
Connected camera via USB to your computer
Use the code:
cap = cv2.VideoCapture(0)

cap=cv2.Videocapture(0)
i=0
while(i<50):
ret,frame=cap.read() //change car -> cap
print ret

i=0
while(i<50):
#put this statement inside the loop to capture the frame returned by ip webcam or
#droidcam in every iteration
#put image address in the parameter
cap=cv2.VideoCapture('http://192.168.x.x:4747/shot.jpg?rnd=890215')
ret,frame=car.read()
print(ret)

here is the python code to do wirelessly stream video from android to opencv through droidcam
import numpy as np
import cv2
#go to the setting find ip cam username and password if it is not empty use
#first one
#cap = cv2.VideoCapture('http://username:password#ip:port/video')
cap = cv2.VideoCapture('http://ip:port/video')
while(cap.isOpened()):
ret, frame = cap.read()
#do some stuff
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

Install droidcam app on PC and mobile and then write this code:
import cv2
cap =cv2.VideoCapture(1)
while True:
_, img = cap.read()
cv2.imshow("img", img)
cv2.waitKey(1)

This answer here worked for me, replacing the url with http://my-ip:8080/shot.jpg for IP Webcam app. Here is my code:
import cv2
import urllib.request
import numpy as np
my_ip = # ip given by ip-webcam
while True:
req = urllib.request.urlopen('http://'+my_ip+':8080/shot.jpg')
arr = np.asarray(bytearray(req.read()), dtype=np.uint8)
img = cv2.imdecode(arr, -1) # 'Load it as it is'
if cv2.waitKey(1) == 27:
break
cv2.imshow('Its Me', img)
cv2.destroyAllWindows()

Related

Java Android Appium - how to take screenshot when telephone is connected via USB cable?

Java Android Appium - how to take screenshot when telephone is connected via USB cable ?
The following line returns "Illegal base64 character a" - is there any different solution to take a screenshot ?
File source = driver.getScreenshotAs(OutputType.FILE);
I want to invoke screenshot when test fails in Test ng listeners Class:
#Override public void onTestFailure(ITestResult result) {}
That's because there is an annoying thing Appium does when using it's driver to take a screenshot, but I'm not sure if this applies in your situation.
Can you output the Base64 in the console to check it's specific output? If the output is something like this:
"Z3Rlc2dyZXNncmdyZWFncmVzZ3Jlc2dyZWFncmVzZ3Jlc2dlaW93YWpm\n"
"ZW9ndGVzZ3Jlc2dyZ3JlYWdyZXNncmVzZ3JlYWdyZXNncmVzZ2Vpb3dh\n"
"amZlb2d0ZXNncmVzZ3JncmVhZ3Jlc2dyZXNncmVhZ3Jlc2dyZXNnZWlv\n"
"d2FqZmVvZ3Rlc2dyZXNncmdyZWFncmVzZ3Jlc2dyZWFncmVzZ3Jlc2dl\n"
"aW93YWpmZW9ndGVzZ3Jlc2dyZ3JlYWdyZXNncmVzZ3JlYWdyZXNncmVz\n"
"Z2Vpb3dhamZlb2d0ZXNncmVzZ3JncmVhZ3Jlc2dyZXNncmVhZ3Jlc2dy\n"
Then you should replace the "\n" to a blank "":
String screenshotBase64 = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BASE64);
String replaceBase64 = screenshotBase64.replaceAll("\n","");
doSomethingWith(replaceBase64);

Streaming mp3 in Xamarin Android MediaManager not working

I'm using this nu-get package to stream mp3 url in a Xamarin Android project:
https://github.com/martijn00/XamarinMediaManager
I followed the instructions in the link up there... and it shows the music playing in the notification bar but it is not working (no sound and it's not even starting the song).
Code snippet:
clickButton.Click += (sender, args) =>
{
ClickButtonEvent();
};
private static async void ClickButtonEvent()
{
await CrossMediaManager.Current.Play("http://www.montemagno.com/sample.mp3");
}
I built the sample included in the link, and I got the same result from their sample. Also deployed on real device too, same result!
Image:
Am I missing something ?
Or is the library broken ?
I ran into this using Android Emulator on Hyper-v. It turns out that the network is set to internal. So the http://www.montemagno.com/sample.mp3 could not be found. My workaround:
Hyper-v -> Virtual Switch Manager, add an external network.
Hyper-v -> Virtual Machines->Settings, add new hardware->Network adapter and set to external network.
"Visual Studio Emulator for Android" desktop app, launch phone vm,
in Visual Studio, deploy and run app.
Sound should work from external source now.
Permissions maybe? In the project site it states that for Android:
You must request AccessWifiState, Internet, MediaContentControl and
WakeLock permissions
By default example use ExoPlayerAudioService.
There are issue with url escape in ExoPlayerAudioService.GetSource method
private IMediaSource GetSource(string url)
{
string escapedUrl = Uri.EscapeDataString(url);
var uri = Android.Net.Uri.Parse(escapedUrl);
var factory = URLUtil.IsHttpUrl(escapedUrl) || URLUtil.IsHttpsUrl(escapedUrl) ? GetHttpFactory() : new FileDataSourceFactory();
var extractorFactory = new DefaultExtractorsFactory();
return new ExtractorMediaSource(uri
, factory
, extractorFactory, null, this);
}
string escapedUrl = Uri.EscapeDataString(url);
I.E. http://example.com/path_to_audio.mp3 will be escaped to "http%3A%2F%2Fexample.com%2Fpath_to_audio.mp3" as result HTTP error.
To fix just skip url escape.

i want to create android app to control arduino car with bluetooth

my project has 2 steps:
Establish a connection between my phone and the arduino board
Use accelerometer sensor to move the car
The motion part i can handle it, but i can't find a way to use bluetooth. I just can't figure how to work with this Api.
What should i do to connect to the arduino and start sending signals to it?
Check this link out, its a Guide on Connecting Android Device with Arduino and Bluetooth
I'll just paste the Steps here, in case the link expires someday.
At the top of your source code, include these libs.
#include "SoftwareSerial.h"
#include "Bluetooth.h"
To start using it, at the top of your source declare a public variable to access it:
Bluetooth *blue = new Bluetooth(2, 3);
With Bluetooth(RX_Pin, TX_Pin)
The default pin is 1234, name is “PNGFramework” and baudrate is 9600
Now, on your Setup(), add the follow line:
void setup(){
Serial.begin(9600);
blue->setupBluetooth();
}
Send a message when we receive some data from Serial.
void loop(){
String msg = blue->Read();
if(msg.length() > 1){
Serial.print("Received: ");
Serial.println(msg);
}
if(Serial.available()){
blue->Send("Example message#");
}
}
In Android
First, create a bluetooth object, use the following code, make sure to use the same RobotName that you used in the Arduino project. (default is “PNGFramework”).
BluetoothArduino mBlue = BluetoothArduino.getInstance("PNGFramework");
To connect with the Arduino, add the command bellow:
mBlue.Connect();
Now, to read a message, run the command:
String msg = mBlue.getLastMessage();

urlopen error [errno 111] connection refused

I am doing python exercise with a book 'headfirst python'
and making android app by using python and sl4a
my code is
import android
import json
import time
from urllib import urlencode
from urllib2 import urlopen
hello_msg = "Welcome to Coach Kelly's Timing App"
list_title = 'Here is your list of athletes:'
quit_msg = "Quitting Coach Kelly's App."
web_server = 'http://127.0.0.1:8080'
get_names_cgi = '/cgi-bin/generate_name.py'
def send_to_server(url, post_data=None):
if post_data:
page = urlopen(url, urlencode(post_data))
else:
page = urlopen(url)
return(page.read().decode("utf8"))
app = android.Android()
def status_update(msg, how_long=2):
app.makeToast(msg)
time.sleep(how_long)
status_update(hello_msg)
athlete_names = sorted(json.loads(send_to_server(web_server + get_names_cgi)))
app.dialogCreateAlert(list_title)
app.dialogSetSingleChoiceItems(athlete_names)
app.dialogSetPositiveButtonText('Select')
app.dialogSetNegativeButtonText('Quit')
app.dialogShow()
resp = app.dialogGetResponse().result
status_update(quit_msg)
this is my code and the result is
what is the problem???
I can not figure out what the problem is...
Use 10.0.2.2:8080
because If you are running both server and emulator in you computer 127.0.0.1:(port) the local IP will refer to the emulator then you need another local IP for the server which will be automatically The 10.0.2.2
hope i clearified it well, glad i helped
Having followed #Coderji 's solution, I was finally able to solve this problem albeit with a different IP address; since the suggested 10.0.2.2 didn't work for me.
What worked for me was to access a terminal, ipconfig, and then used any of the provided ipv4 addresses provided by cmd (all of them seemed to work). Cheers.

android mobile socket open

Why Socket can be open on the android emulator and connect to the python server code and open a socket !! In other Hand When i run same android code on the mobile it doesn't run . didnt open a socket ..Any suggestion what is the problem and how to solve such thing
enter code here
import sys
from threading import Thread
import socket
import MySQLdb
allClients=[]
class Client(Thread):
def __init__(self,clientSocket):
Thread.__init__(self)
self.sockfd = clientSocket #socket client
self.name = ""
self.nickName = ""
def newClientConnect(self):
allClients.append(self.sockfd)
while True:
while True:
try:
rm= self.sockfd.recv(2048)
print rm
i=0
while (i<2):
if (rm) == row[i][0]:
reply="\n Welcome to our game %s: %s"%(rm,row[i][1])
self.sockfd.send(reply)
break
else:
i=i+1
if i==2:
reply="\n Error opaa ba2a"
self.sockfd.send(reply)
i=0
break
break
except ValueError:
self.sockfd.send("\n UNVAlied Comment ")
def run(self):
self.newClientConnect()
while True:
buff = self.sockfd.recv(2048)
if buff.strip() == 'quit':
self.sockfd.close()
break # Exit when break
else:
self.sendAll(buff)
#Main
if __name__ == "__main__":
#Server Connection to socket:
IP = '50.0.10.107'
PORT = 5807
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
print ("Server Started")
try:
serversocket.bind(('',54633))
except ValueError,e:
print e
serversocket.listen(5)
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
x=db.cursor()
x.execute("SELECT * FROM lolo")
row = x.fetchall()
print "Connected to the Database"
while True:
(clientSocket, address) = serversocket.accept()
print 'New connection from ', address
ct = Client(clientSocket)
ct.start()
__all__ = ['allClients','Client']
The python code and the server code it map and button when click on button connection start and it work great on the emulator
Could be a number of thing:
You don't have networking permissions enabled in your manifest file
Your wifi / 3G is disabled
If your server is on your personal computer and you're connected to the internet using a router then you need to redirect the port you're using for socket communication from the router to your machine.
If your code works on emulator but not on real phone, that could be a network issue. Emulator depends on LAN to access your server and phone access through 3G network. Is your server accessible through internet?

Categories

Resources