Capturing a single image from my webcam in Java or Python - java

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)

Related

Is there a way to take a bunch of images and turn them into an mp4 file in java?

I am currentrly working on a Way to visualize Fractals in Java. The mathematics behind it work perfectly fine and I am very happy with how the Pics turn out. Now i want to take these Images and turn them into a Video. I've written a Java Program that produces any number of Pictures and saves them (alphabetically) in a new directory. Now I need a way for Java to convert these Images into a Video.
I know there are solutions such as ffmpeg, however I need this process to be repeatable, so I don't think a Command Line Application would be the best Option.
Is there any Way to implement such a function into Java directly ?
If you're willing to use a third party library and the platform is supported (Windows or Linux, 64bit). You can use Pilecv4j (Full disclosure, I'm the main committer).
There's a test checked in that does exactly this. You can find it here: TestSplitIntoFiles.java
Here is the pertinent function that does this with the minor difference that it's not reading the image file names from the contents on the disk:
private static void encodeFiles(final File imageDir, final long numFrames, final File outputVideo) throws IOException {
try(final CvMat firstFrame = ImageFile.readMatFromFile(new File(imageDir, "image-0.jpg").getAbsolutePath());
final EncodingContext ectx = Ffmpeg2.createEncoder()
.outputStream(outputVideo.getAbsolutePath())
.openVideoEncoder("libx264", "vidEncoder")
.addCodecOptions("preset", "slow")
.addCodecOptions("crf", "40")
.enable(firstFrame, false)
;) {
final VideoEncoder ve = ectx.getVideoEncoder("vidEncoder");
ectx.ready();
LongStream.range(0, numFrames)
.mapToObj(fn -> new File(imageDir, "image-" + fn + ".jpg").getAbsolutePath())
.forEach(frameFile -> {
try(CvMat mat = uncheck(() -> ImageFile.readMatFromFile(frameFile));) {
ve.encode(mat, false);
}
});
}
}
If you decide to give it a try, let me know if you run into any issues. You can use the Issues on GitHub. I've been using it professionally for a while.
Also, see the answer to this question: Read a mp4 and write to anther mp4 creates bigger size

Converting MATLAB code to Java code

I need to call this MATLAB code from Java code. The code clusters an image according to the specified number of clusters and the specified initial cluster centers (i.e. [176;137] in this code).
nrows = size(a_image,1);
ncols = size(a_image,2);
double_a_2_image = double(reshape(a_image,nrows*ncols,1));
nColors = 2;
[cluster_idx_2_a cluster_center] =
kmeans(double_a_2_image,nColors,'distance','sqEuclidean','start',repmat([176;137],
[1,1,3]));
a_pixel_labels_2 = reshape(cluster_idx_2_a,nrows,ncols);
figure('Name','a* image labeled by cluster index: 2 colors'),imshow(a_pixel_labels_2,
[]);
What is the best tool to convert this code into jar file (or maybe .class file)? Another point: I need to run the resulted jar file on a machine that do not have matlab installed. Is that possible or should I install MATLAB Compiler Runtime (MCR) on this machine?
A simple search on google gives you this link : MATLAB Builder JA, which generate a Java wrapper around your MATLAB code. And for your second question, you won't need it, as the wrapper is taking care of the MATLAB code itself.

OpenCV Constants.CaptureProperty

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);

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.

how to implement clean screen and config keybind with jLine

I want to develop a java cli with jline..I get different Jline version from Internet, but I don't know the difference between them..
My OS is WINDOWS XP SP2.
In Jline09.9 and Jline1.0, it also don't support clean screen. How to config keybind to support clean screen??
The source code WindowsTerminal.java
/**
* Windows doesn't support ANSI codes by default; disable them.
*/
public boolean isANSISupported() {
return false;
}
In jLine0.9.9 and Jline1.0 , clean screen don't work..
http://i.stack.imgur.com/2m71z.jpg
In Jline2.x, it support clean screen, but console appear gibberish when I use array key UP/DOWN/LEFT/RIGHT , INSERT, DELETE, END..
Bad code and strange Character in Jline 2.6 and Jline2.9 When type array key or DELETE,HOME,INSERT key
http://i.stack.imgur.com/5A8d2.jpg
I don't know how to config keybind in Jline1.x and Jline2.x through keybinds.properties.
And How to config the keybinds.properties ? How to use it??
Could you give some advice or example?
Did you install AnsiConsole? This is needed to render the "gibberish" escape codes.
AnsiConsole.systemInstall();
should do it for you.

Categories