9

For college, we have been given an assignment where, given an image, we have to identify the "figures", their color, and the amount of "pixel-groups" inside them. Let me explain:

enter image description here

The image above has one figure (in the image there can be multiple figures, but let us forget about that for now).

  • The background color of the canvas is the pixel at 0,0 (in this case, yellow)
  • The border color of the figure is black (it can be any color other than the canvas' background color).
  • The figure's background color is white (it can also be the same as the canvas' background color).
  • A figure can only have one background color.
  • There are two pixel groups in the figure. One is a pool of blue pixels, and the other is a pool of red with some green inside. As you can see, it doesn't matter the color of the pixel group's pixels (it is just different than the figure's background color). What matters is the fact that they're in contact (even diagonally). So despite having two different colors, such group is considered as just one anyway.
  • As you can see, the border can be as irregular as you wish. It only has, however, one color.
  • It is known that a pixel group will not touch the border.
  • I was told that a pixel group's colors can be any except the figure's background color. I assume that then it can be the same as the figure's border color (black).

We have been given a class capable of taking images and converting them to a matrix (each element being an integer representing the color of the pixel).

And that's it. I'm doing it with Java.

WHAT HAVE I DONE SO FAR

  • Iterate through each pixel in the matrix
  • If I find a pixel that is different from the background color, I will assume it belongs to the border of the figure. I will call this pixel initialPixel from now on.
  • Note that the initialPixel in the image I provided is that black pixel in the top-left corner of the figure. I made a sharp cut there purposefully to illustrate it.
  • My mission now is to find the background color of the figure (in this case white).

But I'm having quite a great deal of trouble to find such background color (white). This is the closest method I did, which worked for some cases - but not with this image:

  • Since I know the color of the border, I could find the first different color that is to the south of the initialPixel. Did sound like a good idea - it did work sometimes, but it would not work with the image provided: it will return yellow in this case, since initialPixel is quite away from the figure's contents.

Assuming I did find the figure's background color (white), my next task would be to realize that there exist two pixel groups within the figure. This one seems easier:

  • Since I now know the figure's background color (white), I can try iterating through each pixel within the figure and, if I find one that does not belong to the border and is not part of the figure's background, I can already tell there is one pixel group. I can begin a recursive function to find all pixels related to such group and "flag" them so that in the future iterations I can completely ignore such pixels.

WHAT I NEED

Yes, my problem is about how to find the figure's background color (keep in mind it can be the same as the whole image's background color - for now it is yellow, but it can be white as well) based on what I described before.

I don't need any code - I'm just having trouble thinking a proper algorithm for such. The fact that the border can have such weird irregular lines is killing me.

Or even better: have I been doing it wrong all along? Maybe I shouldn't have focused so much on that initialPixel at all. Maybe a different kind of initial method would have worked? Are there any documents/examples about topics like this? I realize there is a lot of research on "computer vision" and such, but I can't find much about this particular problem.

SOME CODE

My function to retrieve a vector with all the figures: *Note: Figure is just a class that contains some values like the background color and the number of elements.

public Figure[] getFiguresFromImage(Image image) {
    Figure[] tempFigures = new Figure[100];
    int numberOfFigures = 0;
    matrixOfImage = image.getMatrix();
    int imageBackgroundColor = matrixOfImage[0][0];
    int pixel = 0;

    for (int y = 0; y < matrixOfImage.length; ++y) {
        for (int x = 0; x < matrixOfImage[0].length; ++x) {
            pixel = matrixOfImage[y][x];
            if (!exploredPixels[y][x]) {
                // This pixel has not been evaluated yet
                if (pixel != imageBackgroundColor ) {
                    // This pixel is different than the background color
                    // Since it is a new pixel, I assume it is the initial pixel of a new figure
                    // Get the figure based on the initial pixel found
                    tempFigures[numberOfFigures] = retrieveFigure(y,x);
                    ++numberOfFigures;
                }
            }
        }   
    }

    // ** Do some work here after getting my figures **

    return null;
}

Then, clearly, the function retrieveFigure(y,x) is what I am being unable to do.

Notes:

  • For learning purposes, I should not be using any external libraries.
Saturn
  • 17,888
  • 49
  • 145
  • 271
  • how do u define background of an image and tell to your program? – DarthVader Oct 21 '12 at 06:03
  • in your picture? is the white background or the yellow? i cant even tell that. even the black might be the background. – DarthVader Oct 21 '12 at 06:04
  • @DarthVader: Ah! I'm sorry. The background color of the canvas is the pixel at 0,0. And the figure will not touch the border of the canvas. – Saturn Oct 21 '12 at 06:06
  • See [this answer](http://stackoverflow.com/questions/7052422/image-graphic-into-a-shape-in-java/7059497#7059497) which became [this question](http://stackoverflow.com/questions/7218309/smoothing-a-jagged-path) for one approach to finding the regions of where a color occurs. – Andrew Thompson Oct 21 '12 at 06:06

2 Answers2

7

A good way to solve this problem is to treat the image as a graph, where there is one node ('component' in this answer) for each color filled area.

Here is one way to implement this approach:

  1. Mark all pixels as unvisited.

  2. For each pixel, if the pixel is unvisited, perform the flood fill algorithm on it. During the flood fill mark each connected pixel as visited.

    Now you should have a list of solid color areas in your image (or 'components'), so you just have to figure out how they are connected to each other:

  3. Find the component that has pixels adjacent to the background color component - this is your figure border. Note that you can find the background color component by finding the component with the 0,0 pixel.

  4. Now find the components with pixels adjacent to the newly found 'figure border' component. There will be two such components - pick the one that isn't the background (ie that doesn't have the 0,0 pixel). This is your figure background.

  5. To find the pixel groups, simply count the number of components with pixels adjacent to the figure background component (ignoring of course the figure border component)

Advantages of this approach:

  • runs in O(# pixels) time.
  • easy to understand and implement.
  • doesn't assume the background color and figure background color are different.

To make sure you understand how iterating through the components and their neighbors might work, here's an example pseudocode implementation for step 5:

List<Component> allComponents; // created in step 2
Component background; // found in step 3 (this is the component with the 0,0 pixel)
Component figureBorder; // found in step 4
List<Component> pixelGroups = new List<Component>(); // list of pixel groups

for each Component c in allComponents:
    if c == background:
        continue;
    for each Pixel pixel in c.pixelList:
        for each Pixel neighbor in pixel.neighbors:
            if neighbor.getComponent() == figureBorder:
                c.isPixelGroup = true;

int numPixelGroups = 0;
for each Component c in allComponents:
    if (c.isPixelGroup)
        numPixelGroups++;
Community
  • 1
  • 1
Cam
  • 14,930
  • 16
  • 77
  • 128
  • Thanks, it sounds like a great idea, and now I'm in the middle of trying it out. I'll let you know how things go :). I have a question about step 5 though: what if I need to find out how many pixel groups does *a certain figure* has? I mean, apparently your example will find all pixel groups in the whole image, but I may need to say "There is a figure color green with 2 groups, and there is another figure color green with 5 groups" – Saturn Oct 22 '12 at 23:19
  • @Omega: That's great to hear - sorry I missed your comment above! – Cam Nov 01 '12 at 04:12
1

Try this code :

import java.util.Scanner;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;

class Analyzer{
    private int pixdata[][];
    private int rgbdata[][];
    private BufferedImage image;
    int background_color;
    int border_color;
    int imagebg_color;
    private void populateRGB(){
        rgbdata = new int[image.getWidth()][image.getHeight()];
        for(int i = 0; i < image.getWidth(); i++){
            for(int j = 0; j < image.getHeight(); j++){
                rgbdata[i][j] = image.getRGB(i, j);
            }
        }
        int howmanydone = 0;
        int prevcolor,newcolor;
        prevcolor = rgbdata[0][0];

        /*
        for(int i = 0; i < image.getWidth(); i++){
           for(int j = 0; j < image.getHeight(); j++){
              System.out.print(rgbdata[i][j]);
           }
           System.out.println("");
        }*/
        for(int i = 0; i < image.getWidth(); i++){
            for(int j = 0; j < image.getHeight(); j++){
                newcolor = rgbdata[i][j];
                if((howmanydone == 0) && (newcolor != prevcolor)){
                    background_color = prevcolor;
                    border_color = newcolor;
                    prevcolor = newcolor;
                    howmanydone = 1;
                }
                if((newcolor != prevcolor) && (howmanydone == 1)){
                    imagebg_color = newcolor;
                }
            }
        }
    }
    public Analyzer(){ background_color = 0; border_color = 0; imagebg_color = 0;}
    public int background(){ return background_color; }
    public int border() { return border_color;}
    public int imagebg() {return imagebg_color;}
    public int analyze(String filename,String what) throws IOException{
        image = ImageIO.read(new File(filename));
        pixdata = new int[image.getHeight()][image.getWidth()];
        populateRGB();
        if(what.equals("background"))return background();
        if(what.equals("border"))return border();
        if(what.equals("image-background"))return imagebg();
        else return 0;
    }
}
public class ImageAnalyze{
    public static void main(String[] args){
        Analyzer an = new Analyzer();
        String imageName;

        Scanner scan = new Scanner(System.in);
        System.out.print("Enter image name:");
        imageName = scan.nextLine();
        try{
        int a = an.analyze(imageName,"border");//"border","image-background","background" will get you different colors
        System.out.printf("Color bg: %x",a);

        }catch(Exception e){
           System.out.println(e.getMessage());
        }
    }
}

the color returned is ARGB format. You will need to extract R,G and B from it.

There is a bug in this code. Working on implementation using Finite State machine. in the first state you're inside the image, hence 0,0 is the background color, then when there is a change, the change is the border color, then the third state is when inside the image + inside the border and the color changes.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
  • As in, starting from the initialPixel position and then go diagonally down-right? But if I did that, there is a chance (probably in the image I provided) that the result will be yellow instead of the expected white. Because, in that case, initialPixel is so away that if you go diagonally down-right, it seems rather possible you will hit yellow instead of white. If not, then just imagine that black border a bit larger. – Saturn Oct 21 '12 at 06:22
  • You can choose to ignore a certain color(transparent), (yellow in this case). Define what's a boundary(black in this case) – Aniket Inge Oct 21 '12 at 06:24
  • I can't choose to ignore yellow, because it is also possible that the figure's background color is indeed yellow as well (the figure's background and the canvas' background colors can be the same - in this case they are not, bit it is possible anyway). – Saturn Oct 21 '12 at 06:26