I am trying to read an Image pixel by pixel and want to save the pixel RGB value in arrays.
but when trying to do so I am getting an exception in the statement
R[i]=redValue;
Someone please suggest what I might doing wrong?
please find the exception stack trace here -
paste.ubuntu.com/6216208
public class AnalyzeImage extends Activity
{
int []R;
int []G;
int []B;
int width, height, i=0;
int a=1;
public int analyzeImagefunc(Bitmap bitmap)
{
try{
width = bitmap.getWidth();
height = bitmap.getHeight();
i = 0;
for(int x = 0;x < width;x++)
{
for(int y = 0;y < height;y++)
{
int pixel = bitmap.getPixel(x,y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
a=5;
R[i]=redValue;
a=6;
i++;
}
}
}
catch(Exception e)
{
//nothing
}
return a;
}
}
Your arrays need to be initialzed first before using. You have jsut declared the arrays:
int []R;
int []G;
int []B;
but not initialized them.So if you try to access any array element it will throw null pointer exception. Try to initialized your array like:
int []R = new int[10];
int []G = new int[10];
int []B = new int[10];
You can change the size of arrays as per your need.
int []R;
int []G;
int []B;
R, G, B is not initialized any where.
initialize the R
width = bitmap.getWidth();
height = bitmap.getHeight();
i = 0;
int size = height * width;
R = new int[size]; // initialize the size of array R
for(int x = 0;x < width;x++)
Array need initialization with fix size. so if array's size is not fix then you should go with ArrayList. and also you can cast ArrayList to array if needed for final output.
public class AnalyzeImage extends Activity {
int[] R;
int[] G;
int[] B;
ArrayList<Integer> R_Lst = new ArrayList<Integer>();
ArrayList<Integer> G_Lst = new ArrayList<Integer>();
ArrayList<Integer> B_Lst = new ArrayList<Integer>();
int width, height, i = 0;
int a = 1;
public int analyzeImagefunc(Bitmap bitmap) {
try {
width = bitmap.getWidth();
height = bitmap.getHeight();
i = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int pixel = bitmap.getPixel(x, y);
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
a = 5;
// R[i] = redValue;
R_Lst.add(redValue);
B_Lst.add(blueValue);
G_Lst.add(greenValue);
a = 6;
i++;
}
}
}
catch (Exception e) {
// nothing
}
R=convertIntegers(R_Lst);
return a;
}
public int[] convertIntegers(List<Integer> integers)
{
int[] ret = new int[integers.size()];
for (int i=0; i < ret.length; i++)
{
ret[i] = integers.get(i).intValue();
}
return ret;
}
// (Note that this will throw a NullPointerException if either integers or any element within it is null.)
width = bitmap.getWidth();
height = bitmap.getHeight();
int n = width * height;
R = new int[n];
G = new int[n];
B = new int[n];
i = 0;
By implication, you also require:
R[i] = redValue;
G[i] = greenValue;
B[i] = blueValue;
Related
Good morning. I'm a developer trying to put a tensorflow model into Android.
I've encountered an error that I've never seen before while trying to fix it with multiple errors.
The java.nio.BufferOverFlowException error i'm facing now is that it didn't happen before, but it happened suddenly.
My code uses a byte array, but i cannot specify which part is the problem.
This source that takes a float array as input and returns an array with 10 classes after passing through the model.
The returned values have softmax value.
public float[] hypothesis(float[] inputFloats, int nFeatures, int nClasses, Context context)
{
try {
int nInstance = inputFloats.length / nFeatures;
// FloatBuffer.wrap(inputFloats);
Toast.makeText(context, "", Toast.LENGTH_LONG).show();
inferenceInterface.feed(INPUT_NODE, FloatBuffer.wrap(inputFloats), INPUT_SIZE);
inferenceInterface.run(OUTPUT_NODES_HYPO);
float[] result = new float[nInstance * nClasses];
inferenceInterface.fetch(OUTPUT_NODE_HYPO, result);
return result;
}
catch(Exception e){
Toast.makeText(context, e+" ...", Toast.LENGTH_LONG).show();
return null;
}
}
The length of the inputfloats is 720 and the nFeatures is 720. nClasses is 10.
Although the value is not correct, it worked before.
e in the catch statement prints java.nio.BufferOverFlowException.
Could there be a problem in the middle of converting a byte array to a float array?
Related source.
public float[] bytetofloat(byte[] array){
int[] returnArr = new int[array.length/4];
float[] returnArr1 = new float[array.length/4];
for(int i = 0 ; i < returnArr.length; i++){
//array[i] = 0;
returnArr[i] = array[i*4] & 0xFF;
if(returnArr[i] < 0 || returnArr[i]>255)
Log.d("ARRAY", returnArr[i]+" ");
returnArr1[i] = (float)returnArr[i];
}
return returnArr1;
}
public Bitmap RGB2GRAY(Bitmap image){
int width = image.getWidth();
int height = image.getHeight();
Bitmap bmOut;
bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
for(int x = 0; x < width; x++){
for(int y = 0 ; y < height; y++){
int pixel = image.getPixel(x, y);
int A = Color.alpha(pixel);
int R = Color.red(pixel);
int G = Color.green(pixel);
int B = Color.blue(pixel);
R = G = B = (int)(0.2126 * R + 0.7152 * G + 0.0722 * B);
bmOut.setPixel(x, y, Color.argb(A, R, G, B));
}
}
return bmOut;
}
private void activityPrediction(float[] inputArray){
try {
float[] result = activityInference.hypothesis(inputArray, 20*36, 10, getApplicationContext());
predictionView.setText(Arrays.toString(result));
}
catch (Exception e){
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private byte[] bitmapToByteArray(Bitmap bitmap)
{
int chunkNumbers = 10;
int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
byte[] imageBytes = new byte[bitmapSize];
int rows, cols;
int chunkHeight, chunkWidth;
rows = cols = (int) Math.sqrt(chunkNumbers);
chunkHeight = bitmap.getHeight() / rows;
chunkWidth = bitmap.getWidth() / cols;
int yCoord = 0;
int bitmapsSizes = 0;
for (int x = 0; x < rows; x++)
{
int xCoord = 0;
for (int y = 0; y < cols; y++)
{
Bitmap bitmapChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight);
byte[] bitmapArray = getBytesFromBitmapChunk(bitmapChunk);
System.arraycopy(bitmapArray, 0, imageBytes, bitmapsSizes, bitmapArray.length);
bitmapsSizes = bitmapsSizes + bitmapArray.length;
xCoord += chunkWidth;
bitmapChunk.recycle();
bitmapChunk = null;
}
yCoord += chunkHeight;
}
return imageBytes;
}
private byte[] getBytesFromBitmapChunk(Bitmap bitmap)
{
int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapSize);
bitmap.copyPixelsToBuffer(byteBuffer);
byteBuffer.rewind();
return byteBuffer.array();
}
'e.printStackTrace()' result
at com.example.leehanbeen.platerecognize.ActivityInference.hypothesis(ActivityInference.java:58)
at com.example.leehanbeen.platerecognize.MainActivity.activityPrediction(MainActivity.java:148)
at com.example.leehanbeen.platerecognize.MainActivity.access$100(MainActivity.java:28)
at com.example.leehanbeen.platerecognize.MainActivity$2.onClick(MainActivity.java:69)
around MainActivity.java:69
byte[] byteArrayRes = bitmapToByteArray(image_bitmap);
float[] inputArray = bytetofloat(byteArrayRes);
activityPrediction(inputArray);
MainActivity.java:28
public class MainActivity extends AppCompatActivity {
MainActivity.java:148
float[] result = activityInference.hypothesis(inputArray, 20*36, 10, getApplicationContext());
around ActivityInference.java:58
float[] result = new float[nInstance * nClasses];
inferenceInterface.fetch(OUTPUT_NODE_HYPO, result);
I have to create an android app for image registration. I have created a 2D array for each image after cropping images and i made an fft using jtrasform, then i tryed to create a cross correlation matrix. serching in this matrix for the max value coordinates i expected to have the X e Y values for shifting my image but this values are wrong and i can't find the error.
public void Registration(Bitmap image,Bitmap image2) {
int square,x,y;
int Min2,Min1,Min;
Min1=min(image.getHeight(),image2.getHeight());
Min2=min(image.getWidth(),image2.getWidth());
if(Min1<Min2)
Min=Min1;
else
Min=Min2;
if (Min>1024)
square =1024;
else{
if (Min>512)
square =512;
else{
if (Min<256)
square=128;
else
square=256;
}}
Bitmap crop=Bitmap.createBitmap(image, 0,0,square, square);
Bitmap crop2=Bitmap.createBitmap(image2, 0,0,square, square);*/
float[][] array = new float[square-1][square-1];
float[][] array2 = new float[square-1][square-1];
float[][] array3 = new float[square-1][square-1];
for (x = 0; x < square-1; x++) {
int p = crop.getPixel(x,x);
int p1=crop2.getPixel(x,x);
array[x][x] = (Color.red(p) + Color.green(p) + Color.blue(p)) / 3;
array2[x][x] = (Color.red(p1) + Color.green(p1) + Color.blue(p1)) / 3;
}
for (y = square-1; y < (2*square)-1; y++) {
for (x = 0; x < square-1; x++){
array[x][y] = 0;
array2[x][y] = 0;
}}
FloatFFT_2D a = new FloatFFT_2D(square,square);
FloatFFT_2D b = new FloatFFT_2D(square,square);
a.complexForward(array);
b.complexForward(array2);
for (y = 0; y < (2*square)-1; y++) {
for (x = 0; x < square-1; x++){
if(y>=square){
array2[x][y] =-array2[x][y];}
array3[x][y]=array[x][y]*array2[x][y];}}
FloatFFT_2D c = new FloatFFT_2D(square-1,square-1);
c.complexInverse(array3,false);
Max(array3,(square),(2*square));
I'm looking for some help in applying 2D Gabor Wavelets Formula to an image in java.
This is the formula that I'm using.
Gabor Formula
I need my output to look like this
I've read the image in and its currently stored in a 2D array. My code is as follows:` public void RunGabor() throws IOException
{
double[][]pixels=getImage();
int H= pixels.length;
int W =pixels[0].length;
size=H*W;
gaussian=size/2;
System.out.println(gaussian);
GaborGrid = new int[H][W];
GaborNorm = new int[H][W];
double X=0,Y=0, gx=-gaussian,gy=-gaussian, count=0, total=0;
int ax=0, dy=0;
for(int x=0; x<pixels.length; x++)
{
for(int k=0;k< pixels[0].length; k++)
{
X=gx*Math.cos(theta)+gy*Math.sin(theta);
Y=-gx*Math.sin(theta)+gy*Math.cos(theta);
pixels[dy][ax]=((Math.exp(-(Math.pow(X, 2)+(Math.pow(Y, 2)*
Math.pow(upsi,2)))/(2*Math.pow(sigma, 2))))*
(Math.cos((kappa*X+varphi))));
System.out.println("Pixels" +pixels[dy][ax]);
total+=pixels[dy][ax];
count++;
System.out.println("Count" +count);
gx+=1;
ax++;
}
System.out.println("second loop");
ax=0;
dy++;
gy+=1;
gx=-gaussian;
}
mean=total/count;
System.out.println("Mean" +mean);
NormaliseImage(pixels);
}`
From there it calls a method normaliseImage
public void NormaliseImage(double[][] pixels)
{
double minII = pixels[0][0];
double maxII = pixels[0][0];
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
if(pixels[y][x] <= minII){
minII =pixels[y][x];
}
if(pixels[y][x]>= maxII){
maxII=pixels[y][x];
}
}
My create image class looks like this
public CreateImage(int[][] data, String IMGname)
{
name = IMGname;
width = data[0].length;
height = data.length;
System.out.println("NEW IMAGE 1");
pixels = new int[height*width];
int count=0;
for(int i=0; i<data.length; i++)
{
for(int j=0; j<data[0].length; j++)
{
pixels[count] = (int)Math.abs(data[i][j]);
pixels[count] = convert2pixel(pixels[count]);
count++;
}
}
Create(width, height, pixels, name);
}
public int convert2pixel(int pixel)
{
return ((0xff<<24)|(pixel<<16)|(pixel<<8)|pixel);
}
public int convert2grey(double pixel)
{
int red=((int)pixel>>16) & 0xff;
int green = ((int)pixel>>8) & 0xff;
int blue = (int)pixel & 0xff;
return (int)(0.3*red+0.6*green+0.1*blue);
}
public void Create(int Width, int Height, int pixels[], String n)//throws Exception
{
//System.out.println("Inside Create Image");
MemoryImageSource MemImg = new MemoryImageSource(Width,Height,pixels,0,Width);
Image img2= Toolkit.getDefaultToolkit().createImage(MemImg);
BufferedImage bfi = new BufferedImage(Height,Width, BufferedImage.TYPE_INT_BGR);
Graphics2D g2D = bfi.createGraphics();
g2D.drawImage(img2, 0, 0, Width, Height, null);
try
{
ImageIO.write(bfi, "png", new File(n+".png"));
}
catch(Exception e){}
}
}
My output is just a grey screen, any help would be appreciated.
Update: Gabor Driver Class `
public class Gabor_Driver{
public static void main(String[]args)throws IOException
{
double lamda=75;
double theta=45;
double varphi=90;
double upsi=10;
double bandW=10;
//int size=500;
Gabor gabor = new Gabor(lamda, theta, varphi, upsi, bandW );
}
}
`
Gabor class :
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class Gabor
{
CreateImage ci;
private double lamda=0;
private double theta=0;
private double varphi=0;
private double upsi=0;
private double bandW=0;
private double B=0;
private double sigma=0;
private double kappa=0;
private int[][] GaborGrid;
private int[][] GaborNorm;
int size=0;
double toRadians=180/Math.PI, min=500, max=-500, mean=0;;
int gaussian=0;
double rotation;
double GLFmean=0;
//Standard Gabor no quantization
public Gabor(double l, double t, double v, double u, double b) throws IOException
{
lamda=l;
theta=t/toRadians;
varphi=v/toRadians;
upsi=u;
bandW=b;
kappa=(2*Math.PI)/lamda;
Calculate_Sigma();
RunGabor();
}
public void RunGabor() throws IOException
{
double[][]pixels=getImage();
int H= pixels.length;
int W =pixels[0].length;
size=H*W;
gaussian=size/2;
System.out.println(gaussian);
GaborGrid = new int[H][W];
GaborNorm = new int[H][W];
double X=0,Y=0, gx=-gaussian,gy=-gaussian, count=0, total=0;
int ax=0, dy=0;
for(int x=0; x<pixels.length; x++)
{
for(int k=0;k< pixels[0].length; k++)
{
X=gx*Math.cos(theta)+gy*Math.sin(theta);
Y=-gx*Math.sin(theta)+gy*Math.cos(theta);
pixels[dy][ax]=((Math.exp(-(Math.pow(X, 2)+(Math.pow(Y, 2)*
Math.pow(upsi,2)))/(2*Math.pow(sigma, 2))))*
(Math.cos((kappa*X+varphi))));
System.out.println("Pixels" +pixels[dy][ax]);
total+=pixels[dy][ax];
count++;
System.out.println("Count" +count);
gx+=1;
ax++;
}
System.out.println("second loop");
ax=0;
dy++;
gy+=1;
gx=-gaussian;
}
mean=total/count;
System.out.println("Mean" +mean);
NormaliseImage(pixels);
}
public double[][] getImage() throws IOException{
int[][]pixels =null;
double[][] doubles = null;
JFileChooser fc = new JFileChooser();
int returnValue = fc.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
BufferedImage image = ImageIO.read(selectedFile);
System.out.println(selectedFile.getName());
int W =image.getWidth();
int H= image.getHeight();
int width = image.getWidth();
int height = image.getHeight();
pixels = new int[height][width];
for (int row = 0; row < height; row++) {
image.getRGB(0, row, width, 1, pixels[row], 0, width);
}
doubles = new double[pixels.length][pixels[0].length];
for(int i=0; i<pixels.length; i++) {
for(int j=0; j<pixels[0].length; j++)
doubles[i][j] = pixels[+i][+j];
}
}
return doubles;
}
public void NormaliseImage(double[][] pixels)
{
double minII = pixels[0][0];
double maxII = pixels[0][0];
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
if(pixels[y][x] <= minII){
minII =pixels[y][x];
}
if(pixels[y][x]>= maxII){
maxII=pixels[y][x];
}
}
}
int count=0;
double total=0;
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
total += pixels[y][x];
count++;
}
}
double average =(double)total/count;
for(int y=0; y<pixels.length; y++){
for(int x= 0; x<pixels[0].length; x++){
double normalise= ((((pixels[y][x]-min))/((max-min)))*255);
if(normalise<=average){
normalise =0;
}
GaborNorm[y][x] = (int) normalise;
}
}
ci = new CreateImage(GaborNorm, "Gabor");
}
private void Calculate_Sigma()
{
B=(1/Math.PI)*(0.588705011)*((Math.pow(2, bandW)+1)/(Math.pow(2, bandW)-1));
sigma=B*lamda;
}
}
Create image class:
import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
public class CreateImage
{
int[] pixels;
int width=0, height=0;
String name;
public CreateImage(int[][] data, String IMGname)
{
name = IMGname;
width = data[0].length;
height = data.length;
System.out.println("NEW IMAGE 1");
pixels = new int[height*width];
int count=0;
for(int i=0; i<data.length; i++)
{
for(int j=0; j<data[0].length; j++)
{
pixels[count] = (int)Math.abs(data[i][j]);
pixels[count] = convert2pixel(pixels[count]);
count++;
}
}
Create(width, height, pixels, name);
}
public int convert2pixel(int pixel)
{
return ((0xff<<24)|(pixel<<16)|(pixel<<8)|pixel);
}
public int convert2grey(double pixel)
{
int red=((int)pixel>>16) & 0xff;
int green = ((int)pixel>>8) & 0xff;
int blue = (int)pixel & 0xff;
return (int)(0.3*red+0.6*green+0.1*blue);
}
public void Create(int Width, int Height, int pixels[], String n)//throws Exception
{
//System.out.println("Inside Create Image");
MemoryImageSource MemImg = new MemoryImageSource(Width,Height,pixels,0,Width);
Image img2= Toolkit.getDefaultToolkit().createImage(MemImg);
BufferedImage bfi = new BufferedImage(Height,Width, BufferedImage.TYPE_INT_BGR);
Graphics2D g2D = bfi.createGraphics();
g2D.drawImage(img2, 0, 0, Width, Height, null);
try
{
ImageIO.write(bfi, "png", new File(n+".png"));
}
catch(Exception e){}
}
}
Your calculations are mostly correct. You are calculating the function itself in RunGabor - I think gx, gy should be replaced with x, k. This
for(int x=0; x<pixels.length; x++)
{
for(int k=0;k< pixels[0].length; k++)
{
X=gx*Math.cos(theta)+gy*Math.sin(theta);
Y=-gx*Math.sin(theta)+gy*Math.cos(theta);
pixels[dy][ax]=((Math.exp(-(Math.pow(X, 2)+(Math.pow(Y, 2)*
Math.pow(upsi,2)))/(2*Math.pow(sigma, 2))))*
(Math.cos((kappa*X+varphi))));
should be replaced with
public Kernel getKernel() {
double sigma = calculateSigma(waveLength, bandwidth);
float[] data = new float[width*height];
for(int k = 0, x = -width/2; x <= width/2; x++) {
for(int y = -height/2; y <= height/2; y++) {
for(double orientation : orientations) {
double x1 = x*Math.cos(orientation) + y*Math.sin(orientation);
double y1 = -x*Math.sin(orientation) + y*Math.cos(orientation);
data[k] += (float)(gaborFunction(x1, y1, sigma, aspectRatio, waveLength, phaseOffset));
}
k++;
}
}
But you have to apply the function on the pixels that you are reading, the image. If you look at this other implementation https://github.com/clumsy/gabor-filter/blob/master/src/main/java/GaborFilter.java
you will find many parallels. See if you can fix it.
At least as a first step you should try to print the values of the gabor function either 3x3 or 5x5. If they look reasonable you can go ahead to apply it to the image.
I'm writing an application to hide animage in another image using LSB. The encoding returns an image that differs from the image that was hidden and after searching the problem for quite some time now, i think i became seriously blind, when it comes to my code.
If somebody could take a look and give me a hint, I would be very thankful. The significant code below and the whole project (if somebody would want to test it) under the link: https://github.com/miassma/Steganography.git
public class SteganographyOperationsUtil {
/*checking if the image to hide can fit the hiding image
it returns the range of shades of gray that can be kept in the hiding image*/
public static int checkImages(ImageModel hiding, ImageModel toHide, ImageModel copyOfToHide){
int hidingSize = hiding.getWidth() * hiding.getHeight();
int toHideSize = toHide.getWidth() * toHide.getHeight();
int header = 40;
int value = 8;
while((toHideSize * value + header) > hidingSize){ //if doesnt fit, reducing one range, checking again
value--;
if(value==0){
break;
}
}
if(value == 0) return -1;
if(value<8) posterize(copyOfToHide, (int)pow(2, value)); //run the posterisation if needed
return (int)pow(2, value);
}
/* preparing the hiding image
we need zero on each LSB
*/
public static void prepareHidingImage(ImageModel imgModel){
for (int x = 0; x < imgModel.getWidth(); ++x) {
for (int y = 0; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
int temp = 254;
int newColor = color & temp;
int[] newColorPixel = {newColor};
imgModel.getImage().getRaster().setPixel(x, y, newColorPixel);
}
}
imgModel.imageChanged();
}
//fullfill by leading zeros with the lenght of the option
public static String fillString(String toFill, int option){
String zero = "0";
if (toFill.length() < option){
int temp = option - toFill.length();
do{
toFill = zero.concat(toFill);
}while(--temp >0);
}
return toFill;
}
/* fullfill the string to get the color matching the posterisation range
for example 1 will be 11111111 (2 ranges of gray)
101 will become 10110110 (3 ranges of gray)
1011 will become 10111011 (4 ranges of gray)
*/
public static String complete(String toComplete){
while (toComplete.length() < 9){
toComplete = toComplete+toComplete;
}
toComplete = toComplete.substring(0, 8);
return toComplete;
}
//hiding Image
public static void hidingOperation(ImageModel hiding, ImageModel toHide, int value){
prepareHidingImage(hiding);
String posterisation = Integer.toString(value-1, 2);
String hiddenWidth = Integer.toString(toHide.getWidth(), 2);
String hiddenHeight = Integer.toString(toHide.getHeight(), 2);
hiddenWidth = fillString(hiddenWidth, 16);
hiddenHeight = fillString(hiddenHeight, 16);
posterisation = fillString(posterisation, 8);
String header = hiddenWidth;
header = header.concat(hiddenHeight);
header = header.concat(posterisation);
int newColor;
int temp = 0;
int temp2 = 0;
int bitsToCheck = (int)logb(value, 2); //how many bits of each pixel we have to hide for given postarisation
int zero = 0;
int one = 1;
int i = 0;
int j = 0;
String colorOfToHideBinary = "";
outerLoop:
for (int x = 0; x < hiding.getWidth(); ++x) {
for (int y = 0; y < hiding.getHeight(); ++y) {
int color = hiding.getImage().getRaster().getPixel(x, y, new int[1])[0];
//filling header
if(temp < header.length()){
if(header.charAt(temp)== '0'){
newColor = color | zero;
}else{ newColor = color | one;
}temp++;
//hiding image
}else{
/*
getting the value of the next pixel of the image to hide, only if temp ==0,
what means that it is the first pixel or each needed bits by the posterisation range
has been already checked
*/
if(temp2 == 0){
int colorOfToHide = toHide.getImage().getRaster().getPixel(i, j, new int[1]) [0];
colorOfToHideBinary = Integer.toString(colorOfToHide, 2);
colorOfToHideBinary = fillString(colorOfToHideBinary, 8);
}
//i check each value of the color in binary, but only as much as needed by the posterisation range
if (colorOfToHideBinary.charAt(temp2) == '0'){
newColor = color | zero;
}else { newColor = color | one;}
temp2++;
if (temp2 == bitsToCheck){
temp2 = 0;
j++;
if(j == toHide.getHeight()){
j = 0;
i++;
}
}
}
int[] newColorPixel = {newColor};
hiding.getImage().getRaster().setPixel(x, y, newColorPixel);
if(i == toHide.getWidth()){
break outerLoop;
}
}
}
hiding.imageChanged();
}
//decrypting image
public static ImageModel encodingOperation(ImageModel imgModel){
int i = 0;
int j = 0;
String widthB = "";
String heightB = "";
String posterisationB = "";
int temp = 0;
int one = 1;
/* loop for taking values from the header, seems to work pretty fine */
outerLoop:
for (int x = 0; x < imgModel.getWidth(); ++x) {
for (int y = 0; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
if(temp<16){
if ((color & one) == one) widthB = widthB.concat("1");
else widthB = widthB.concat("0");
}else if(temp < 32){
if ((color & one) == one) heightB = heightB.concat("1");
else heightB = heightB.concat("0");
}else if(temp <40){
if ((color & one) == one) posterisationB = posterisationB.concat("1");
else posterisationB = posterisationB.concat("0");
}else{
break outerLoop;
}temp++; j++;
}i++;
}
int width = Integer.parseInt(widthB, 2);
int height = Integer.parseInt(heightB, 2);
int posterisation = Integer.parseInt(posterisationB, 2);
int bitsToCheck = (int)logb(posterisation+1, 2);
int temp2 = 0;
String colorInBinary = "";
//preparing the canvas for the encoded image, width and height from the header
ImageModel encryptedImage = ImageModel.fromHidden(width, height);
int a = 0;
int b = 0;
/* encoding the image
starting after the point after the header, saved in the variables i,j
*/
outerLoop:
for (int x = i; x < imgModel.getWidth(); ++x) {
for (int y = j; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
/* pixel by pixel reading color of the hidden image
temp2 checks, where to stop - how many LSB of the hiding image keeps information bout one pixel of the hidden img
*/
if ((color & one) == one) colorInBinary = colorInBinary.concat("1");
else colorInBinary= colorInBinary.concat("0");
temp2++;
if (temp2 == bitsToCheck){
temp2 = 0;
//fullfilling the color to the right by the given posterisation range
colorInBinary = complete(colorInBinary);
int newColor = Integer.parseInt(colorInBinary, 2);
colorInBinary = "";
int[] newColorPixel = {newColor};
encryptedImage.getImage().getRaster().setPixel(a, b, newColorPixel);
b++;
if(b == height){
a++;
b=0;
}if (a == width){
break outerLoop;
}
}
}
}
return encryptedImage;
}
public static double logb( double a, double b ){
return Math.log(a) / Math.log(b);
}
public static void posterize(ImageModel imgModel, int value) {
int[] lut = new int[256];
float param1 = 255.0f / (value - 1);
float param2 = 256.0f / (value);
for (int i = 0; i < 256; ++i) {
lut[i] = (int)((int)(i / param2) * param1);
}
useLUT(imgModel, lut);
}
public static void useLUT(ImageModel imgModel, int[] lut) {
for (int x = 0; x < imgModel.getWidth(); ++x) {
for (int y = 0; y < imgModel.getHeight(); ++y) {
int color = imgModel.getImage().getRaster().getPixel(x, y, new int[1])[0];
int[] newColorPixel = {lut[color]};
imgModel.getImage().getRaster().setPixel(x, y, newColorPixel);
}
}
imgModel.imageChanged();
}
I'm creating an Image filter program and I want to convert a coloured picture to a grayscale picture with the help of an array matrix.
This is what I have currently:
import java.awt.Color;
import se.lth.cs.ptdc.images.ImageFilter;
public class GrayScaleFilter extends ImageFilter {
public GrayScaleFilter(String name){
super(name);
}
public Color[][] apply(Color[][] inPixels, double paramValue){
int height = inPixels.length;
int width = inPixels[0].length;
Color[][] outPixels = new Color[height][width];
for (int i = 0; i < 256; i++) {
grayLevels[i] = new Color(i, i, i);
}
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
Color pixel = inPixels[i][j];
outPixels[i][j] = grayLevels[index];
}
}
return outPixels;
}
}
It looks like I'm supposed to use this formula: ((R+G+B)/3)
I want to create an array matrix like this:
Color[] grayLevels = new Color[256];
// creates the color (0,0,0) and puts it in grayLevels[0],
// (1,1,1) in grayLevels[1], ..., (255,255,255) in grayLevels[255]
This is the class I'm refering too when I want to use grascale:
public abstract Color[][] apply(Color[][] inPixels, double paramValue);
protected short[][] computeIntensity(Color[][] pixels) {
int height = pixels.length;
int width = pixels[0].length;
short[][] intensity = new short[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
Color c = pixels[i][j];
intensity[i][j] = (short) ((c.getRed() + c.getGreen() + c
.getBlue()) / 3);
}
}
return intensity;
}
Any feedback on how I can achieve this? Instead of using outPixels[i][j] = new Color(intensity, intensity, intensity);
Build the grayLevels array this way:
for (int i = 0; i < 256; i++) {
grayLevels[i] = new Color(i, i, i);
}
Then, when you need a certain color, just retrieve it as grayLevels[index].