java image processing sobel edge detection - java

I have a problem with java program, in which i'm using sobel operator for edge detection, but when I'm trying to use that funcion, console says:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 262144
at sun.awt.image.ByteInterleavedRaster.getPixels(ByteInterleavedRaster.java:1015)
at Obrazek.jButtonSobelActionPerformed(Obrazek.java:566)
And the code for that is:
FileInputStream inFile = null;
try {
long beginTime = (new java.util.Date()).getTime();
int i, j;
double Gx[][], Gy[][], G[][];
inFile = new FileInputStream("D://lenacsmall.bmp");
BufferedImage bi = ImageIO.read(inFile);
int width = bi.getWidth();
int height = bi.getHeight();
int[] pixels = new int[width * height];
int[][] output = new int[width][height];
int[] raster = bi.getRaster().getPixels(0,0,width,height,pixels);
int counter = 0;
for(i = 0 ; i < width ; i++ )
{
for(j = 0 ; j < height ; j++ )
{
output[i][j] = pixels[counter];
counter = counter + 1;
}
}
Gx = new double[width][height];
Gy = new double[width][height];
G = new double[width][height];
for (i=0; i<width; i++) {
for (j=0; j<height; j++) {
if (i==0 || i==width-1 || j==0 || j==height-1)
Gx[i][j] = Gy[i][j] = G[i][j] = 0;
else{
Gx[i][j] = output[i+1][j-1] + 2*output[i+1][j] + output[i+1][j+1] -
output[i-1][j-1] - 2*output[i-1][j] - output[i-1][j+1];
Gy[i][j] = output[i-1][j+1] + 2*output[i][j+1] + output[i+1][j+1] -
output[i-1][j-1] - 2*output[i][j-1] - output[i+1][j-1];
G[i][j] = Math.abs(Gx[i][j]) + Math.abs(Gy[i][j]);
}
}
}
counter = 0;
for(int ii = 0 ; ii < width ; ii++ )
{
for(int jj = 0 ; jj < height ; jj++ )
{
pixels[counter] = (int) G[ii][jj];
counter = counter + 1;
}
}
BufferedImage outImg = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
outImg.getRaster().setPixels(0,0,width,height,pixels);
FileOutputStream outFile = null;
try {
outFile = new FileOutputStream("D://copyTop.bmp");
} catch (FileNotFoundException ex) {
}
try {
ImageIO.write(outImg,"BMP",outFile);
} catch (IOException ex) {
}
JFrame TheFrame = new JFrame("obrazek " + width + " " + height);
JLabel TheLabel = new JLabel(new ImageIcon(outImg));
TheFrame.getContentPane().add(TheLabel);
TheFrame.setSize(600, 600);
TheFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
TheFrame.setVisible(true);
} catch (FileNotFoundException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
inFile.close();
} catch (IOException ex) {
Logger.getLogger(Obrazek.class.getName()).log(Level.SEVERE, null, ex);
}
}
I'm really need some help. I hope someone will answer for that post, thank you.
Greetings :)

Try this, edge detection using sobel approach, I just did this yesterday.
`
static BufferedImage inputImg,outputImg;
static int[][] pixelMatrix=new int[3][3];
public static void main(String[] args) {
try {
inputImg=ImageIO.read(new File("your input image"));
outputImg=new BufferedImage(inputImg.getWidth(),inputImg.getHeight(),TYPE_INT_RGB);
for(int i=1;i<inputImg.getWidth()-1;i++){
for(int j=1;j<inputImg.getHeight()-1;j++){
pixelMatrix[0][0]=new Color(inputImg.getRGB(i-1,j-1)).getRed();
pixelMatrix[0][1]=new Color(inputImg.getRGB(i-1,j)).getRed();
pixelMatrix[0][2]=new Color(inputImg.getRGB(i-1,j+1)).getRed();
pixelMatrix[1][0]=new Color(inputImg.getRGB(i,j-1)).getRed();
pixelMatrix[1][2]=new Color(inputImg.getRGB(i,j+1)).getRed();
pixelMatrix[2][0]=new Color(inputImg.getRGB(i+1,j-1)).getRed();
pixelMatrix[2][1]=new Color(inputImg.getRGB(i+1,j)).getRed();
pixelMatrix[2][2]=new Color(inputImg.getRGB(i+1,j+1)).getRed();
int edge=(int) convolution(pixelMatrix);
outputImg.setRGB(i,j,(edge<<16 | edge<<8 | edge));
}
}
File outputfile = new File("your output image");
ImageIO.write(outputImg,"jpg", outputfile);
} catch (IOException ex) {System.err.println("Image width:height="+inputImg.getWidth()+":"+inputImg.getHeight());}
}
public static double convolution(int[][] pixelMatrix){
int gy=(pixelMatrix[0][0]*-1)+(pixelMatrix[0][1]*-2)+(pixelMatrix[0][2]*-1)+(pixelMatrix[2][0])+(pixelMatrix[2][1]*2)+(pixelMatrix[2][2]*1);
int gx=(pixelMatrix[0][0])+(pixelMatrix[0][2]*-1)+(pixelMatrix[1][0]*2)+(pixelMatrix[1][2]*-2)+(pixelMatrix[2][0])+(pixelMatrix[2][2]*-1);
return Math.sqrt(Math.pow(gy,2)+Math.pow(gx,2));
}
`

In your for loops when you check
if (i==0 || i==width-1 || j==0 || j==height-1)
you should probably be checking for i >= width-2 rather than i==width-1.
For example, if width is 10 it falls into the statement if i == 9.
you want to catch if i == 8 since you later check [i+1], which in your code would be out of the bounds of your image array, since the maximum you can have is 9 (width-1).
Obviously the same applies for j.

Related

KeyListener Supposedly Calling upon other Key's code (JDBC)

I have a system so that you can press space to pause the simulation, and then arrows move the camera etc. and then if you press e, a JFrame pops up with a JTable inside it with the results from a SQL search of a connected database.
This works fine, I can close the JFrame and carry on running the simulation as usual, all the buttons and functions work.
The problem is after 20 seconds, the system takes the collected data and writes this data to the end of the database, which is fine, that works it writes to the end if the data is not already their. However if I press e to open the table, and then close the table, when returning to the simulation screen whatever button I press that has a listener attached to it, will just keep opening new tables, and I am stumped as to the reason why.
Any solution that would allow for when I close this JFrame for my key's to begin to function the way they did before writing to the file, would be greatly appreciated.
Here are the relevant pieces of code (let me know if there is any more you may need)
public void databaseConnector(boolean read){
try{
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/Outputs", "Sam", "sam");
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "SELECT INDEX FROM SHM";
ResultSet rs = st.executeQuery(sql);
int len = 0;
while(rs.next()) {
len++;
}
if (read){
databaseReader(st, len);
} else {
double data[] = {modulus[0] , natural[0], modulus[1], natural[1], length, startPosition, endPosition, amplitude, equilibrium};
for (int i = 4; i < data.length; i++){
data[i] /= 100;
}
PreparedStatement sqls = con.prepareStatement( "SELECT * FROM SHM WHERE " + columnNames[1] + " = " + data[0] + " AND " + columnNames[2] + " = " + data[1] + " AND "
+ columnNames[3] + " = " + data[2] + " AND " + columnNames[4] + " = " + data[3] + " AND "
+ columnNames[5] + " = " + data[4] + " AND " + columnNames[6] + " = " + data[5]);
databaseWriter(st, len, sqls, data);
}
st.close();
con.close();
} catch (Exception e){
e.printStackTrace();
}
}
public void databaseReader(Statement st, int len){
try{
Object[][] data;
//Get data from table and convert to 2D array
data = new Object[len][columnNames.length];
String sql = "SELECT * FROM SHM";
ResultSet rs = st.executeQuery(sql);
int x = 0;
while (rs.next()){
for(int i = 0; i < columnNames.length; i++){
data[x][i] = new Double(rs.getDouble(columnNames[i]));
}
x++;
}
rs.close();
//Output data
JFrame frame = new JFrame("Table");
TableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.setAlwaysOnTop(true);
frame.pack();
frame.setVisible(true);
} catch (Exception e){
System.err.println(e.getMessage());
}
}
public void databaseWriter(Statement st, int len, PreparedStatement sql, double[] data){
try{
//checker
ResultSet rs = sql.executeQuery();
if (!rs.next()){ //if not empty then
rs = st.executeQuery("SELECT * FROM SHM");
rs.moveToInsertRow();
rs.updateInt(columnNames[0],len + 1);
for (int i = 0; i < data.length; i++) {
rs.updateDouble(columnNames[i+1],data[i]);
}
rs.insertRow();
}
rs.close();
} catch (Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
public void gravity(){
if (moving){
double force = tension();
Player.ha = force / Player.mass;
Player.hSpeed += Player.ha * delta / 60;
//}
Player.vSpeed += Player.va;
Player.move(1, (int) (Player.hSpeed * delta));
if (milliSecondTimer < 20){
calculationChecker();
}
if (milliSecondTimer > 20 && !hasWritten){
endPosition = (int) (maxX - rect.get(0).getMaxX());
databaseConnector(false);
hasWritten = true;
}
} else {
milliSecondTimer = 0;
hasWritten = false;
amplitude = 0;
equilibrium = 0;
MaxX = new ArrayList<Integer>();
MinX = new ArrayList<Integer>();
Equilibrium = new ArrayList<Integer>();
Player.hSpeed = 0;
Player.ha = 0;
}
}
public class MyKeyListener implements KeyListener{
public void action(){
int s = 4;
if (keysDown.contains(KeyEvent.VK_SHIFT)){
s = 10;
} else {
s = 4;
}
if (keysDown.contains(KeyEvent.VK_UP) /*|| keysDown.contains(KeyEvent.VK_W)*/){
scaleChange = true;
moverY += 10;
}
if (keysDown.contains(KeyEvent.VK_RIGHT) /*|| keysDown.contains(KeyEvent.VK_D)*/){
if (!moving) {
Player.move(1,s);
right = true;
} else {
moverX -= 10;
}
}
if (keysDown.contains(KeyEvent.VK_DOWN) /*|| keysDown.contains(KeyEvent.VK_S)*/){
scaleChange = true;
moverY -= 10;
}
if (keysDown.contains(KeyEvent.VK_LEFT) /*|| keysDown.contains(KeyEvent.VK_A)*/){
if (!moving) {
Player.move(3,s);
right = false;
} else {
moverX += 10;
}
}
if (keysDown.contains(KeyEvent.VK_E)){
databaseConnector(true);
}
if (keysDown.contains(KeyEvent.VK_SPACE)){
Player.ha = 0;
Player.va = 0;
Player.vSpeed = 0;
Player.hSpeed = 0;
if (!moving){
modulus[0] = mod1.getValue();
modulus[1] = mod2.getValue();
natural[0] = len1.getValue();
natural[0] /= 10;
natural[1] = len2.getValue();
natural[1] /= 10;
setRectangles();
startPosition = (int) (Player.getCenterX() - rect.get(0).getMaxX());
}
moving = !moving;
}
if (keysDown.contains(KeyEvent.VK_EQUALS)){
scaleScreen += 1;
scaleChange = true;
}
if (keysDown.contains(KeyEvent.VK_SLASH)){
scaleScreen -= 1;
if(scaleScreen == 0){
scaleScreen = 1;
}
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if (!keysDown.contains(e.getKeyCode())){
keysDown.add(e.getKeyCode());
}
action();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void keyReleased(KeyEvent e) {
keysDown.remove(new Integer(e.getKeyCode()));
}
}

crystal reports RCAPI

Is there is a way to display the data in specified format using RCAPI.
Pls find the code below.
ReportClientDocument boReportClientDocument = new ReportClientDocument();
boReportClientDocument.open("blankreport.rpt", 0);
public void displayReportData(ReportClientDocument document,ISection detailArea) {
int INSERT_AT_END = -1;
DBUtil dBUtil = new DBUtil();
Field field = null;
Fields fields = null;
FieldObject boFieldObject = null;
try {
document.getDatabaseController().addDataSource(dBUtil.getData());
// ISection detailArea = document.getReportDefController().getReportDefinition().getDetailArea().getSections().get(0);
Tables tables = document.getDatabaseController().getDatabase().getTables();
for (int i = 0; i < tables.size(); i++) {
fields = tables.getTable(i).getDataFields();
int leftInc = 0;
int topInc =0;
System.out.println("no of records iiii::::" + i);
for (int j = 0; j < fields.size(); j++) {
System.out.println("no of records jjjj::::" + j);
field = (Field) fields.get(j);
boFieldObject = new FieldObject();
boFieldObject.setDataSource(field.getFormulaForm());
boFieldObject.setFieldValueType(field.getType());
boFieldObject.setLeft(250 +leftInc);
boFieldObject.setTop(800);
boFieldObject.setWidth(3);
boFieldObject.setHeight(250);
// leftInc += 30;
//topInc += 50;
document.getReportDefController().getReportObjectController().add(boFieldObject,detailArea,-1);
}
}
} catch (ReportSDKException ex) {
Logger.getLogger(Report.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
System.out.println(ex);
}
}

Writing 2d array into file that needs to look like array

I have the following code that creates and writes to the file but it writes everything out in one solid line.
Example: 11111111111111111111111111
I need it look like the following(space in between every number):
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
Here is my code:
public void saveFile()
{
String save = "Testing";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]));
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
}
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This is because you are not putting space between them.
bw.write(String.valueOf(gameArray[row][col]));
bw.write(" ");
and at the end of inner loop, again,
bw.write("\n");
write bw.write("\n") at the end of your inner loop.
Just like :
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]));
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
bw.write("\n")
}
This should work for you:
public void saveFile()
{
String save = "Testing";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]);
if ((col+1)!=gameArray[row].length)
bw.write(" ");
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
bw.write(System.getProperty("line.seperator"));
}
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Can't read int from input file in java

I've got a program that reads an input file with 4000 1's or 0's, one on each line.
The program compiles fine but when it runs I get the following error:
ˇ˛0Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Project1.main(Project1.java:27)
For some reason when I look at the text file, the first line is a 0 and nothing else yet when the program reads the first line it gets ˇ˛0. I also tried using a buffered reader with no luck. Could anyone please offer some input. Thank you!
Here's my code:
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class Project1 {
public static void main(String[] args) {
int [] stream = new int[4000];
int [] received = new int[4000];
int corrupt = 0;
float standardDev = 0;
float [] averages = new float[4000];
float averagev = 0;
float voltage = 0;
try {
Scanner st = new Scanner(new File("CS 380 bit feed.txt"));
System.out.print(st.next());
FileWriter outFile = new FileWriter("output");
PrintWriter out = new PrintWriter(outFile);
int i=0;
Random rand = new Random();
stream[i]=st.nextInt();
if (stream[i] == 0)
voltage = (float) (2.49 * rand.nextFloat());
else
voltage = (float) ((2.5 * rand.nextFloat()) + 2.5);
if (voltage < 2.5)
received[i] = 0;
else
received[i] = 1;
averagev = voltage;
averages[i] = voltage;
if (stream[i] != received[i])
corrupt++;
i++;
while (i < 4000) {
stream[i]=st.nextInt();
if (stream[i] == 0)
voltage = (float) 2.49 * rand.nextFloat();
else
voltage = (float) ((2.5 * rand.nextFloat()) + 2.5);
averagev = ((averagev * i) + voltage)/(i+1);
if (voltage <= averagev)
received[i] = 0;
else
received[i] = 1;
if (stream[i] != received[i])
corrupt++;
i++;
}
averagev = 0;
int j = 0;
while (j < 4000) {
for (int k = 0; k<8; k++) {
out.print(received[j]);
averagev = averages[i] + averagev;
j++;
}
out.println(" " + averages[j]);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
averagev = averagev / 4000;
for (int k = 0; k<4000; k++)
standardDev = ((averagev - averages[k])*(averagev - averages[k])) + standardDev;
standardDev = standardDev/4000;
System.out.println("Errors: " + corrupt);
System.out.println("Percentage Corrupt: " + corrupt / 4000);
System.out.println("Average of Average Voltages: " + averagev);
System.out.println("Standard Deviation: " + standardDev);
}
}
Look at the file in a hex editor. It might be corrupt or have a Byte Order Mark at the beginning, which wouldn't necessarily show up in a text editor.

What's wrong with my loop? Keep getting NoSuchElementException

I keep getting a NoSuchElement Exception at the line maze[r][c]=scan.next();. How can I resolve that?
try {
Scanner scan = new Scanner(f);
String infoLine = scan.nextLine();
int rows=0;
int columns=0;
for(int i = 0; i<infoLine.length();i++){
if(Character.isDigit(infoLine.charAt(i))==true){
rows = (int)infoLine.charAt(i);
columns = (int)infoLine.charAt(i+1);
break;
}
}
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNextLine()==true && r<rows){
for(int c = 0; c<columns;c++){
maze[r][c]=scan.next();
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Look at this part of your code:
while(scan.hasNextLine()==true && r<rows){ // 1
for(int c = 0; c<columns;c++){ // 2
maze[r][c]=scan.next(); // 3
} // 4
r++; // 5
} // 6
In line 1 you are checking to make sure that scan has another line available. But in line 3, you read that line - inside the 2:4 loop. So if there are more than 1 columns, you will be asking for the next scan more than once - and you only checked to see if there was one next line. So on the second column, if you're at the end of scan, you try to read from scan even though it's run out.
Try this:
try {
Scanner scan = new Scanner(f);
String infoLine = scan.nextLine();
int rows = 0;
int columns = 0;
for (int i = 0; i < infoLine.length();i++) {
if (Character.isDigit(infoLine.charAt(i))) {
rows = Character.digit(infoLine.charAt(i), 10);
columns = Character.digit(infoLine.charAt(i + 1), 10);
break;
}
}
String [][] maze = new String[rows][columns];
int r = 0;
while(scan.hasNextLine() && r < rows) {
int c = 0;
while(scan.hasNextLine() && c < columns) {
maze[r][c]=scan.next();
c++
}
r++;
}
return maze;
} catch (FileNotFoundException e) {
e.printStackTrace();
}

Categories

Resources