I am trying to create an app in java using OpenCV to grab videostream from web service which is a camera system with couple of cameras and a recording device.
I have found the address "rtsp://login:pass#IP address:Port/cam/realmonitor?channel=1&subtype=0" for accessing the camera on channel 1.
For opening camera stream I have used this code (curently it catches a local usb camera):
VideoCapture cap;
Mat2Image mat2Img = new Mat2Image();
public VideoGrabber(){
cap = new VideoCapture(0);
try {
System.out.println("Sleeping..");
Thread.sleep(4000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Camera on..");
cap.open("0");
if(!cap.isOpened()){
System.out.println("Camera Error");
}
else{
System.out.println("Camera OK?");
}
}
After grabbing the video stream I put it into a JFrame.
I think I should put the video streaming service address in cap.open( ... ) but using rtsp://login:pass#http://192.168.1.14:8006/cam/realmonitor?channel=1&subtype=0 gave me "Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Width (0) and height (0) must be > 0".
Please help,
EDIT
I have found out that rtsp://login:pass#http://192.168.1.14:554/cam/realmonitor?channel=1&subtype=0 works in vlc but still no luck in opencv.
EDIT #2
Ok. After playing with vlcl, gstreamer and most of the popular solutions it just started working. I don't know if it wasn't bad rtsp address after all. Code:
static {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
//load the library of opencv
}
VideoCapture cap;
Mat2Image mat2Img = new Mat2Image();
Mat matFilter = new Mat();
public VideoGrabber(){
cap = new VideoCapture();
try {
System.out.println("Sleeping..");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Camera on..");
cap.open("rtsp://login:pass#192.168.1.14:554/cam/realmonitor?channel=1&subtype=0");
if(!cap.isOpened()){
System.out.println("Camera Error");
}
else{
System.out.println("Camera OK?");
}
}
Answering my question and for Fouad I post the working code:
I am guessing the answer was loading ffmpeg dll.
//all the imports
public class App {
static {
String path = null;
try {
//I have copied dlls from opencv folder to my project folder
path = "E:\\JAVA Projects\\OpenCv\\RTSP Example\\libraries";
System.load(path+"\\opencv_java310.dll");
System.load(path+"\\opencv_ffmpeg310_64.dll");
} catch (UnsatisfiedLinkError e) {
System.out.println("Error loading libs");
}
}
public static void main(String[] args) {
App app = new App();
//Address can be different. Check your cameras manual. :554 a standard RTSP port for cameras but it can be different
String addressString = "rtsp://login:password#192.168.1.14:554/cam/realmonitor?channel=11&subtype=0";
Mat mat = new Mat();
VideoCapture capturedVideo = new VideoCapture();
boolean isOpened = capturedVideo.open(addressString);
app.openRTSP(isOpened, capturedVideo, mat);
}
public void openRTSP(boolean isOpened, VideoCapture capturedVideo, Mat cameraMat) {
if (isOpened) {
boolean tempBool = capturedVideo.read(cameraMat);
System.out.println("VideoCapture returned mat? "+tempBool);
if (!cameraMat.empty()) {
System.out.println("Print image size: "+cameraMat.size());
//processing image captured in cameraMat object
} else {
System.out.println("Mat is empty.");
}
} else {
System.out.println("Camera connection problem. Check addressString");
}
}
}
Related
Hello everyone I have been digging the javax.sound.midi Api and I came across with the issue that I think is not related with the library itself but something related with mac. Well I have this simple code to send a Timing clock midi message. And receive this red message"PLATFORM_API_MacOSX_MidiOut.c: 162->Invalid message: message status=0xF8 while sending short message". Anyone knows work around this? thank in advance
I had a look at this source code https://github.com/JetBrains/jdk8u_jdk/blob/master/src/macosx/native/com/sun/media/sound/PLATFORM_API_MacOSX_MidiOut.c
And it seem the range of midi message is a bit constrained.
public class TestMidiLibrary {
public static void main(String[] args) {
MidiDevice.Info[] info = MidiSystem.getMidiDeviceInfo();
MidiDevice device = null;
try {
device = MidiSystem.getMidiDevice(info[6]);
device.open();
} catch (MidiUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ShortMessage msg = new ShortMessage();
try {
msg.setMessage(ShortMessage.TIMING_CLOCK);
long timeStamp = -1;
Receiver r = device.getReceiver();
r.send(msg,timeStamp);
} catch (InvalidMidiDataException | MidiUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am trying to make an application to scan documents from a scanner and i have found an application based on the mmscomputing free library that i found in github https://github.com/ashishkataria/browserWebScanning
It shows a panel from where you can choose a scanner from a list of available ones and scan the document.
public void getScan()
{
try
{
scanner.acquire();
}
catch (ScannerIOException e1)
{
IJ.showMessage("Access denied! \nTwain dialog maybe already opened!");
e1.printStackTrace();
}
}
public Image getImage()
{
Image image = imp.getImage();
return image;
}
public void update(ScannerIOMetadata.Type type, ScannerIOMetadata metadata) {
if (type.equals(ScannerIOMetadata.ACQUIRED))
{
if(imp!=null)
{
jContentPane.remove(ipanel);
jContentPane.remove(cpanel);
jContentPane.remove(crpdpanel);
}
imp = new ImagePlus("Scan", metadata.getImage());
im = imp.getImage();
imagePanel = new ImagePanel(im);
imagePanel.updateUI();
imagePanel.repaint();
imagePanel.revalidate();
ClipMover mover = new ClipMover(imagePanel);
imagePanel.addMouseListener(mover);
imagePanel.addMouseMotionListener(mover);
ipanel = imagePanel.getPanel();
ipanel.setBorder(new LineBorder(Color.blue,1));
ipanel.setBorder(BorderFactory.createTitledBorder("Scanned Image"));
ipanel.setBounds(0, 30,600, 600);
ipanel.repaint();
ipanel.revalidate();
ipanel.updateUI();
jContentPane.add(ipanel);
jContentPane.getRootPane().revalidate();
jContentPane.updateUI();
cpanel = imagePanel.getUIPanel();
cpanel.setBounds(700, 30,300, 150);
cpanel.repaint();
cpanel.setBorder(new LineBorder(Color.blue,1));
cpanel.setBorder(BorderFactory.createTitledBorder("Cropping Image"));
cpanel.setBackground(Color.white);
jContentPane.add(cpanel);
jContentPane.repaint();
jContentPane.revalidate();
metadata.setImage(null);
try {
new uk.co.mmscomputing.concurrent.Semaphore(0, true).tryAcquire(2000, null);
} catch (InterruptedException e) {
IJ.error(e.getMessage());
}
}
else if (type.equals(ScannerIOMetadata.NEGOTIATE)) {
ScannerDevice device = metadata.getDevice();
try {
device.setResolution(100);
} catch (ScannerIOException e) {
IJ.error(e.getMessage());
}
try{
device.setShowUserInterface(true);
device.setResolution(100); }catch(Exception e){
e.printStackTrace(); }
}
else if (type.equals(ScannerIOMetadata.STATECHANGE)) {
System.out.println("Scanner State "+metadata.getStateStr());
System.out.println("Scanner State "+metadata.getState());
if ((metadata.getLastState() == 3) && (metadata.getState() == 4)){}
} else if (type.equals(ScannerIOMetadata.EXCEPTION)) {
IJ.error(metadata.getException().toString());
}
}
I am trying to make it handle multiple documents and save in a pdf file, this library handles only 1 document right now.
i want to know how can i save the images in a buffer or something else and rescan until the user is done .
and is there a function that can save those images in a pdf file ?
I'm trying to show a video on the java ME 3.5 sdk emulator but I keep getting Unsupported Media Format 'video/mpeg-1', url='null' exception.
I also tried to change 'video/mpeg-1' to 'video/mpeg' but it still doesn't work. However it works fine when I lunch it on Wireless toolkit 2.5 emulator !
public void startApp() {
try {
if (error) {
return;
}
//display.setCurrent(list);
loadPlayer();
VideoControl videoControl = (VideoControl) player.getControl("javax.microedition.media.control.VideoControl");
if (videoControl == null) {
throw new Exception("No VideoControl!!");
}
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, canvas);
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
display.setCurrent(canvas);
player.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void loadPlayer() throws Exception {
player = Manager.createPlayer(getClass().getResourceAsStream("/1.mpg"), "video/mpeg-1");
player.realize();
}
public class Midlet extends MIDlet implements CommandListener{
Player p;
public void startApp() {
Display.getDisplay(this).setCurrent(new SongsList(this));
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command cmnd, Displayable dsplbl) {
if (cmnd.getLabel().equals("Exit"))
{
destroyApp(true);
}
else
{
try {
//InputStream is = getClass().getResourceAsStream("/res/getlucky.mpeg");
//p = Manager.createPlayer(is, "audio/mpeg");
p = Manager.createPlayer("http://puu.sh/6n9jC.mp3");
p.realize();
p.start();
} catch (IOException ex) {
ex.printStackTrace();
} catch (MediaException ex) {
ex.printStackTrace();
}
}
}
}
this is the songslist class :
public class SongsList extends List{
public SongsList(Midlet midlet)
{
super("Songs", List.IMPLICIT);
append("get lucky", null);
addCommand(new Command("Exit", Command.EXIT, 0));
addCommand(new Command("Select", Command.OK, 0));
setCommandListener(midlet);
}
}
tried use via file stored in project (its under src/res):
inputStream = getClass().getResourceAsStream("res/getlucky.mpg");
audioPlayer = Manager.createPlayer(inputStream, "audio/mpg");
as well as from HTTP:
//audioPlayer = Manager.createPlayer("http://puu.sh/6n9jC.mp3");
Nothing works, what am I doing wrong?
EDIT:
I've tried to delete my application and just copy paste it to a new project and it worked for some reason.. now I encounter new problems:
1) I try to play a song - this is the link http://puu.sh/6n9jC.mp3
its not playing so I guess there's a limited file size for what can be played can someone tell me what is this limit ?
2) Im trying to record the audio with RecordPlayer but its always null
public AudioAnalyzer()
{
try {
thread = new Thread(this);
recordFinished = false;
//inputStream = getClass().getResourceAsStream("res/getlucky.mpg");
//audioPlayer = Manager.createPlayer(inputStream, "audio/mpg");
audioPlayer = Manager.createPlayer("http://puu.sh/35YTG.mp3");
//audioPlayer = Manager.createPlayer("http://puu.sh/6n9jC.mp3");
audioPlayer.realize();
System.out.println(System.getProperty("supports.audio.capture"));
recordControl = (RecordControl)audioPlayer.getControl("RecordControl");
recordOutput = new ByteArrayOutputStream();
recordControl.setRecordStream(recordOutput);
recordControl.startRecord();
audioPlayer.start();
//thread.start();
} catch (MediaException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
I even tried to print if the system is supporting audio capture and the result were true but I get NullPointException at this line :
recordOutput = new ByteArrayOutputStream();
although I tried to get the recordcontrol from the player it is still null :
recordControl = (RecordControl)audioPlayer.getControl("RecordControl");
I think I read that it'll always give NullPointerException unless you run it on a real device and not an emulator is that true ? can someone verify it ? and if so what can I do if I don't own a device currently any other way to use recordcontrol feature in emulator (assuming recordcontrol isn't working on emulators).
File size is 8MB (maybe play on your phone), try to this code
public void initMedia(final String aFileUrl) {
if (m_player == null) {
try {
m_player = Manager.createPlayer(aFileUrl);
m_player.addPlayerListener(this);
m_player.realize();
m_player.prefetch();
m_volumeControl = (VolumeControl) m_player.getControl("VolumeControl");
} catch (IOException ex) {
} catch (Exception ex) {
} catch (OutOfMemoryError e) {
}
}
}
In your code, i guess you miss "m_player.prefetch()", try this. And print your Exception message...
This code in general for file, resourcce, http...
public void initMedia(final String aProtocol, final String aMediaSource) {
if (m_player == null) {
try {
if (aMediaSource.indexOf("file://") == 0) {
InputStream iRecordStream = Connector.openInputStream(aMediaSource);
m_player = Manager.createPlayer(iRecordStream, "audio/amr");
} else {
m_player = Manager.createPlayer(aProtocol);
}
m_player.addPlayerListener(this);
m_player.realize();
boolean isPrefetch = true;
try {
m_player.prefetch();
} catch (Exception ex) {
isPrefetch = false;
}
// trick to pass prefetch error
if (!isPrefetch) {
if (m_player != null) {
m_player.close();
m_player = null;
}
if (aMediaSource.indexOf("file://") == 0) {
InputStream iRecordStream = Connector.openInputStream(aMediaSource);
m_player = Manager.createPlayer(iRecordStream, "audio/amr");
} else {
m_player = Manager.createPlayer(aProtocol);
}
m_player.addPlayerListener(this);
m_player.realize();
m_player.prefetch();
}
m_volumeControl = (VolumeControl) m_player.getControl("VolumeControl");
} catch (IOException ex) {
} catch (Exception ex) {
} catch (OutOfMemoryError e) {
}
}
}
In general when it comes to J2ME development, you should always test your app on multiple real devices.
Emulators can't be trusted.
Also, J2ME is very fragmented, and various devices have various bugs and behaves differently with the same code. This will affect any app on many areas. One area being audio playback.
For example, some devices requires that you use the realize() and prefetch() methods, while other devices will crash if you use prefetch(). The only possible solution (if you wish to support as many devices as possible) is to use multiple try/catch blocks.
See this link for a detailed explanation and other tips'n'tricks on audio playback with MIDP2.0
http://indiegamemusic.com/help.php?id=1
I have a program that uses OpenCV to make some pictures with the webcam.
When I run the application in my IDE(NetBeans) it works like a charm, but when I try to run the jar file it doesn't even show what the webcam sees in our JFrame. Does anyone know how to solve this?
public void run(){
try {
grabber = new VideoInputFrameGrabber(0);
grabber.start();
while (active) {
IplImage originalImage = grabber.grab();
Label.setIcon(new ImageIcon( originalImage.getBufferedImage() ));
}
grabber.stop();
grabber.flush();
} catch (Exception ex) {
//Logger.getLogger(ChPanel.class.getName()).log(Leve l.SEVERE, null, ex);
}
}
public BufferedImage saveImage(){
IplImage img;
try {
//capture image
img = grabber.grab();
// save to file
File outputfile = new File(Project.getInstance().getFileURLStr() + " capture" + fotoCount++ + ".jpg");
ImageIO.write(img.getBufferedImage(), "jpg", outputfile);
//get file and set it in the project library
BufferedImage ImportFile = ImageIO.read(outputfile);
Project p = Project.getInstance();
MainScreen ms = MainScreen.getInstance();
ImageIcon takenPhoto = new ImageIcon(ImportFile);
p.setNextImage(takenPhoto);
ms.setPanels();
return ImportFile;
} catch (com.googlecode.javacv.FrameGrabber.Exception e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
When I run it out of CMD, it does show the image on my JFrame. But when I try to take the picture it shows this message: "Failed to write core dump. Minidumps are not enabled by default on client version of windows"
I already found the problem, I had about 3 versions of Java installed, wich propably wasn't okay :p