I have been busy with trying to get the webcam to work within netbeans over the past few days.
The problem I am having is to get the coding to activate and take a picture using the webcam.
So far I have seen that I will have to use the OpenCV and some other JAR files.
Please could someone help me out by perfecting the coding I have below:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// coding for webcam and taking a picture
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
try
{
//start of the webcam for taking the picture
grabber.start();
Image IM = this.takePicture();
//stops the webcam
grabber.stop();
}
catch (Exception e)
{
//displays error message if problem with webcam
JOptionPane.showMessageDialog(null, "Problem accessing or using the Webcam!");
}
}
What I need is for the picture to be displayed in a label on my interface after it has taken the picture.
The Open CV has been successfully installed and now just the coding needed to get the picture taken.
Any Help would be helpful.
Okay, your coding is a bit off, it does need some changes made to it. You are on the right track however.
I do have a sample code that may be able to help you out which works:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// coding for webcam and taking a picture
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
try
{
//start of the webcam for taking the picture
grabber.start();
//grabs teh image taken from the webcam
IplImage img = grabber.grab();
//checks if the webcam has taken the picture and if the picture if mot empty
if(img != null)
{
//determines where to save the picture
cvSaveImage("C:\\User1\\PrifilePicture\\"+lbl_StudnetLogin.getText()+".jpeg", img);
}
//stops the webcam
grabber.stop();
//used to resize teh picture taken in order to display picture to the user
Image imeResize = ImageIO.read(new File("C:\\SalVentri\\PrifilePicture\\"+lbl_StudnetLogin.getText()+".jpeg"));
//1st ---> width _______2sn ---> height
lbl_Profile.setIcon(new ImageIcon(imeResize.getScaledInstance(155, 100, 100)));
}
catch (Exception e)
{
//displays error message if problem with webcam
JOptionPane.showMessageDialog(null, "Problem accessing or using the Webcam!");
}
}
Hope this helps
I found that this works as well.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.opencv.core.*;
import org.opencv.highgui.Highgui;
import org.opencv.highgui.VideoCapture;
public class JPanelOpenCV extends JPanel{
BufferedImage image;
public static void main (String args[]) throws InterruptedException{
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
JPanelOpenCV t = new JPanelOpenCV();
VideoCapture camera = new VideoCapture(0);
Mat frame = new Mat();
camera.read(frame);
if(!camera.isOpened()){
System.out.println("Error");
}
else {
while(true){
if (camera.read(frame)){
BufferedImage image = t.MatToBufferedImage(frame);
t.window(image, "Original Image", 0, 0);
t.window(t.grayscale(image), "Processed Image", 40, 60);
//t.window(t.loadImage("ImageName"), "Image loaded", 0, 0);
break;
}
}
}
camera.release();
}
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
public JPanelOpenCV() {
}
public JPanelOpenCV(BufferedImage img) {
image = img;
}
//Show image on window
public void window(BufferedImage img, String text, int x, int y) {
JFrame frame0 = new JFrame();
frame0.getContentPane().add(new JPanelOpenCV(img));
frame0.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame0.setTitle(text);
frame0.setSize(img.getWidth(), img.getHeight() + 30);
frame0.setLocation(x, y);
frame0.setVisible(true);
}
//Load an image
public BufferedImage loadImage(String file) {
BufferedImage img;
try {
File input = new File(file);
img = ImageIO.read(input);
return img;
} catch (Exception e) {
System.out.println("erro");
}
return null;
}
//Save an image
public void saveImage(BufferedImage img) {
try {
File outputfile = new File("Images/new.png");
ImageIO.write(img, "png", outputfile);
} catch (Exception e) {
System.out.println("error");
}
}
//Grayscale filter
public BufferedImage grayscale(BufferedImage img) {
for (int i = 0; i < img.getHeight(); i++) {
for (int j = 0; j < img.getWidth(); j++) {
Color c = new Color(img.getRGB(j, i));
int red = (int) (c.getRed() * 0.299);
int green = (int) (c.getGreen() * 0.587);
int blue = (int) (c.getBlue() * 0.114);
Color newColor =
new Color(
red + green + blue,
red + green + blue,
red + green + blue);
img.setRGB(j, i, newColor.getRGB());
}
}
return img;
}
public BufferedImage MatToBufferedImage(Mat frame) {
//Mat() to BufferedImage
int type = 0;
if (frame.channels() == 1) {
type = BufferedImage.TYPE_BYTE_GRAY;
} else if (frame.channels() == 3) {
type = BufferedImage.TYPE_3BYTE_BGR;
}
BufferedImage image = new BufferedImage(frame.width(), frame.height(), type);
WritableRaster raster = image.getRaster();
DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer();
byte[] data = dataBuffer.getData();
frame.get(0, 0, data);
return image;
}
}
Related
I need to rotate ImageIcon to buffered image in Java. I've tried every possible way, is there any way, I already tried to convert ImageIcon to bufferedImage.
I tried every possible StackOverflow solution
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
public class Test {
public static void main(String[] args) {
// Create GUI
GUI gui = new GUI();
// Schedule task; rotate img every 1s
Timer timer = new Timer(1000, e -> gui.rotateImg());
timer.setRepeats(true);
timer.start();
}
static class GUI extends JFrame {
// Web url for image of cute doggo
private static final String IMAGE_URL = "https://i.pinimg.com/736x/10/b2/6b/10b26b498bc3fcf55c752c4e6d9bfff7.jpg";
// Cache image and UI components for rotation
private BufferedImage image;
private ImageIcon icon;
private JLabel label;
// Create new JFrame
public GUI() {
// Config grame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 700);
setLocationRelativeTo(null);
URL url;
image = null;
try {
// Download + cache image from web
url = new URL(IMAGE_URL);
image = ImageIO.read(url);
} catch (IOException e) {
// Handle error downloading
System.out.println("Failed to read image due to: " + e.getMessage());
} finally {
// On success - create/cache UI components
if (image != null) {
// In this example I am using a label here to display an ImageIcon
// But at root the ImageIcon is holding a BufferedImage which is what we're modifying on rotation
add(label = new JLabel(icon = new ImageIcon(image)));
}
}
// Show configured JFrame
setVisible(true);
}
public void rotateImg() {
if (image == null) return;
// Rotate image
BufferedImage rotated = rotateImg(image, Math.toRadians(90));
// Add rotated image
icon.setImage(image = rotated);
// Repaint
label.revalidate();
label.repaint();
}
// SRC: https://www.delftstack.com/howto/java/java-rotate-image/
private BufferedImage rotateImg(BufferedImage img, double degrees) {
int w = img.getWidth(), h = img.getHeight();
BufferedImage imgCopy = new BufferedImage(w, h, img.getType());
Graphics2D g2d = imgCopy.createGraphics();
g2d.rotate(degrees, w / 2, h / 2);
g2d.drawImage(img, null, 0, 0);
return imgCopy;
}
}
}
I'm working on image processing but I can't find a way to paint GUI RGB with binary image reading. I'm stuck with paintComponent area.
I can read file but cant paint RGB values to GUI. Can somebody guide me please?
This is what I have done so far:
private int ws;
private FileInputStream fis;
mybin(){
try {
fis = new FileInputStream("mybin.bin");
String mn = getMagicNumber();
System.out.println(mn);
skipWhitespace();
int width = readNumber();
System.out.println(width);
skipWhitespace();
int height = readNumber();
System.out.println(height);
skipWhitespace();
int maxNum = readNumber();
System.out.println(maxNum);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e2) {}
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600,600);
this.setVisible(true);
}
private String getMagicNumber() {
byte [] magicNum = new byte[2];
try {
fis.read(magicNum);
} catch (IOException e) {
e.printStackTrace();
}
return new String(magicNum);
}
private void skipWhitespace() {
try {
ws = fis.read();
while(Character.isWhitespace(ws))
ws = fis.read();
} catch (IOException e) {
e.printStackTrace();
}
}
private int readNumber() {
String wstr = "";
try {
while(!Character.isWhitespace(ws)) {
//while(Character.isDigit(ws))
wstr = wstr + (ws-'0'/*48*/);
ws = fis.read();
}
}catch(IOException e2) {}
System.out.println(wstr);
return Integer.parseInt(wstr);
}
class DrawingPanel extends JPanel{
#Override
public void paintComponent(Graphics g) {
}
}
public static void main(String [] args) {
new mybin();
}
}
If you have a data structure to hold RGB values and want to paint them on the screen:
First you should create an image of them, first. Something like this:
// Create an image, with given dimensions, and RGB palette...
final BufferedImage image = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB);
// Paint the RGB values (EG from arrays) to the image
for (int x = 0; x < width; ++x)
for (int y = 0; y < height; ++y)
{
// Convert the R,G,B values to a single int
final int rgb = r[x,y]*0x10000 + g[x,y]*1x100 + b[x,y];
// Color the pixel...
image.setRGB(x, y, rgb);
}
Then display it on your GUI.
This could be done, creating a special component, and performing painting, see c0der's answer.
Or you could just create an Icon, and add it to any JLabel:
label.setIcon(new ImageIcon(image));
Painting a BufferedImage can be as simple as:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
public class ImageFrame extends javax.swing.JFrame {
public ImageFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(new GraphicsPanel());
pack();
setVisible(true);
}
public static void main(final String[] args){
new ImageFrame();
}
}
class GraphicsPanel extends JPanel {
private BufferedImage image;
//always use publicly accessible resources when posting mcve
private final String imagePath = "https://upload.wikimedia.org/wikipedia/commons/3/3f/Crystal_Project_bug.png";
GraphicsPanel(){
try {
image = ImageIO.read(new URL(imagePath)); //or image = ImageIO.read(new File(...));
} catch(final IOException e) {e.printStackTrace(); }
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
}
#Override
protected void paintComponent(final Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}
Hey,I'm trying to make a program which loads a colored image as grayscale on canvas and then returns the color to the pixels clicked.
I'm stuck here when the setrgb() method is not doing what its supposed to. I have copied the color from original image by getRGB() and am using setRGB() to assign it to a new image.
I have tried to output both the pixel color values but they are not same.
Please help me out with this.
Here's the code so far:
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.awt.*;
import java.applet.*;
#SuppressWarnings("serial")
public class BlackWHite extends Applet implements MouseListener
{
String str;
int x=0,y=0;
BufferedImage bimg = null;
BufferedImage nimg = null;
BufferedImage image=null;
double image_width =300;
double image_height=300;
private Image img;
public void init()
{
img = null;
str = JOptionPane.showInputDialog(null, "Enter file location : ",
"Choose Image", 1);
BufferedImage image=null;
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
e.printStackTrace();
}
//getting width and height of image
image_width = image.getWidth();
image_height = image.getHeight();
BufferedImage img = image;
//drawing a new image
bimg = new BufferedImage((int)image_width, (int)image_height,
BufferedImage.TYPE_BYTE_GRAY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
nimg = new BufferedImage((int)image_width, (int)image_height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = nimg.createGraphics();
g.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
addMouseListener(this);
}
public void loadImage()
{
try {
img = getImage(getCodeBase(), "blackwhiteimage.jpg");
} catch(Exception e) {
}
}
public void paint(Graphics g)
{
try {
image = ImageIO.read(new File(str));
} catch (IOException e) {
e.printStackTrace();
}
convert(); //converting the image
if (img == null)
loadImage(); //draw
g.drawImage(img, 0, 0, this);
int c = image.getRGB(x,y);
int red = (c & 0x0000FFFF) >> 16;
int green = (c & 0x0000FFFF) >> 8;
int blue = c & 0x0000FFFF;
c=(red << 16) | (green << 8) | blue;
System.out.print("c="+c);
nimg=bimg;
nimg.setRGB(x,y,c);
try {
ImageIO.write(nimg, "jpg", new File("pixelcolor.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
g.drawImage(nimg, 0, 0, this);
int f = nimg.getRGB(x,y);
System.out.println("f="+f);
}
void convert() {
try {
//saving black and white image onto drive
ImageIO.write(bimg, "jpg", new File("blackwhiteimage.jpg"));
} catch (Exception e) {
System.out.println(e);
}
}
#Override
public void mouseClicked(MouseEvent me) {
x = me.getX();
y = me.getY();
repaint();
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0) {
}
}
The fundamental problem is that you are trying to set the colour of the image in gray scale colour space. That is not the only bug in the applet, but you can start with it. Try using another way to convert the image to gray scale while keeping it in RGBA, such as those shown here: convert a RGB image to grayscale Image reducing the memory in java
I am trying to make image from BufferImage, but it's not working. here is my code ...
This code is not working, can anyone please help me ...
try {
BufferedImage bimage = (BufferedImage)(new ImageIcon("str")).getImage();
BufferedImage image = new BufferedImage(500, 500, bimage.TYPE_BYTE_GRAY);
File outputfile = new File("saved.png");
ImageIO.write(image, "png", outputfile);
Image image_1 = ImageIO.read(new File("saved.png"));
lp2_2.setIcon(new ImageIcon(image_1));
} catch (IOException e) {}
Maybe your way of converting IconImage to BufferedImageis not right.
So you can try the following snippet
BufferedImage bi = new BufferedImage(icon.getIconWidth(),icon.getIconHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
icon.paintIcon(null, g, 0,0);
g.dispose();
After this you can use BufferdImage as you are already using.
Or you can look this question Java converting Image to BufferedImage
if you want to see how to convert Image to 'BifferedImage' because as given in this post you can't just cast Image to BufferedImage.
Although i would request you to add more information like what error or exception you are getting and may be if there is an exception add the stacktrace .
Hopefully this will work better, I have tried it many times.
public void writeImage(String output, String fileName, BufferedImage img) throws IOException {
File file = new File(output + "\\HE\\" + fileName + ".bmp");
ImageIO.write(img, "bmp", file);
}
=================================================================================
If you want to use this image in any JPanel then here is code for it, it is already working fine,
import java.awt.BorderLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class ShowImage {
public ShowImage(final String filename) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame editorFrame = new JFrame("My Frame " +filename);
editorFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
BufferedImage image = null;
try {
image = ImageIO.read(new File(filename));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
ImageIcon imageIcon = new ImageIcon(image);
JLabel jLabel = new JLabel();
jLabel.setIcon(imageIcon);
editorFrame.getContentPane().add(jLabel, BorderLayout.CENTER);
editorFrame.pack();
editorFrame.setLocationRelativeTo(null);
editorFrame.setVisible(true);
}
});
}
}
here is my new code and its working properly ... thank you all for your kind support ...
try{
BufferedImage cat = ImageIO.read(new File(str));
for (int w = 0; w < cat.getWidth(); w++) {
for (int h = 0; h < cat.getHeight(); h++) {
Color color = new Color(cat.getRGB(w, h));
//int averageColor = ((color.getRed() + color.getGreen() + color.getBlue()) / 3);
//int averageColor = int((color.getRed())*0.21 +(color.getGreen())*0.71+(color.getBlue())*0.07);
double r =color.getRed()*0.21;
double g =color.getGreen()*0.71;
double b =color.getBlue()*0.07;
int averageColor = (int)(r+g+b);
Color avg = new Color(averageColor, averageColor, averageColor);
cat.setRGB(w, h, avg.getRGB());
}
}
ImageIO.write(cat, "jpg", new File("image_greyscale.jpg"));
lp2_2.setIcon(new ImageIcon((new ImageIcon("image_greyscale.jpg")).getImage().getScaledInstance( 600, 600, java.awt.Image.SCALE_SMOOTH )));
}catch(IOException e){
e.printStackTrace();
System.exit(1);}
Everyone here missed the point. A BufferedImage is an Image.
My issue: Every time I create graphics from a buffered image and then draw another buffered image to the graphics I get an image that is blank.
My code is as follows.
Graphics2D g2d = atlas.createGraphics();
// images[i] is a buffered image read the fileio
g2d.drawImage(images[i], null, x, y); // Image is not blank, been tested
g2d.dispose();
// then save image
Ironically after trying to create a self contained example which is as follows... it worked. I am not quite sure what I am doing wrong in my code and I am wondering if it is because maybe an image is not static, could an image or another variable not being static affect my drawing?
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
public class Main {
public static void main(String[] args) {
String FOLDER_LOCATION = "./Images/";
BufferedImage atlas = new BufferedImage(2048, 2048, BufferedImage.TYPE_INT_ARGB);
BufferedImage redSquare = readImage(FOLDER_LOCATION + "red.png");
Graphics2D g2d = atlas.createGraphics();
g2d.drawImage(redSquare, null, 0, 0);
g2d.dispose();
writeImage(atlas, FOLDER_LOCATION + "atlas.png");
}
public static BufferedImage readImage(String location) {
BufferedImage img = null;
InputStream is = null;
try {
is = new FileInputStream(location);
img = ImageIO.read(is);
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch(Exception e) {
e.printStackTrace();
}
}
return img;
}
public static void writeImage(BufferedImage bi, String location) {
try {
File file = new File(location);
ImageIO.write(bi, "png", file);
} catch(Exception e) {
e.printStackTrace();
}
}
}
After I save the image I see just a blank 2048 by 2048 image. I printed the entire image out and I get (0, 0, 0), but if I print out any of the image I am drawing to the atlas I get something like (72, 32, 283).
I am not quite sure what I am doing wrong, but my entire source code for this project is here: https://github.com/gemurdock/jTextureAtlas and the branch I am working on is here: https://github.com/gemurdock/jTextureAtlas/tree/alpha.
You have to look at the alpha branch to see my code