Convert Image to Grayscale with array matrix RGB java - java

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].

Related

Transformation of photo to photo in the form of matrix

I wrote the following code, but the photographs must be in the form of a matrix, not side by side.
My goal is not to leave any empty space at the end of the canvas.
import java.awt.Color;
public class aaa {
public static Color karstr ( Color x,Color y,double lambda ){
int r= (int)((1-lambda)*x.getRed()+lambda*y.getRed());
int g= (int)((1-lambda)*x.getGreen()+lambda*y.getGreen());
int b= (int)((1-lambda)*x.getBlue()+lambda*y.getBlue());
return new Color (r,g,b);
}
public static void main(String[] args) {
int genilik =50;
int ykseklik=100;
Picture p=new Picture("c:/data/a.jpg");
Picture q=new Picture("c:/data/b.jpg");
Picture r= new Picture(p.width()+400,p.height()+10);
for (int i = 0; i < p.width(); i++)
for (int j = 0; j < p.height(); j++) {
Color x=p.get(i, j);
Color y=q.get(i,j);
r.set(i*genilik/p.width(),j*ykseklik/p.height(), x);
Color c=karstr(x,y,(double)1/5);
r.set(i*genilik/p.width()+50,j*ykseklik/p.height(), c);
Color a=karstr(x,y,(double)1/4);
r.set(i*genilik/p.width()+100,j*ykseklik/p.height(),a);
Color b=karstr(x,y,(double)1/3);
r.set(i*genilik/p.width()+150,j*ykseklik/p.height(),b);
Color f=karstr(x,y,(double)1/2);
r.set(i*genilik/p.width()+200,j*ykseklik/p.height(),f);
Color g=karstr(x,y,(double)1/1.2);
r.set(i*genilik/p.width()+250,j*ykseklik/p.height(),g);
r.set(i*genilik/p.width()+300,j*ykseklik/p.height(), y);
}
r.show();
}
}
import java.awt.Color;
public class PhotoTransformation {
private Picture source;
private Picture dest;
public PhotoTransformation(Picture source, Picture dest) {
source = source;
dest = dest;
}
public static void main(String[] args) {
Picture p=new Picture("c:/data/a.jpg");
Picture q=new Picture("c:/data/b.jpg");
PhotoTransformation photoTransformation = new PhotoTransformation(p, q);
Picture[] photoSeries = photoTransformation.produceTransformationPhotos(8);
// Show the photos
}
public Picture[] produceTransformationPhotos(int transitionPhotoNumber) {
int photoNumber = transitionPhotoNumber + 2;
Picture[] photos = new Picture[photoNumber];
int width = source.width();
int height = source.height();
for (int p = 0; p < photoNumber; p++) {
Picture newPhoto = new Picture(width, height);
photos[p] = newPhoto;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
Color sourceColor = source.get(i, j);
Color destColor = dest.get(i, j);
double weight = (double) p / (double) (photoNumber - 1);
Color transformationColor = produceWeightedMeanColor(sourceColor, destColor, weight);
newPhoto.set(i, j, transformationColor);
}
}
}
return photos;
}
private static Color produceWeightedMeanColor(Color x, Color y, double weight) {
int r = (int)((1-weight) * x.getRed() + weight * y.getRed());
int g = (int)((1-weight) * x.getGreen() + weight * y.getGreen());
int b = (int)((1-weight) * x.getBlue() + weight * y.getBlue());
return new Color(r,g,b);
}
}

Edit 2D array instance variable size without Array List (image manipulation)

I need to edit the original instance variable private in[][] pixels; to be twice the width, I've done the algorithm to mirror the image and make a new array twice as wide I just don't know how to set the original int[][] pixels to it. The pixels array has to be the one modified, it can't go by another name.
private int[][] pixels;
...
if(transformationName == "Mirror"){
int[][] mirrorTemp = new int[height][width*2];
for(int h = 0; h < height; h++){
for(int w = 0; w < width; w++){
mirrorTemp[h][w] = pixels[h][w];
mirrorTemp[h][w + width] = pixels[h][width - h - 1];
}
}
int[][] pixels = new int[height][width*2];
for(int h = 0; h < height; h++){
for(int w = 0; w < (width*2); w++){
pixels[h][w] = mirrorTemp[h][w];
}
}
}
First, I believe the following is what you intended to do.
for(int h = 0; h < height; h++){
for(int w = 0; w < width; w++){
mirrorTemp[h][w] = pixels[h][w];
mirrorTemp[h][w + width] = pixels[h][width - w];
}
}
After this, you can simply
pixels = mirrorTemp;
since the two are both int[][] type.
Hope this helps.

Gabor Image Processing in Java without MathLab

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.

Java Bufferedimage setRgb getRgb, 2 different results

i´m trying to convert a image into a matrix and convert it back, but the 2 pictures are different:
convert it into a matrix:
public int[][] getMatrixOfImage(BufferedImage bufferedImage) {
int width = bufferedImage.getWidth(null);
int height = bufferedImage.getHeight(null);
int[][] pixels = new int[width][height];
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
pixels[i][j] = bufferedImage.getRGB(i, j);
}
}
return pixels;
}
and convert it back into a bufferedImage:
public BufferedImage matrixToBufferedImage(int[][] matrix) {
int width=matrix[0].length;
int height=matrix.length;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
int pixel=matrix[i][j] <<24|matrix[i][j] <<16|matrix[i][j]<<8|matrix[i][j] ;
bufferedImage.setRGB(i, j, pixel);
}
}
return bufferedImage;
}
with this result:
http://img59.imageshack.us/img59/5464/mt8a.png
Thanks!
Why do you do
int pixel=matrix[i][j] <<24|matrix[i][j] <<16|matrix[i][j]<<8|matrix[i][j];
instead of just
int pixel=matrix[i][j];
?

Java mirror image diagonal method not working

I'm having trouble getting my method to work. The method should mirror any image I choose on its diagonal to produce a mirror effect, but at the moment it just produces the same image unedited and I don't what I'm doing wrong. Any help would be greatly appreciated. Thank you.
public Picture mirrorImageDiagonal() {
int size = this.getWidth();
Pixel rightPixel = null;
Pixel leftTargetPixel = null;
Pixel rightTargetPixel = null;
Picture target = new Picture(size, size);
for (double x = 0; x < size; x ++) {
for (double y = 0; y <= x; y ++) {
int yIndex = Math.min((int) y, this.getHeight() - 1);
int xIndex = Math.min((int) x, this.getWidth() - 1);
leftTargetPixel = target.getPixel(yIndex, xIndex);
rightTargetPixel = target.getPixel(xIndex, yIndex);
rightPixel = this.getPixel(xIndex, yIndex);
rightTargetPixel.setColor(rightPixel.getColor());
leftTargetPixel.setColor(rightPixel.getColor());
}
}
return target;
}
I am assuming that you are trying to complete the challenge for A6 in the picture lab packet. I just completed this for school, but if you are not, I hope this still helps you.
public void mirrorDiagonal()
{
Pixel[][] pixels = this.getPixels2D();
Pixel pixel1 = null;
Pixel pixel2 = null;
int width = pixels[0].length;
for (int row = 0; row < pixels.length; row++)
{
for (int col = 0; col < width; col++)
{
if (col < pixels.length)
{
pixel1 = pixels[row][col];
pixel2 = pixels[col][row];
pixel1.setColor(pixel2.getColor());
}
}
}
}

Categories

Resources