JavaCV Grabber webcam only working on my computer? - java

So I created an executable JAR using this code and everything works fine on my machine however I tested it on some other computers and the webcam capture never starts. The indicator light doesn't come on. This is the example I see in most tutorials for doing image capture and I'm doing face recognition so it's easiest to utilize the javaCV function rather than adding another library. All suggestions appreciated, thank you.
CanvasFrame canvas = new CanvasFrame("Webcam");
//Set Canvas frame to close on exit
canvas.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
try {
//Start grabber to capture video
grabber.start();
//Declare img as IplImage
IplImage img;
long starttime = System.currentTimeMillis();
while (temptime < 4000) {
//inser grabed video fram to IplImage img
img = grabber.grab();
//Set canvas size as per dimentions of video frame.
canvas.setCanvasSize(grabber.getImageWidth(), grabber.getImageHeight());
if (img != null) {
//Flip image horizontally
cvFlip(img, img, 1);
//Draw text over the canvas
Graphics g = canvas.createGraphics();
g.setFont(camfont);
g.setColor(Color.red);
//Show video frame in canvas
canvas.showImage(img);
if (temptime > 2000 && tempcount == 1) {
//take and save the picture
cvSaveImage("User-cap.jpg", img);
tempcount++;
}
temptime = System.currentTimeMillis() - starttime;
}
}
} catch (Exception e) {
}
try {
grabber.stop();
canvas.dispose();
} catch (Exception e) {
System.out.println("Grabber couldn't close.");
}

you need to have OpenCV installed in the machine where you are running that program , jar only will contain javacv wrapper , but doesnt contains dll of opencv

Related

Java OpenCV save video file

I would like to save a file (avi) of some frames (in this case, 600) from my webcam using java opencv, but i have no idea how to do that, the code below gives me the avi file specified but with size 0, no frames inside whatsover, also in the directory i have those 600 frames in jpeg's.
It's important to use java for that, no python.
Mat frame = new Mat();
VideoWriter writer = new VideoWriter("c:/opencv/vid.avi", VideoWriter.fourcc('X','2','6','4'), 30 ,frame.size(), true);
videoCapture = new VideoCapture();
videoCapture.open(0);
videoCapture.set(Videoio.CAP_PROP_FRAME_WIDTH, 1280);
videoCapture.set(Videoio.CAP_PROP_FRAME_HEIGHT, 720);
while (true){
videoCapture.read(frame);
if (!frame.empty())
break;
}
int frameNo = 0;
while (frameNo < 600){
videoCapture.read(frame);
writer.write(frame);
Imgcodecs imageCodecs = new Imgcodecs();
String file = "c:/opencv/i" + frameNo + ".jpg";
Imgcodecs.imwrite(file,frame);
frameNo++;
}
videoCapture.release(); // release device
You didn't mention which openCV version are you using, I use OpenCV-3.4.2
AVI container use DIVX codec reference: https://wiki.videolan.org/DivX/
I modify a bit your code:
Mat frame = new Mat();
VideoWriter writer = new VideoWriter("c:/opencv/vid.avi", VideoWriter.fourcc('D', 'I', 'V', 'X'), 30, new Size(videoCapture.get(Videoio.CAP_PROP_FRAME_WIDTH), videoCapture.get(Videoio.CAP_PROP_FRAME_HEIGHT)));
while(runnable)
{
if(videoCapture.grab())
{
try
{
//Decodes and returns the grabbed video frame.
videoCapture.retrieve(frame);
//encode to .jpg the frame to a MatOfByte
Imgcodecs.imencode(".jpg", frame, mem);
//read into an Image
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
//Draw image to a Jpanel
BufferedImage buff = (BufferedImage) im;
Graphics g = jPanel1.getGraphics();
g.drawImage(buff, 0, 0, getWidth(), getHeight(), 0, 0, buff.getWidth(), buff.getHeight(), null);
//record the frame
writer.write(frame);
}
catch(Exception ex)
{
System.out.println("Error");
ex.printStackTrace();
}
}
}
videoCapture.release(); // release device

Java opencv unblur part of image around the mouse cursor

I have an image on which gaussian blur is applied through this code
try {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat im = Imgcodecs.imread("bin\\" + backImage[randNum]);
Mat dst = new Mat();
Imgproc.GaussianBlur(im, dst, new Size(55, 55) ,8 , 8);
Imgcodecs.imwrite("bin\\gauLock.jpg", dst);
} catch (Exception e) {
dispose();
}
Now I want to unblur the area around the mouse cursor
Somewhat like this
So my questions are
Is this possible?
Can this be done using only opencv?
If yes then how?

Java file operations after opening image with ImageIO

I am working with Java and combine two images. I save the combined image and want to delete the overlay, but it seems there are still streams open. And i don't know which and how to close them.
f_overlay and f_image are both Files.
// load source images
BufferedImage image = null;
BufferedImage overlay = null;
try {
log.debug(f_image.getAbsolutePath());
log.debug(f_overlay.getAbsolutePath());
image = ImageIO.read(f_image);
overlay = ImageIO.read(f_overlay);
} catch (IOException e) {
log.error(e.getMessage());
}
// create the new image, canvas size is the max. of both image sizes
int w = Math.max(image.getWidth(), overlay.getWidth());
int h = Math.max(image.getHeight(), overlay.getHeight());
BufferedImage combined = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
// paint both images, preserving the alpha channels
Graphics g = combined.getGraphics();
g.drawImage(image, 0, 0, null);
g.drawImage(overlay, 0, 0, null);
// Save as new image
try {
ImageIO.write(combined, "PNG", f_image);
} catch (IOException e) {
log.error(e.getMessage());
}
// we can delete the overlay now
log.debug("Delete overlay: " + f_overlay.delete());
Are there any suggestions?
I can't see anything wrong in your code.
However, I would only delete the file f_overlay if the reading was successful. Important, after you call delete() on the file object, you must not use the object for anything else, so best is to assign f_overlay=null
boolean state = f_overlay.delete();
f_overlay=null;
log.debug("Delete ... "+state);

Grab image from clipboard on Mac OSX using applet

I am using an Applet to save image from clipboard. The image is saved but something happened with its format. It is darken and lost colors.
here's how I am doing it:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
//create clipboard object
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
//file that we'll save to disk.
File file = new File("/tmp/clipboard.jpg");
//class to write image to disk. You specify the image to be saved, its type,
// and then the file in which to write the image data.
ImageIO.write(image, "jpg", file);
//getData throws this.
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
return "Não tem imagem na área de transferência";
} catch (Exception ioe){
ioe.printStackTrace();
}
return null;
}
}
);
I read that Mac uses a different image format but I did not find how to convert it to a format I could save. I imagined that java should have taken care of that.
So, how can I convert the image from clipboard to jpg?
PS. I tried using png instead of jpg, got a worse result: black image
To solve the issue on Mac, I used the solution proposed on The nightmares of getting images from the Mac OS X clipboard using Java.
I pass the retrieved BufferedImage to method that redraws it to new BufferedImage, returning a valid image. Here follows the code from that page:
public static BufferedImage getBufferedImage(Image img) {
if (img == null) return null;
int w = img.getWidth(null);
int h = img.getHeight(null);
// draw original image to thumbnail image object and
// scale it to the new size on-the-fly
BufferedImage bufimg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bufimg.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.drawImage(img, 0, 0, w, h, null);
g2.dispose();
return bufimg;
}
And how I use it:
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//Get data from clipboard and assign it to an image.
//clipboard.getData() returns an object, so we need to cast it to a BufferdImage.
BufferedImage image = (BufferedImage) clipboard.getData(DataFlavor.imageFlavor);
if (isMac()) {
image = getBufferedImage(image);
}
PNG is the preferred image format for Macs. You might want to try saving as that and then converting to a JPG if needed afterwards.

My batch jpg resizer works with color images, but grayscale ones become washed out

I've been having a problem with my Java program. It's for resizing images. You drop it into a folder and run it, and it creates a new folder with the resized images. It works great on color, but it has a problem with grayscale. The images are converted, but they become lighter and more washed out, as if someone has messed with the curves or levels. All the input files and output files are sRGB color space jpegs, saved in RGB color mode. I have thousands of 50 megapixel film scans I'm trying to convert down to 15 megapixels or less. Any help or ideas anyone could offer would be most appreciated. The programs full code is below, it's about 130 lines. I have a feeling the problem may be in the toBufferedImage function but I'm lost as to what it could be.
package jpegresize;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
System.out.println("JPEGResize running . . .");
int max_side = 4096;
float quality = 0.9f;
if(args.length == 0) System.out.println("No maximum side resolution or compression quality arguments given, using default values.\nUsage: java -jar JPEGResize.jar <maximum side resolution in pixels> <quality 0 to 100 percent>");
if(args.length >= 1) max_side = Integer.parseInt(args[0]);
if(args.length >= 2) quality = Float.parseFloat(args[1]) / 100.0f;
System.out.println("Maximum side resolution: " + max_side);
System.out.println("Compression quality: " + (quality * 100) + "%");
File folder = new File(".");
File[] listOfFiles = folder.listFiles(new JPEGFilter());
for(int i = 0; i < listOfFiles.length; i++) {
System.out.println("Processing " + listOfFiles[i].getName() + " . . .");
resizeFile(listOfFiles[i].getName(), max_side, quality);
System.out.println("Saved /resized/" + listOfFiles[i].getName());
}
System.out.println("Operations complete.");
}
public static void resizeFile(String filename, int max_side, float quality) {
try
{
BufferedImage input_img = ImageIO.read(new File(filename));
double aspect_ratio = ((double)input_img.getWidth()) / ((double)input_img.getHeight());
int width, height;
if(input_img.getWidth() >= input_img.getHeight()) {
width = max_side;
height = (int)(((double)max_side) / aspect_ratio);
}
else {
width = (int)(((double)max_side) * aspect_ratio);
height = max_side;
}
Image scaled_img = input_img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage output_img = toBufferedImage(scaled_img);
Iterator iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter)iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
File doesDirExist = new File("resized/");
if(!doesDirExist.exists())
new File("resized").mkdir();
File file = new File("resized/" + filename);
FileImageOutputStream output = new FileImageOutputStream(file);
writer.setOutput(output);
IIOImage image = new IIOImage(output_img, null, null);
writer.write(null, image, iwp);
writer.dispose();
}
catch (IOException e)
{
e.printStackTrace();
}
}
// This method returns a buffered image with the contents of an image
public static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
}
class JPEGFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.toLowerCase().endsWith(".jpg")) || (name.toLowerCase().endsWith(".jpeg"));
}
}
If jdk's classes and methods are buggy, report the bug to oracle (oh! I wish I could go on saying to SUN..).
And, while the next release will correct the bug ;), try some work arounds, scaling image by yourself like proposed here.
Regards,
Stéphane
In your code, you assume jpeg are encoded in RGB, but that's not always the case. It's also possible to encode 8 bit gray scaled jpeg. So I suggest that you try this when building your BufferedImage, replace :
BufferedImage.TYPE_INT_RGB;
by
BufferedImage.TYPE_BYTE_GRAY;
and see if it works for those images.
If so, then you still have to find out a way to determine the encoding type to automatically change the type of BufferedImage color encoding to use, but you will be one stop closer.
Regards,
Stéphane

Categories

Resources