OpenCV Constants.CaptureProperty - java

Hi I use OpenCV Java and have some problem.
I open video file and try get property like FPS.
And others:
CV_CAP_PROP_POS_MSEC
CV_CAP_PROP_FRAME_COUNT
So first I opened video like this:
VideoCapture vC = new VideoCapture(url2);
and next i have a problem with function
vC.get(int i)
in OpenCV C++ its look like
vC.get(CV_CAP_PROP_FPS);
In Java where I find this constants?In HighGui I didnt find them. Only what I find is another libary to OpenCV where are this constants http://siggiorn.com/wp-content/uploads/libraries/opencv-java/docs/sj/opencv/Constants.CaptureProperty.html. But where I find them in OpenCV Java. Anyway how I have to use vC.get() function? Maybe some working example?

There is a bug report about this issue.
Until it is fixed, I suggest that you find these constants in the C++ source code, and define them yourself.
Edit:
I was just curious myself. You find them in the file modules/highgui/include/opencv2/highgui.hpp They are:
CAP_PROP_POS_MSEC =0,
CAP_PROP_POS_FRAMES =1,
CAP_PROP_POS_AVI_RATIO =2,
CAP_PROP_FRAME_WIDTH =3,
CAP_PROP_FRAME_HEIGHT =4,
CAP_PROP_FPS =5,
CAP_PROP_FOURCC =6,
CAP_PROP_FRAME_COUNT =7,
CAP_PROP_FORMAT =8,
CAP_PROP_MODE =9,
CAP_PROP_BRIGHTNESS =10,
CAP_PROP_CONTRAST =11,
CAP_PROP_SATURATION =12,
CAP_PROP_HUE =13,
CAP_PROP_GAIN =14,
CAP_PROP_EXPOSURE =15,
CAP_PROP_CONVERT_RGB =16,
CAP_PROP_WHITE_BALANCE_BLUE_U =17,
CAP_PROP_RECTIFICATION =18,
CAP_PROP_MONOCROME =19,
CAP_PROP_SHARPNESS =20,
CAP_PROP_AUTO_EXPOSURE =21, // DC1394: exposure control done by camera, user can adjust refernce level using this feature
CAP_PROP_GAMMA =22,
CAP_PROP_TEMPERATURE =23,
CAP_PROP_TRIGGER =24,
CAP_PROP_TRIGGER_DELAY =25,
CAP_PROP_WHITE_BALANCE_RED_V =26,
CAP_PROP_ZOOM =27,
CAP_PROP_FOCUS =28,
CAP_PROP_GUID =29,
CAP_PROP_ISO_SPEED =30,
CAP_PROP_BACKLIGHT =32,
CAP_PROP_PAN =33,
CAP_PROP_TILT =34,
CAP_PROP_ROLL =35,
CAP_PROP_IRIS =36,
CAP_PROP_SETTINGS =37

use class import org.opencv.videoio.Videoio;
vc.open(FD.class.getResource("1.avi").getPath());
double totalFrameNumber = vc.get(Videoio.CAP_PROP_FRAME_COUNT);
System.out.println("\n"+totalFrameNumber);

It seems the bug is solved. Now you should be able to use it as:
VideoCapture vC = new VideoCapture(...);
nbFrames = vC.get(Videoio.CAP_PROP_FRAME_COUNT);

Related

Convert WGS84 lat/long to GGRS87

Hello I am using GMapsFX for my JavaFX application. I am getting longtitude and latitute from Google Maps with the API but I would like to get GGRS87 also.
In Greek it is called EGSA87. Ι have searched for that and found nothing so far. There might be a solution on the libraries of Geotools or proj4j but I don't have very good knowledge of java and especially I can't find the solutions in so big libraries like those.
I have found many sites to make calculations but how can I make a mathematical calculation myself? Or even a library to solve this problem?
You can use the GDAL library for it, but its setup is actually quite complicated. You would have to install GDAL on your system (it is in Debian packages) and then build the Java JNI bindings for it [1]. [2] is also quite useful in getting it to work.
Then, you could use the Java GDAL library:
<dependency>
<groupId>org.gdal</groupId>
<artifactId>gdal</artifactId>
</dependency>
and do something like:
final SpatialReference source = new SpatialReference();
source.ImportFromEPSG(4326); // EPSG code for WGS84, see www.epsg.io
final SpatialReference target = new SpatialReference();
target.ImportFromEPSG(4121); // EPSG code for GGRS87, see www.epsg.io
this.coordinateTransform = CoordinateTransformation.CreateCoordinateTransformation(source, target);
final Geometry geometry = ogr.CreateGeometryFromWkt(String.format("POINT (%f %f)", longitude, latitude));
geometry.Transform(coordinateTransform);
final double ggrsX = geometry.GetX();
final double ggrsY = geometry.GetY();
[1] https://trac.osgeo.org/gdal/wiki/GdalOgrInJavaBuildInstructionsUnix
[2] http://geoexamples.blogspot.com/2012/05/running-gdal-java.html

How to convert opencv code into javacv code

How to convert this C++ opencv code . (this code is from camshift tracking demo in opencv https://github.com/Itseez/opencv/blob/master/samples/cpp/camshiftdemo.cpp )
Mat roi(hue,selection), maskroi(mask,selection);
into javacv code?
The neweast javacpp presets javacpp-presets-0.9 already hava whole opencv javacv version implementation. Check if the functions you need is available.
https://github.com/bytedeco/javacpp-presets/tree/master/opencv
If not, I think you need to see the definition(implemetaion) of the two c++ function roi() and maskroi() to convert very line code into javacv counterpart by yourself.
And, google group of javacpp is also a best place to ask if you hava javacpp related questions. http://groups.google.com/group/javacpp-project
Note:
for c++ output parameter type(call by pointer or call by reference), you need to understand java function parameter has no output type, so you need to use array instead as workaround, for example:
C++ code:
void detectBothEars(Mat input, Rect* left, Rect* right);
The javacv counterpat should be:
void detectBothEarsRect(Mat input, Rect[] left, Rect[] right);
And the client code is:
Rect[] leftRect = new Rect[1];
Rect[] rightRect = new Rect[1];
detectBothEars(face, leftRect , rightRect);
The same constructor is available from Java: public Mat(Mat m, Rect roi)
So, we can basically do the same thing:
Mat roi = new Mat(hue, selection), maskroi = new Mat(mask, selection);

How to extract programmatically video frames?

I need programmatically extract frames from mp4 video file, so each frame goes into a separate file. Please advise on a library that will allow to get result similar to the following VLC command (http://www.videolan.org/vlc/):
vlc v1.mp4 --video-filter=scene --vout=dummy --start-time=1 --stop-time=5 --scene-ratio=1 --scene-prefix=img- --scene-path=./images vlc://quit
Library for any of these Java / Python / Erlang / Haskell will do the job for me.
Consider using the following class by Popscan. The usage is as follows:
VideoSource vs = new VideoSource("file://c:\test.avi");
vs.initialize();
...
int frameIndex = 12345; // any frame
BufferedImage frame = vs.getFrame(frameIndex);
I would personally look for libraries that wrap ffmpeg/libavcodec (the understands-most-things library that many encoders and players use).
I've not really tried any yet so can't say anything about code quality and ease, but the five-line pyffmpeg example suggests it's an easy option - though it may well be *nix-only.

OpenCV in Java, why can't I use Mat.CvType.CV_8UC1?

If I try to write that code
Mat.CvType.CV_8UC1
I get the error CvType cannot be resolved or is not a field. What am I missing? I think I've added the correct library and DLL in the project properties because everything else seems to be working. I need to find those CV_8UC1 CV_8UC2, etc.
You can try to use CvType.CV_8UC1 insted of Mat.CvType.CV_8UC1

Capturing a single image from my webcam in Java or Python

I want to capture a single image from my webcam and save it to disk. I want to do this in Java or Python (preferably Java). I want something that will work on both 64-bit Win7 and 32-bit Linux.
EDIT: I use Python 3.x, not 2.x
Because everywhere else I see this question asked people manage to get confused, I'm going to state a few things explicitly:
I do not want to use Processing
I do not want to use any language other than those stated above
I do want to display this image on my screen in any way, shape or form
I do not want to display a live video feed from my webcam on my screen, or save such a feed to my hard drive
The Java Media Framework is far too out of date. Do not suggest it.
I would rather not use JavaCV, but if I absolutely must, I want to know exactly which files from the OpenCV library I need, and how I can use these files without including the entire library (and preferably without sticking these files in any sort of PATH. Everything should be included in the one directory)
I can use Eclipse on the 64-bit Win7 computer if need be, but I also have to be able to compile and use it on 32-bit Linux as well
If you think I might or might not know something related to this subject in any way shape or form, please assume I do not know it, and tell me
EDIT2: I was able to get Froyo's pygame example working on Linux using Python 2.7 and pygame 1.9.1. the pygame.camera.camera_list() call didn't work, but it was unnecessary for the rest of the example. However, I had to call cam.set_controls() (for which you can find the documentation here http://www.pygame.org/docs/ref/camera.html) to up the brightness so I could actually see anything in the image I captured.
Also, I need to call the cam.get_image() and pygame.image.save() methods three times before the image I supposedly took on the first pair of calls actually gets saved. They appeared to be stuck in a weird buffer. Basically, instead of calling cam.get_image() once, I had to call it three times every single time I wanted to capture an image. Then and only then did I call pygame.image.save().
Unfortunately, as stated below, pygame.camera is only supported on Linux. I still don't have a solution for Windows.
#thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.
using SimpleCV (not supported in python3.x):
from SimpleCV import Image, Camera
cam = Camera()
img = cam.getImage()
img.save("filename.jpg")
using OpenCV:
from cv2 import *
# initialize the camera
cam = VideoCapture(0) # 0 -> index of camera
s, img = cam.read()
if s: # frame captured without any errors
namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
imshow("cam-test",img)
waitKey(0)
destroyWindow("cam-test")
imwrite("filename.jpg",img) #save image
using pygame:
import pygame
import pygame.camera
pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")
Install OpenCV:
install python-opencv bindings, numpy
Install SimpleCV:
install python-opencv, pygame, numpy, scipy, simplecv
get latest version of SimpleCV
Install pygame:
install pygame
On windows it is easy to interact with your webcam with pygame:
from VideoCapture import Device
cam = Device()
cam.saveSnapshot('image.jpg')
I haven't tried using pygame on linux (all my linux boxen are servers without X), but this link might be helpful http://www.jperla.com/blog/post/capturing-frames-from-a-webcam-on-linux
import cv2
camera = cv2.VideoCapture(0)
while True:
return_value,image = camera.read()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow('image',gray)
if cv2.waitKey(1)& 0xFF == ord('s'):
cv2.imwrite('test.jpg',image)
break
camera.release()
cv2.destroyAllWindows()
Some time ago I wrote simple Webcam Capture API which can be used for that. The project is available on Github.
Example code:
Webcam webcam = Webcam.getDefault();
webcam.open();
try {
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));
} catch (IOException e) {
e.printStackTrace();
} finally {
webcam.close();
}
I wrote a tool to capture images from a webcam entirely in Python, based on DirectShow. You can find it here: https://github.com/andreaschiavinato/python_grabber.
You can use the whole application or just the class FilterGraph in dshow_graph.py in the following way:
from pygrabber.dshow_graph import FilterGraph
import numpy as np
from matplotlib.image import imsave
graph = FilterGraph()
print(graph.get_input_devices())
device_index = input("Enter device number: ")
graph.add_input_device(int(device_index))
graph.display_format_dialog()
filename = r"c:\temp\imm.png"
# np.flip(image, axis=2) required to convert image from BGR to RGB
graph.add_sample_grabber(lambda image : imsave(filename, np.flip(image, axis=2)))
graph.add_null_render()
graph.prepare()
graph.run()
x = input("Press key to grab photo")
graph.grab_frame()
x = input(f"File {filename} saved. Press key to end")
graph.stop()
It can be done by using ecapture
First, run
pip install ecapture
Then in a new python script
type:
from ecapture import ecapture as ec
ec.capture(0,"test","img.jpg")
More information from thislink
I am able to achieve it, this way in Python (Windows 10):
Please install PyAutoGUI
import pyautogui as pg #For taking screenshot
import time # For necessary delay
import subprocess
# Launch Windows OS Camera
subprocess.run('start microsoft.windows.camera:', shell=True)
time.sleep(2) # Required !
img=pg.screenshot() # Take screenshot using PyAutoGUI's function
time.sleep(2) # Required !
img.save(r"C:\Users\mrmay\OneDrive\Desktop\Selfie.PNG") # Save image screenshot at desired location on your computer
#Close the camera
subprocess.run('Taskkill /IM WindowsCamera.exe /F', shell=True)

Categories