background of an image not fully accurate around text - java

I have an issue where I have an image with a fully black background that I have added text to.
the program works well except that the background close, around the text, isn't fully black.
the program I'm trying to do takes a picture and areas where the pixels are bright add characters such as "#" and dark areas are filled with " "(space) or ".".
my current code is:
import java.awt.*;
import java.io.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public static void main(String[] args) throws Exception {
BufferedImage image = ImageIO.read(new File("Person.jpg"));
Graphics g = image.getGraphics();
g.setFont(new Font("Times New Roman", Font.PLAIN,10));
Color backGround = new Color(0,0,0);
int bg = backGround.getRGB();
int pixelSize = 10;
for(int i = 0; i < image.getWidth()-pixelSize;i+=pixelSize){
for(int j =0; j <image.getHeight()-pixelSize;j+=pixelSize){
Color color = grayScale(image, i,j, pixelSize); /*grayScale() take the area...
of wanted pixel size and takes the average color and then grayscale it. */
for(int x = 0; x < pixelSize; x++){
for(int y = 0; y < pixelSize; y++){
image.setRGB(x+i,y+j, bg);
}
}
g.setColor(new Color(255,255,255));
g.drawString(acill(color), i, j); /* acill() maps the brightness of the pixel...
to a string of characters ex: string c = " .:!#" if the pixel i bright (255,255,255)
then the function returns "#". */
}
}
g.dispose();
ImageIO.write(image, "jpg", new File("Person1.jpg"));
}
}

managed to solve it by changing the picture file from jpg to png. I do not know what causes this but at least it works. If anyone knows why I'd be happy to know.

The noise you see in your image is fully expected, and is an artifact of lossy JPEG compression. You may get rid of some of it, by increasing the JPEG quality setting, at the expense of a larger file. But using lossy JPEG will always cause some such noise, and will never be able to exactly retain the information in your original image (thus "lossy"). JPEG is also created to compress "natural images" efficiently, and is not very good at compression "artificial" images like this.
As your image is black and white (bitonal) only, it is probably much better to use a lossless file format that natively supports bitonal images, like PNG, TIFF with "fax" compression, even BMP. For your image, these are likely to compress the data better than JPEG anyway. You could also use JBIG, which is a lossy format created for bitonal images, but only if you can accept the fact that it may not exactly retain your image.

Related

Pixel relocation, showing side-by-side

I want to read individual pixels from one image and "relocate" them to another image. I basically want to simulate how it would be if I grabbed pixel by pixel from one image and "move" them to a blank canvas. Turning the pixels I grab from the original image white.
This is what I have right now, I'm able to read the pixels from the image and create a copy (which comes out saturated for some reason) of it.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageTest
{
public static void main(String args[])throws IOException
{
//create buffered image object img
File oldImgFile = new File("/path/to/image/shrek4life.jpg");
BufferedImage oldImg = null;
BufferedImage newImg = null;
try{
oldImg = ImageIO.read(oldImgFile);
}catch(IOException e){}
newImg = new BufferedImage(oldImg.getWidth(), oldImg.getHeight(), BufferedImage.TYPE_INT_ARGB);
File f = null;
try
{
for(int i = 0; i < oldImg.getWidth(); i++){
for(int j = 0; j < oldImg.getHeight(); j++){
//get the rgb color of the old image and store it the new
Color c = new Color(oldImg.getRGB(i, j));
int r = c.getRed();
int g = c.getGreen();
int b = c.getBlue();
int col = (r<<16) | (g<<8) | b;
newImg.setRGB(i, j, col);
}
}
//write image
f = new File("newImg.jpg");
ImageIO.write(newImg, "jpg", f);
}catch(IOException e){
System.out.println("Error: " + e);
}
}//main() ends here
}//class ends here
And I would like to basically slow the process down and display it happening. But I'm not sure how to do that. Would I need to use to accomplish this ? I'm somewhat new to threading but I think I would need multiple threads to handle the painting of both pictures.
First of all, I would like to mention you are working in a very inefficient way. You are creating a Color, decomposing a pixel in its channels, and moving to the new image by a bit-shift. It is easier if you work directly with the integer the whole time (and more efficient).
I will assume the image "/path/to/image/shrek4life.jpg" has ARGB color space. I recommend ensure this, because if the old image does not have this color space you should make a conversion.
When you create the new image, you create it as ARGB color space, so each channel is expressed in a byte of the int, first byte for Alpha, second byte for red, third byte for green and the last one for blue.
I think you forgot the alpha channel when you manipulated the old image pixel to move it into the new image.
With this explanation in mind, I think you can change your code to increase the efficiency, like this:
for(int i = 0; i < oldImg.getWidth(); i++){
for(int j = 0; j < oldImg.getHeight(); j++){
int pixel = oldImg.getRGB(i,j);
newImg.setRGB(i, j, pixel );
//If you like to get more control over the pixels and print
//you can decompose the pixel using Color as you already do
//But when you understand fully the process I recommend erase it
Color c = new Color(pixel);
//Print the color or do whatever you like
}
}
About how to display the process of pixel relocation:
In process:
You can print the changed pixel as a number with its position in image (discouraged). System.out.println("pixel"+pixel+" X:"+i+" Y:"+j);
Use this tutorial in baeldung to print an image. I suggest draw a rectangle with the color of the image and wait for a key press (enter, for example) using Scanner. After the key was press, you can load the next pixel, an so on.
If a single rectangle with just one pixel has little information, I suggest add an array of rectangles to draw several pixels in a time. Even you can print an image, and see the process pixel by pixel, using Scanner to mark each step.
As #haraldK suggest, you can use Swing to display de relocation image. Through swing timer and invokes update()
Post process:
Save the image in a file. To improve the speed of process, I suggest save a few pixels (10 - 100).

Write pixel data in a grayscale image in java

I am developing a project on image processing where I have to fill the digitized images of cracked paintings. I have to convert a color image to grayscale, performing some calculations on the 2D Array of the gray image and writing it back as gray image. The code for this is:
BufferedImage colorImage=ImageIO.read(new File(strImagePath));
BufferedImage image = new BufferedImage(colorImage.getWidth(),colorImage.getHeight(),BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image.getGraphics();
g.drawImage(colorImage, 0, 0, null);
g.dispose();
ImageIO.write(image,"PNG",new File("Image.PNG"));
BufferedImage imgOriginal=ImageIO.read(new File("Image.PNG"));
int width=image.getWidth();
int height=image.getHeight();
BufferedImage im=new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
int arrOriginal[][]=new int[height][width];
for(int i=0;i<height;i++)
for(int j=0;j<width;j++)
arrOriginal[i][j]=imgOriginal.getRGB(j,i)& 0xFF;
for(int i=0;i<height;i++)
for(int j=0;j<width;j++)
im.setRGB(j,i,arrOriginal[i][j]);
ImageIO.write(im,"PNG",new File("Image1.PNG"));
But the output image is very much darker, I am not getting the original image back (I have not done any changes yet).
I think there should be some changes in setRGB() statement but I don't know what.
To write image back, I have also tried:
`
BufferedImage im = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
WritableRaster raster = im.getRaster();
for(int i=0;i<height;i++)
for(int j=0;j<width;j++)
raster.setSample(j,i,0,arrOriginal[i][j]);
`
But it also don't give me original image back.
Can anyone provide me the solution of this problem?
Thanks in advance.
I don't know anything about Java-based image processing, but I do know quite a lot about image processing in general, so I will see if I can give you any ideas. Please don't shoot me if I am wrong - I am just suggesting an idea.
In a greyscale image, the red, green and blue values are all the same, i.e. Red=Green=Blue. So, when you call getRGB and do the AND with 0xff, you are probably getting the blue component only, but that is ok as the red and green are the same - because it's greyscale.
I suspect the problem is that when you write it back to create your new output image, you are only setting the blue component and not the red and green - which should still be the same. Try writing back
original pixel + (original pixel << 8 ) + (original pixel <<16)
so that you set not only the Blue, but also the Red and Green components.

Get Pixel Color around an image

I have an image, and I figured out how to use robot and getPixelColor() to grab the color of a certain pixel. The image is a character that I'm controlling, and I want robot to scan around the image constantly, and tell me if the pixels around it equal a certain color. Is this at all possible? Thanks!
Myself, I'd use the Robot to extract the image that's just a little larger than the "character", and then analyze the BufferedImage obtained. The details of course will depend on the details of your program. Probably the quickest would be to get the BufferedImage's Raster, then get thats dataBuffer, then get thats data, and analyze the array returned.
For example,
// screenRect is a Rectangle the contains your "character"
// + however many images around your character that you desire
BufferedImage img = robot.createScreenCapture(screenRect);
int[] imgData = ((DataBufferInt)img.getRaster().getDataBuffer()).getData();
// now that you've got the image ints, you can analyze them as you wish.
// All I've done below is get rid of the alpha value and display the ints.
for (int i = 0; i < screenRect.height; i++) {
for (int j = 0; j < screenRect.width; j++) {
int index = i * screenRect.width + j;
int imgValue = imgData[index] & 0xffffff;
System.out.printf("%06x ", imgValue );
}
System.out.println();
}

What's the appropriate way to colorize a grayscale image with transparency in Java?

I'm making an avatar generator where the avatar components are from PNG files with transparency. The files are things like body_1.png or legs_5.png. The transparency is around the parts but not within them and the images are all grayscale. The parts are layering fine and I can get a grayscale avatar.
I would like to be able to colorize these parts dynamically, but so far I'm not having good luck. I've tried converting the pixel data from RGB to HSL and using the original pixel's L value, while supplying the new color's H value, but the results are not great.
I've looked at Colorize grayscale image but I can't seem to make what he's saying work in Java. I end up with an image that has fairly bright, neon colors everywhere.
What I would like is for transparency to remain, while colorizing the grayscale part. The black outlines should still be black and the white highlight areas should still be white (I think).
Does anyone have a good way to do this?
EDIT:
Here's an image I might be trying to color:
Again, I want to maintain the brightness levels of the grayscale image (so the outlines stay dark, the gradients are visible, and white patches are white).
I've been able to get a LookupOp working somewhat based on Colorizing images in Java but the colors always look drab and dark.
Here's an example of my output:
The color that was being used is this one (note the brightness difference): http://www.color-hex.com/color/b124e7
This is my lookupOp
protected LookupOp createColorizeOp(short R1, short G1, short B1) {
short[] alpha = new short[256];
short[] red = new short[256];
short[] green = new short[256];
short[] blue = new short[256];
//int Y = 0.3*R + 0.59*G + 0.11*B
for (short i = 0; i < 30; i++) {
alpha[i] = i;
red[i] = i;
green[i] = i;
blue[i] = i;
}
for (short i = 30; i < 256; i++) {
alpha[i] = i;
red[i] = (short)Math.round((R1 + i*.3)/2);
green[i] = (short)Math.round((G1 + i*.59)/2);
blue[i] = (short)Math.round((B1 + i*.11)/2);
}
short[][] data = new short[][] {
red, green, blue, alpha
};
LookupTable lookupTable = new ShortLookupTable(0, data);
return new LookupOp(lookupTable, null);
}
EDIT 2: I changed my LookupOp to use the following and got much nicer looking colors:
red[i] = (short)((R1)*(float)i/255.0);
green[i] = (short)((G1)*(float)i/255.0);
blue[i] = (short)((B1)*(float)i/255.0);
It seems what will work for you is something like this:
for each pixel
if pixel is white, black or transparent then leave it alone
else
apply desired H and S and make grayscale value the L
convert new HSL back to RGB
Edit: after seeing your images I have a couple of comments:
It seems you want to special treat darker tones, since you are not colorizing anything below 30. Following the same logic, shouldn't you also exempt from colorizing the higher values? That will prevent the whites and near-whites from getting tinted with color.
You should not be setting the alpha values along with RGB. The alpha value from the original image should always be preserved. Your lookup table algorithm should only affect RGB.
While you say that you tried HSL, that is not in the code that you posted. You should do your colorizing in HSL, then convert the resulting colors to RGB for your lookup table as that will preserve the original brightness of the grayscale. Your lookup table creation could be something like this:
short H = ??; // your favorite hue
short S = ??; // your favorite saturation
for (short i = 0; i < 256; i++) {
if (i < 30 || i > 226) {
red[i] = green[i] = blue[i] = i; // don't do alpha here
}
else {
HSL_to_RGB(H, S, i, red[i], green[i], blue[i])
}
}
Note: you have to provide the HSL to RGB conversion function. See my answer on Colorize grayscale image for links to source code.

Can I save a huge PNG without the whole thing being in memory?

I'm saving a very large PNG (25 MB or so) with Java. The problem is that while it's being generated, it's using 3+ gigabytes of memory, which is not ideal since it severely slows down systems with low memory.
The code I'm working with needs to combine a set of tiled images into a single image; in other words, I have nine images (PNG):
A1 A2 A3
B1 B2 B3
C1 C2 C3
which need to be combined into a single image.
The code I'm using is this:
image = new BufferedImage(width, height, height, BufferedImage.TYPE_INT_ARGB_PRE);
g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
// draw the 9 images on here at their proper positions...
// save image
g2d.dispose();
File file = getOutputFile();
ImageIO.write(image, "png", file);
Is there a way to make and save an image without having the entire image in memory?
Edit:
To draw the images, I'm doing this in a loop:
BufferedImage tile = ImageIO.read(new File("file.png"));
g2d.drawImage(tile, x, y, w, h);
This is being repeated many times (it's usually about 25x25, but sometimes more), so if there is even a small memory leak here, that could be causing the problem.
You can also take a look at this PNGJ library (disclaimer: I coded it), it allows to save a PNG image line by line.
ImageIO.write(image, "png", file); is internally using com.sun.imageio.plugins.png.PNGImageWriter. That method and that writer expect image to be a rendered image but PNG writting is done by 'bands' so you can make a subclass of RenderedImage that generates the requested bands of the composed large image as the writer ask for that bands to the image.
From PNGImageWriter class:
private void encodePass(ImageOutputStream os,
RenderedImage image,
int xOffset, int yOffset,
int xSkip, int ySkip) throws IOException {
// (...)
for (int row = minY + yOffset; row < minY + height; row += ySkip) {
Rectangle rect = new Rectangle(minX, row, width, 1); // <--- *1
Raster ras = image.getData(rect); // <--- *2
*2 I think this is the only place where the writer reads pixels from you image. You should make a getData(rect) method that computes that rect joining 3 bands from 3 images into one.
*1 As you see it reads bands with a height of 1 pixel.
If the things are as I think you should only need to compose 3 images at a time. There would be no need for the other 6 to be in memory.
I know it is not an easy solution but it might help you if you don't find anything easier.
Would using an external tool be an option? I remember using ImageMagick for similar purpose, you would need to save your smaller images first.

Categories

Resources