Template Matching Java without opencv or 3rd party - java

I am trying to do template matching in java:
This is the code:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.image.DataBufferByte;
public class pro {
public static void main(String[] args) {
try {
// RGB pixel values
byte[] pixels;
File inp=new File("TenCardG.jpg");
BufferedImage image = ImageIO.read(inp);
int width = image.getWidth();
int height = image.getHeight();
// System.out.println("Type: "+image.getColorModel());
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
System.out.println("Dimension of image" + width + " "+height+" "+ " pixels length "+ pixels.length);
//rgb2gray in a 2D array grayImage
int pr;// red
int pg;// green
int pb;// blue
short [][] grayImage =new short [height][width];
int cord;
for (int i=0; i<height;i++)
for(int j=0;j<width;j++)
{
cord= 3*(i*width+j);
pr= ((short) pixels[cord] & 0xff); // red
pg= (((short) pixels[cord+1] & 0xff));// green
pb= (((short) pixels[cord+2] & 0xff));// blue
grayImage[i][j]=(short)Math.round(0.299 *pr + 0.587 * pg + 0.114 * pb);
}
Image scaledImage = image.getScaledInstance(-1,-1, 0);
ImageIO.write(
add_Rectangle(scaledImage),
"jpg",
new File("TenCardG2.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done, check the generated TenCardG2 image at its left top corner");
}
// Add a rectangle of side size 50, 70 at coordinate 0.0 in image img
public static BufferedImage add_Rectangle(Image img) {
if (img instanceof BufferedImage) {
return (BufferedImage) img;
}
// Create a buffered image with transparency
BufferedImage bi = new BufferedImage(
img.getWidth(null), img.getHeight(null),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2D = bi.createGraphics();
g2D.drawImage(img, 0, 0, null);
g2D.setColor(Color.RED);
g2D.drawRect(0, 0, 50, 70);
g2D.dispose();
return bi;
}
}
This is the source image:10 of hearts
This is the template image: Picture of heart
This a matlab code i guess which we change it to java and then implement into that code. I guess that matlab code this it compares bit by bit like and image can be compressed. if so, it will not match. its static processing. we need dynamic one. I don't know where to implement that one
When i run my code which i provide up i get this output which i get
But i should this final output
Can please try to help me

Related

Java recoloring BufferedImage not working with an image of a larger height

I have a program that is supposed to take the RGB values of an image and then multiply them by some constants, and then draw the new image on a JPanel. The problem is that if my image is over a certain height, specifically over 187 pixels, the new colored image is different than an image with a height of less than 187px.
The JPanel shows this: example.
Notice how the longer recolored image is different than the shorter one. I'm sure that the shorter image's colors are correct, and I have no idea how it's getting messed up.
public class RecolorImage extends JPanel {
public static int scale = 3;
public static BufferedImage walk, walkRecolored;
public static BufferedImage shortWalk, shortWalkRecolored;
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(200*scale, 400*scale);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new RecolorImage());
walk = ImageLoader.loadImage("/playerWalk.png");
walkRecolored = recolor(walk);
shortWalk = ImageLoader.loadImage("/playerWalkShort.png");
shortWalkRecolored = recolor(shortWalk);
frame.setVisible(true);
}
#Override
public void paint(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
g.scale(scale, scale);
g.drawImage(walk, 10, 10, null);
g.drawImage(walkRecolored, 40, 10, null);
g.drawImage(shortWalk, 70, 10, null);
g.drawImage(shortWalkRecolored, 100, 10, null);
}
The recolor method:
public static BufferedImage recolor(BufferedImage image) {
BufferedImage outputImage = deepCopy(image);
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int rgb = image.getRGB(x, y);
Color c = new Color(rgb);
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
r *= 0.791;
g *= 0.590;
b *= 0.513;
int newRGB = (rgb & 0xff000000) | (r << 16) | (g << 8) | b;
outputImage.setRGB(x, y, newRGB);
}
}
return outputImage;
}
How I load the images and make deep copies:
public static BufferedImage loadImage(String path) {
try {
return ImageIO.read(ImageLoader.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static BufferedImage deepCopy(BufferedImage image) {
ColorModel colorModel = image.getColorModel();
boolean isAlphaPremultiplied = colorModel.isAlphaPremultiplied();
WritableRaster raster = image.copyData(null);
return new BufferedImage(colorModel, raster, isAlphaPremultiplied, null);
}
My original images: the tall image and short image. Thanks for any help!
Your source images have different color models:
the short image uses 4 bytes per pixel (RGB and alpha)
the tall image uses 1 byte per pixel (index into a palette of 256 colors)
Your recolored images use the same color model as the source images (thanks to the deepCopy method), therefore the recolored image for the tall image also uses the same color palette as the source image, meaning that it cannot contain all the colors you want.
Since your recoloring code overwrites each pixel of the output image anyway the deep copy operation is unnecessary. Instead you would better create a full color image as target image like this:
public static BufferedImage recolor(BufferedImage image) {
BufferedImage outputImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
//... code as before
}

Read in Bufferedimage pixel values then manipulate each one and write to file

I am currently trying to read in an image pixel by pixel and change each colored pixel to the rgb value of (100,100,100). For whatever reason when I check the values of each pixel one the image is saved it has all the colored pixels as (46,46,46) instead.
Here is the original image
After running my program this is the image it gives to me
Here is the code
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Cmaps {
public static void main(String[] args){
File originalImage = new File("C:\\Users\\Me\\Desktop\\0005.bmp");
BufferedImage img = null;
try{
img = ImageIO.read(originalImage);
for(int i = 0; i < img.getHeight(); i++){
for(int j = 0; j < img.getWidth(); j++){
//get the rgb color of the image and store it
Color c = new Color(img.getRGB(i, j));
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
//if the pixel is white then leave it alone
if((r == 255) && (g == 255) && (b == 255)){
img.setRGB(i, j, c.getRGB());
continue;
}
//set the colored pixel to 100,100,100
r = 100;// red component 0...255
g = 100;// green component 0...255
b = 100;// blue component 0...255
int col = (r << 16) | (g << 8) | b;
img.setRGB(i, j, col);
}
}
File f = new File("C:\\Users\\Me\\Desktop\\2\\1.png");
try {
ImageIO.write(img, "PNG", f);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e){
e.printStackTrace();
}
}
}
I have no clue why it doesn't set the pixels to the expected rgb value. I eventually want to be able to basically increment the rgb color as I move down rows and columns in the x and y so what the final image will look like is it will start off dark in the top left corner and then have a fade out effect as you get from that side to the bottom right corner.
Okay, based on the comments:
If the BufferedImage has an IndexColorModel (palette based color model), using setRGB to set a pixel to an arbitrary RGB value will not work. Instead, the color will be looked up, and the pixel will get the color that is considered the closest match in the palette.
Formats like BMP, GIF and PNG may all use IndexColorModel when read using ImageIO.
To convert the image to "true color" (either DirectColorModel or ComponentColorModel in Java will do), you can use:
BufferedImage img; // your original palette image
int w = img.getWidth();
int h = img.getHeight();
BufferedImage trueColor = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Graphics2D g = trueColor.createGraphics();
try {
g.drawImage(img, 0, 0, null);
}
finally {
g.dispose();
}
img = trueColor;
After this, getRGB(x, y) should return what you specify, using setRGB(x, y, argb).

Java BufferedImage to pixel array

I saw a thread on converting a BufferedImage to an array of pixels/bytes. Using getRGB directly on the image works, but is not ideal as it is too slow to gather all pixels. I tried the alternate way of simply grabbing the pixel data.
//convert canvas to bufferedimage
BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2 = img.createGraphics();
canvas.printAll(g2);
g2.dispose();
System.out.println(img.getRGB(0, 0)); //-16777216 works but not ideal
byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
for(byte b : pixels){
System.out.println(b); //all 0 doesnt work
}
However, the whole byte array seems to be empty (filled with 0s).
I don't know what canvas means in your code but this works perfectly:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
public class Px {
public static void main(String[] args) {
new Px().go();
}
private void go() {
BufferedImage img = new BufferedImage(5, 5, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2 = img.createGraphics();
g2.setColor(Color.red);
g2.fillRect(0, 0, 2, 2);
g2.dispose();
byte[] pixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
for (byte b : pixels) {
System.out.print(b + ",");
}
}
}
The result is this:
0,0,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
The color order is blue green red. So my red rect appears as bytes in 0,0,-1,0,0,-1 etc. I assume that -1 is 'the same' as 255.
You could explore your line canvas.printAll(). Maybe the canvas only contains black pixels.

setRGB() doesn't seem to change the color

could you please tell me why the pixels won't set to red
Color myColor = new Color(255, 0, 0);
int rgb = myColor.getRGB();
String fileName = Config.IMAGEFILEPATH + "first_nodal_domain "
+ "full.png";
BufferedImage bi = new BufferedImage(AZIMUTH_RES, ELEVATION_RES, BufferedImage.TYPE_USHORT_GRAY);
for (int i = 0; i < AZIMUTH_RES; i++){
for (int j = 0; j < ELEVATION_RES; j++){
bi.setRGB(i,j,(255 << 16) + (255 << 8) + 255);
}
}
for (Point draw: shadedPoints){
bi.setRGB(draw.x, draw.y, rgb);
}
BufferedImage scaledImage = new BufferedImage(
1000, 1000, BufferedImage.TYPE_USHORT_GRAY);
// Paint scaled version of image to new image
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(bi, 0, 0, 1000, 1000, null);
try {
// write out image to file as .png
ImageIO.write(scaledImage, "png", new File(fileName));
} catch (IOException ex) {
Logger.getLogger(NodalDomainsDrawing.class.getName()).log(Level.SEVERE, null, ex);
}
bi.flush();
thanks in advance.
With respect, you seem to be going about this very strangely...
Rather then trying to draw directly to the pixel level, you should be making use of the Graphics API capabilities.
For example, clearing the image is going to be significantly faster using Graphics#fillRect then looping through and setting each pixel.
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class TestImage02 {
public static void main(String[] args) {
Color myColor = new Color(255, 0, 0);
// int rgb = myColor.getRGB();
List<Point> shadedPoints = new ArrayList<>(25);
for (int index = 0; index < 100; index++) {
shadedPoints.add(new Point(index, index));
}
BufferedImage bi = new BufferedImage(100, 100, BufferedImage.TYPE_USHORT_GRAY);
Graphics2D g2d = bi.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 100, 100);
// for (int i = 0; i < 100; i++) {
// for (int j = 0; j < 100; j++) {
// bi.setRGB(i, j, (255 << 16) + (255 << 8) + 255);
// }
// }
g2d.setColor(myColor);
for (Point draw : shadedPoints) {
// bi.setRGB(draw.x, draw.y, rgb);
g2d.drawLine(draw.x, draw.y, 1, 1);
}
g2d.dispose();
BufferedImage scaledImage = new BufferedImage(
1000, 1000, BufferedImage.TYPE_USHORT_GRAY);
// Paint scaled version of image to new image
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(bi, 0, 0, 1000, 1000, null);
graphics2D.dispose();
try {
// write out image to file as .png
ImageIO.write(scaledImage, "png", new File("Test.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
bi.flush();
}
}
I ran your original code (with modifications to make it work) and it worked fine, but I've post some additional code that use Graphics instead.
You should make sure that you are calling Graphics#dispose. On different OS'es the Graphics object can behave differently, meaning that some times, until you dispose of the graphics object, it may not actually paint anything...

Cut out image in shape of text

I need to cut out an image in the shape of the text in another image. I think it's best shown in images.
This is a photo of a cat:
and this is the text I wish to cut out:
The resulting image would be this:
The text image will always be black with a transparent background, and the resulting cut-out should too have a transparent background. Both input images will also be the same size.
import java.awt.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Rectangle2D;
import javax.imageio.ImageIO;
import java.net.URL;
import java.io.File;
class PictureText {
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/Nqf3H.jpg");
BufferedImage originalImage = ImageIO.read(url);
final BufferedImage textImage = new BufferedImage(
originalImage.getWidth(),
originalImage.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = textImage.createGraphics();
FontRenderContext frc = g.getFontRenderContext();
Font font = new Font(Font.SANS_SERIF, Font.BOLD, 250);
GlyphVector gv = font.createGlyphVector(frc, "Cat");
Rectangle2D box = gv.getVisualBounds();
int xOff = 25+(int)-box.getX();
int yOff = 80+(int)-box.getY();
Shape shape = gv.getOutline(xOff,yOff);
g.setClip(shape);
g.drawImage(originalImage,0,0,null);
g.setClip(null);
g.setStroke(new BasicStroke(2f));
g.setColor(Color.BLACK);
g.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.draw(shape);
g.dispose();
File file = new File("cat-text.png");
ImageIO.write(textImage,"png",file);
Desktop.getDesktop().open(file);
}
}
Create a new BufferedImage and iterate over all the pixels of word cat and if they are black, copy the cat-image pixels to the new image.
Here is some code: (Final working code, supports anti-alias)
public static BufferedImage textEffect(BufferedImage image, BufferedImage text) {
if (image.getWidth() != text.getWidth() ||
image.getHeight() != text.getHeight())
{
throw new IllegalArgumentException("Dimensions are not the same!");
}
BufferedImage img = new BufferedImage(image.getWidth(),
image.getHeight(),
BufferedImage.TYPE_INT_ARGB_PRE);
for (int y = 0; y < image.getHeight(); ++y) {
for (int x = 0; x < image.getWidth(); ++x) {
int textPixel = text.getRGB(x, y);
int textAlpha = (textPixel & 0xFF000000);
int sourceRGB = image.getRGB(x, y);
int newAlpha = (int) (((textAlpha >> 24) * (sourceRGB >> 24)) / 255d);
int imgPixel = (newAlpha << 24) | (sourceRGB & 0x00FFFFFF);
int rgb = imgPixel | textAlpha;
img.setRGB(x, y, rgb);
}
}
return img;
}
Use GlyphVector. Use Font class
public GlyphVector layoutGlyphVector(FontRenderContext frc,
char[] text,
int start,
int limit,
int flags) {
You can get outline Shape from glyph vector by public abstract Shape getOutline()
Assign the outline Shape as a clip to your Graphics instance.
Draw the image on the graphics.
Only clipped shape will be filled.
No java here, but the needed image operations are easy to understand. In Mathematica:
You can do it in Java with just a few lines of source code, using Marvin Framework
source code:
public class CutAndFill {
public static void main(String[] args) {
// 1. Load images
MarvinImage catImage = MarvinImageIO.loadImage("./res/catImage.jpg");
MarvinImage catText = MarvinImageIO.loadImage("./res/catText.png");
// 2. Load plug-in, set parameters and process de image
MarvinImagePlugin combine = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.combine.combineByMask");
combine.setAttribute("combinationImage", catImage);
combine.setAttribute("colorMask", Color.black);
combine.process(catText.clone(), catText);
// 3. Save the output image.
MarvinImageIO.saveImage(catText, "./res/catOut.jpg");
}
}
First, make the black portion of the "Cat" image transparent. See here for help with this. Then, composite that image over the picture of your favorite cat (mine is Sheeba).
The nice thing about this is you can make the transparent text image once, save it, and then apply it to all of Sheeba's family and friends!

Categories

Resources