record and save video stream use opencv in java - java

my question is about : how to record and save with the time specified like after two hours this app must done record and save in one folder.
public class per1 {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Scanner scan = new Scanner(System.in);
VideoCapture camera = new VideoCapture(0);
String cc = String.valueOf(camera.get(Videoio.CAP_PROP_FOURCC));
int fps = (int) camera.get(Videoio.CAP_PROP_FPS);
int width = (int) camera.get(Videoio.CAP_PROP_FRAME_WIDTH);
int height = (int) camera.get(Videoio.CAP_PROP_FRAME_HEIGHT);
final Size frameSize = new Size((int) camera.get(Videoio.CAP_PROP_FRAME_WIDTH), (int) camera.get(Videoio.CAP_PROP_FRAME_HEIGHT));
VideoWriter save = new VideoWriter("D:/video.mpg", Videoio.CAP_PROP_FOURCC, fps, frameSize, true);
if (camera.isOpened()) {
System.out.println("ON");
Mat framecam = new Mat();
boolean cekframe = camera.read(framecam);
System.out.println("cekframe " + cekframe);
try {
while (cekframe) {
camera.read(framecam);
save.write(framecam);
}
Thread.sleep(4000);
} catch (Exception e) {
System.out.println("OFF \n" + e);
}
camera.release();
save.release();
System.exit(1);
System.out.println("DOne");
}
}

Related

How to calculate mean and standard deviation of an image file

I'm new to coding environment, I'm working in an imaging processing project - I have a video file of n size and I'm trying to find a mean and standard deviation of (Height, width and number of frames)that file . the image file(imgfile_500) is in MAT
here is my code
public class Image_conv {
public static void main(String[] args) {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
String filePath = "C:\\Video_500.h264";
if (!Paths.get(filePath).toFile().exists()){
System.out.println("File " + filePath + " does not exist!");
return;
}
VideoCapture video500 = new VideoCapture(filePath);
if (!video500.isOpened()) {
System.out.println("Error! video500 can't be opened!");
return;
}
int ntime=20;
int fps= 60;
int ds_fac=4;
int nf = (ntime*fps);
int wd_ds = 480/ds_fac;
int hg_ds = 640/ds_fac;
int vsize = wd_ds*hg_ds*nf;
Mat frame = new Mat(480,640,CvType.CV_64FC3);
Mat frame500 = new Mat(480,640,CvType.CV_64FC3);
Mat imgfile_500 = new Mat();
if (video500.isOpened()) {
while(true){
if (video500.read(frame))
{
Imgproc.cvtColor(frame, frame500, Imgproc.COLOR_RGB2GRAY);
//System.out.println(frame500.size());
Imgproc.pyrDown( frame500, frame500, new Size( frame500.cols()/2, frame500.rows()/2 ) );
Imgproc.pyrDown( frame500, frame500, new Size( frame500.cols()/2, frame500.rows()/2 ) );
// Imgcodecs.imwrite(i+"led500.jpg", frame500);
// Push a Mat back into MatVector
imgfile_500.push_back(frame500);
}else break;
}
}
//System.out.println(imgfile_500.size());
}
}

Insert image with apache-poi in a .word file, increase the image size

I am new with Apache and I am checking that the image that I insert with the picture is resized in the word document. I am using the example that comes in the Apache documentation, just modified. The image is considerably enlarged from the original size and when the created .word document is opened, the picture is shown resized on document and I find no explanation, when I am forcing the size the picture should be.
Below is the code used:
public class SimpleImages {
public static void main(String\[\] args) throws IOException, InvalidFormatException {
try (XWPFDocument doc = new XWPFDocument()) {
XWPFParagraph p = doc.createParagraph();
XWPFRun r = p.createRun();
for (String imgFile : args) {
int format;
if (imgFile.endsWith(".emf")) {
format = XWPFDocument.PICTURE_TYPE_EMF;
} else if (imgFile.endsWith(".wmf")) {
format = XWPFDocument.PICTURE_TYPE_WMF;
} else if (imgFile.endsWith(".pict")) {
format = XWPFDocument.PICTURE_TYPE_PICT;
} else if (imgFile.endsWith(".jpeg") || imgFile.endsWith(".jpg")) {
format = XWPFDocument.PICTURE_TYPE_JPEG;
} else if (imgFile.endsWith(".png")) {
format = XWPFDocument.PICTURE_TYPE_PNG;
} else if (imgFile.endsWith(".dib")) {
format = XWPFDocument.PICTURE_TYPE_DIB;
} else if (imgFile.endsWith(".gif")) {
format = XWPFDocument.PICTURE_TYPE_GIF;
} else if (imgFile.endsWith(".tiff")) {
format = XWPFDocument.PICTURE_TYPE_TIFF;
} else if (imgFile.endsWith(".eps")) {
format = XWPFDocument.PICTURE_TYPE_EPS;
} else if (imgFile.endsWith(".bmp")) {
format = XWPFDocument.PICTURE_TYPE_BMP;
} else if (imgFile.endsWith(".wpg")) {
format = XWPFDocument.PICTURE_TYPE_WPG;
} else {
System.err.println("Unsupported picture: " + imgFile +
". Expected emf|wmf|pict|jpeg|png|dib|gif|tiff|eps|bmp|wpg");
continue;
}
r.setText(imgFile);
r.addBreak();
try (FileInputStream is = new FileInputStream(imgFile)) {
BufferedImage bimg = ImageIO.read(new File(imgFile));
int anchoImagen = bimg.getWidth();
int altoImagen = bimg.getHeight();
System.out.println("anchoImagen: " + anchoImagen);
System.out.println("altoImagen: " + anchoImagen);
r.addPicture(is, format, imgFile, Units.toEMU(anchoImagen), Units.toEMU(altoImagen));
}
r.addBreak(BreakType.PAGE);
}
try (FileOutputStream out = new FileOutputStream("C:\\W_Ejm_Jasper\\example-poi-img\\src\\main\\java\\es\\eve\\example_poi_img\\images.docx")) {
doc.write(out);
System.out.println(" FIN " );
}
}
}
}
the image inside the word
the original image is (131 * 216 pixels):
the image is scaled in the word

OpenCV Error: Image step is wrong using EigenFaceRecognizer in JavaCV

I am trying to achieve EigenFace Recognition in JavaCV and implementing it through this code:-
public static void main(String[] args) {
String trainingDir = "C:/Users/user/Documents/NetBeansProjects/Face/testimg";
IplImage testImage = cvLoadImage("C:/Users/user/Desktop/aa.png");
File root = new File(trainingDir);
FilenameFilter pngFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".png");
}
};
File[] imageFiles = root.listFiles(pngFilter);
MatVector images = new MatVector(imageFiles.length);
int[] labels = new int[imageFiles.length];
int counter = 0;
int label;
IplImage img;
IplImage grayImg = null;
try {
for (File image : imageFiles) {
img = cvLoadImage(image.getAbsolutePath(), CV_BGR2GRAY);
int yer = image.getName().indexOf(".");
String isim = image.getName().substring(0, yer);
label = Integer.parseInt(isim);
images.put(counter, img);
labels[counter] = label;
counter++;
}
} catch (Exception e) {
e.printStackTrace();
}
IplImage greyTestImage = IplImage.create(testImage.width(), testImage.height(), IPL_DEPTH_8U, 1);
//FaceRecognizer faceRecognizer = createFisherFaceRecognizer();
FaceRecognizer faceRecognizer = createEigenFaceRecognizer();
//FaceRecognizer faceRecognizer = createLBPHFaceRecognizer()
faceRecognizer.train(images, labels);
cvCvtColor(testImage, greyTestImage, CV_BGR2GRAY);
int predictedLabel = faceRecognizer.predict(greyTestImage);
System.out.println("Predicted label: " + predictedLabel);
}
But each time I run it,It gives me an error
OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in cv::Mat::reshape, file ........\opencv\modules\core\src\matrix.cpp, line 802
Exception in thread "main" java.lang.RuntimeException: ........\opencv\modules\core\src\matrix.cpp:802: error: (-13) The matrix is not continuous, thus its number of rows can not be changed in function cv::Mat::reshape
I have read some where that it happens when Images are not of same size and not a multiple of 8,but i have all the images of same size and grayscaled too.The code i used for saving detected Face is:-
Mat image_roi = new Mat(frame,rect_Crop);
Imgproc.cvtColor(image_roi, image_roi, Imgproc.COLOR_BGR2GRAY);
Size sz = new Size(240,240);
Imgproc.resize( image_roi, image_roi, sz );
String filename = "testimg\\" +jTextField1.getText() + ".png";
System.out.println(String.format("Writing %s", filename));
Imgcodecs.imwrite(filename, image_roi);
It also gives me
java.lang.NumberFormatException:
for my files don't know why.....???
Please help....!!!!

Java midi program selection strange behaviour

I've tried to find any information regarding this but I haven't been able to find anything that helps.
I'm trying to make a program that generates a midi-file consisting of two instruments playing at once using different instruments(programs) on them. I have been using a sample program:
http://www.cs.cornell.edu/courses/cs211/2008sp/examples/MidiSynth.java.txt
as a template but when I try and create the midi events artificially(as opposed to generating them on the fly with the synth in the sample program), the resulting midi-file doesn't seem to care that I have switched programs, using the last changed-to program for every note in the file, consisting of two midi-tracks, even though I have saved program-change data to both tracks. I have pasted the code for my program beneith:
import java.io.File;
import java.io.IOException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Soundbank;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Instrument;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiEvent;
import javax.sound.midi.MidiMessage;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.ShortMessage;
import javax.sound.midi.Track;
import javax.sound.midi.InvalidMidiDataException;
public class MidiTest2
{
/* This velocity is used for all notes.
*/
private static final int VELOCITY = 64;
final int PROGRAM = 192;
final int NOTEON = 144;
final int NOTEOFF = 128;
long startTime;
Sequence sequence;
Synthesizer synthesizer;
Sequencer sequencer;
Instrument instruments[];
ChannelData channels[];
ChannelData cc;
//int instrumentCounter = 0;
Track track;
MidiTest2(){
try{
if(synthesizer == null){
if((synthesizer = MidiSystem.getSynthesizer()) == null){
System.out.println("getSynthesizer() failed");
return;
}
}
synthesizer.open();
sequencer = MidiSystem.getSequencer();
sequence = new Sequence(Sequence.PPQ, 10);
}catch(Exception e){
e.printStackTrace();
return;
}
Soundbank sb = synthesizer.getDefaultSoundbank();
if(sb != null){
instruments = synthesizer.getDefaultSoundbank().getInstruments();
synthesizer.loadInstrument(instruments[0]);
}
MidiChannel midiChannels[] = synthesizer.getChannels();
channels = new ChannelData[midiChannels.length];
for(int i = 0; i < channels.length;++i){
channels[i] = new ChannelData(midiChannels[i], i);
}
cc = channels[0];
}
public void createShortEvent(int type, int num){
ShortMessage message = new ShortMessage();
try{
long millis = System.currentTimeMillis() - startTime;
long tick = millis * sequence.getResolution() / 500;
message.setMessage(type+cc.num, num, cc.velocity);
System.out.println("Type: " + message.getCommand() + ", Data1: " + message.getData1() + ", Data2: " + message.getData2() + ", Tick: " + tick);
MidiEvent event = new MidiEvent(message, tick);
track.add(event);
}catch (Exception e){
e.printStackTrace();
}
}
public void createShortEvent(int type, int num, int eventTime){
ShortMessage message = new ShortMessage();
try{
//long millis = System.currentTimeMillis() - startTime;
long tick = eventTime * sequence.getResolution();
message.setMessage(type+cc.num, num, cc.velocity);
System.out.println("Type: " + message.getCommand() + ", Data1: " + message.getData1() + ", Data2: " + message.getData2() + ", Tick: " + tick);
MidiEvent event = new MidiEvent(message, tick);
track.add(event);
}catch (Exception e){
e.printStackTrace();
}
}
public void saveMidiFile(){
try {
int[] fileTypes = MidiSystem.getMidiFileTypes(sequence);
if (fileTypes.length == 0) {
System.out.println("Can't save sequence");
} else {
if (MidiSystem.write(sequence, fileTypes[0], new File("testmidi.mid")) == -1) {
throw new IOException("Problems writing to file");
}
}
} catch (SecurityException ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
}
void run(){
//System.out.println("sequence: " + sequence.getTracks().length);
createNewTrack(0);
createShortEvent(NOTEON, 60, 2);
createShortEvent(NOTEOFF, 60, 3);
createShortEvent(NOTEON, 61, 3);
createShortEvent(NOTEOFF, 61, 4);
createShortEvent(NOTEON, 62, 4);
createShortEvent(NOTEOFF, 62, 5);
createShortEvent(NOTEON, 63, 5);
createShortEvent(NOTEOFF, 63, 6);
createNewTrack(5);
createShortEvent(NOTEON, 50, 1);
createShortEvent(NOTEOFF, 50, 5);
playMidiFile();
saveMidiFile();
}
void printTrack(int num){
Track tempTrack = sequence.getTracks()[num];
System.out.println(tempTrack.get(0).getTick());
}
void playMidiFile(){
try{
sequencer.open();
sequencer.setSequence(sequence);
}catch (Exception e){
e.printStackTrace();
}
sequencer.start();
}
void createNewTrack(int program){
track = sequence.createTrack();
programChange(program);
}
void programChange(int program){
cc.channel.programChange(program);
System.out.println("program: " + program);
startTime = System.currentTimeMillis();
createShortEvent(PROGRAM, program);
}
public static void main(String[] args)
{
MidiTest2 mt = new MidiTest2();
mt.run();
}
}
The ChannelData-class(that doesn't do anything but I thought I'd post it for completeness sake):
public class ChannelData {
MidiChannel channel;
boolean solo, mono, mute, sustain;
int velocity, pressure, bend, reverb;
int row, col, num;
public ChannelData(MidiChannel channel, int num) {
this.channel = channel;
this.num = num;
velocity = pressure = bend = reverb = 64;
}
public void setComponentStates() {
}
}
In the program I try to create 5 notes with the acoustic piano-sound and one note with an electric piano sound. However all notes are played back with the electric piano sound even though I create a new track before I switch instrument.
I have been trying to figure this out now for 5 hours or something and I'm all out of ideas.
Tracks can help your own program with organizing events, but they do not affect the synthesizer in any way.
To be able have different settings, you must use different channels.

Java openCV video processing frames/s

I have a task to write program with 1 camera, 1 kinect, a lot of video processing and then controlling a robot.
This code just shows captured video frames without processing, but I only have 20 frames/s approximately. The same simple frames displaying program in Matlab gave me 29 frames/s. I was hoping that I will win some speed in Java, but it doesn't look like that, am I doing sth wrong? If not, how I can increase the speed?
public class Video implements Runnable {
//final int INTERVAL=1000;///you may use interval
IplImage image;
CanvasFrame canvas = new CanvasFrame("Web Cam");
public Video() {
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}
#Override
public void run() {
FrameGrabber grabber = new VideoInputFrameGrabber(0); // 1 for next camera
int i=0;
try {
grabber.start();
IplImage img;
int g = 0;
long start2 = 0;
long stop = System.nanoTime();
long diff = 0;
start2 = System.nanoTime();
while (true) {
img = grabber.grab();
if (img != null) {
// cvFlip(img, img, 1);// l-r = 90_degrees_steps_anti_clockwise
// cvSaveImage((i++)+"-aa.jpg", img);
// show image on window
canvas.showImage(img);
}
g++;
if(g%200 == 0){
stop = System.nanoTime();
diff = stop - start2;
double d = (float)diff;
double dd = d/1000000000;
double dv = dd/g;
System.out.printf("frames = %.2f\n",1/dv);
}
//Thread.sleep(INTERVAL);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
Video gs = new Video();
Thread th = new Thread(gs);
th.start();
}
}

Categories