Click here to Skip to main content
15,891,423 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have been doing this for several days and I cant seem to understand how to find the total number of pixels. Also I need to find the center of the image as well which is just the average of the coordinates but everytime I put something in it doesn't work out. here is code so far:

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
public class Quiz {
static int width,height;
public static void main( String[] args ){
try {
BufferedImage image = null;
URL url=new URL("http://imc.kean.edu/cps2231/program6.png");
image = ImageIO.read(url);
height=image.getHeight();
width=image.getWidth();
System.out.println("width:"+width+ " height:"+height);

int [][] img=new int[height][width];

for (int y=0;y<height;y++)>
for (int x=0;x<width;x++)>
img[y][x]= image.getData().getSample(x, y, 0);

printImg(img);

int color=2;
int cX=0;
int cY=0;
int pixels=0;
for (int y=0;y<height;y++)> for (int x=0;x<width;x++){>
if (img[y][x] ==0){
label(img, x, y, color);
System.out.println("Color: " + color + " Object size: " + pixels + " pixels," + " Center at "+"("+cX+","+cY+")");
color++;

}
}
}

System.out.println("Total number of black objects:"+ (color-2));
printImg(img);
} catch (IOException e) { e.printStackTrace(); }
}



static void label(int[][] A, int x, int y, int color) {
if ((x>=0) && (y>=0) && (x<width)> System.out.printf("(%d,%d) color:%d\n",x,y,color);
A[y][x]=color;
label(A, x, y-1, color);
label(A, x-1,y, color);
label(A, x, y+1, color);
label(A, x+1, y, color);
}
}

static void printImg(int[][] A) {
for (int y=0;y<height;y++)> for (int x=0;x<width;x++)>
System.out.printf("%d",A[y][x]);
System.out.println();






}
}
}
Posted
Comments
Richard MacCutchan 20-Dec-15 10:19am    
The total number of pixels should be the image width times height. The centre is the intersect of those two values. Please also put <pre> tags round your code to make it readable, and indicate where the problem occurs, and exactly what the problem is.

1 solution

You should view the properties of the image to find out the width and height.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900