I'm working to test this chunk of code - it's a class called MazeBuilder. My problem is that most of the methods are protected, so I can't access them in the tests...
So my thought was that the test should just focus on Run(), so it accesses a lot of the other methods. But I'm concerned that it will be impossible to get any sort of cohesive testing done operating from just one method.
Additionally, what is the proper way to test the 2 constructors ( MazeBuilder() and MazeBuilder(boolean deterministic) )? As it stands, I'm just testing that the object formed is not null - i.e. that they're being built at all. Is there a more expansive way of testing a constructor that I'm unaware of?
package falstad;
public class MazeBuilder implements Runnable {
// Given input information:
protected int width, height ; // width and height of maze,
Maze maze; // reference to the maze that is constructed, results are returned by calling maze.newMaze(..)
private int rooms; // requested number of rooms in maze, a room is an area with no walls larger than a single cell
int expectedPartiters; // user given limit for partiters
// Produced output information to create the new maze
// root, cells, dists, startx, starty
protected int startx, starty ; // starting position inside maze for entity to search for exit
// conventional encoding of maze as a 2 dimensional integer array encapsulated in the Cells class
// a single integer entry can hold information on walls, borders/bounds
protected Cells cells; // the internal representation of a maze as a matrix of cells
protected Distance dists ; // distance matrix that stores how far each position is away from the exit positino
// class internal local variables
protected SingleRandom random ; // random number stream, used to make randomized decisions, e.g for direction to go
Thread buildThread; // computations are performed in own separated thread with this.run()
//int colchange; // randomly selected in run method of this thread, used as parameter to Segment class constructor
/**
* Constructor for a randomized maze generation
*/
public MazeBuilder(){
random = SingleRandom.getRandom();
}
/**
* Constructor with option to make maze generation deterministic or random
*/
public MazeBuilder(boolean deterministic){
if (true == deterministic)
{
System.out.println("Project 2: functionality to make maze generation deterministic not implemented yet! Fix this!");
// Control random number generation
// TODO: implement code that makes sure that if MazeBuilder.build is called for same skill level twice, same results
// HINT: check http://download.oracle.com/javase/6/docs/api/java/util/Random.html and file SingleRandom.java
}
random = SingleRandom.getRandom();
}
/**
* Provides the sign of a given integer number
* #param num
* #return -1 if num < 0, 0 if num == 0, 1 if num > 0
*/
static int getSign(int num) {
return (num < 0) ? -1 : (num > 0) ? 1 : 0;
}
/**
* This method generates a maze.
* It computes distances, determines a start and exit position that are as far apart as possible.
*/
protected void generate() {
// generate paths in cells such that there is one strongly connected component
// i.e. between any two cells in the maze there is a path to get from one to the other
// the search algorithm starts at some random point
generatePathways();
final int[] remote = dists.computeDistances(cells) ;
// identify cell with the greatest distance
final int[] pos = dists.getStartPosition();
startx = pos[0] ;
starty = pos[1] ;
// make exit position at true exit in the cells data structure
setExitPosition(remote[0], remote[1]);
}
/**
* This method generates pathways into the maze.
*
*/
protected void generatePathways() {
int[][] origdirs = new int[width][height] ;
int x = random.nextIntWithinInterval(0, width-1) ;
int y = 0;
final int firstx = x ;
final int firsty = y ;
int dir = 0;
int origdir = dir;
cells.setVisitedFlagToZero(x, y);
while (true) {
int dx = Constants.DIRS_X[dir];
int dy = Constants.DIRS_Y[dir];
if (!cells.canGo(x, y, dx, dy)) {
dir = (dir+1) & 3;
if (origdir == dir) {
if (x == firstx && y == firsty)
break;
int odr = origdirs[x][y];
dx = Constants.DIRS_X[odr];
dy = Constants.DIRS_Y[odr];
x -= dx;
y -= dy;
origdir = dir = random.nextIntWithinInterval(0, 3);
}
} else {
cells.deleteWall(x, y, dx, dy);
x += dx;
y += dy;
cells.setVisitedFlagToZero(x, y);
origdirs[x][y] = dir;
origdir = dir = random.nextIntWithinInterval(0, 3);
}
}
}
/**
* Establish valid exit position by breaking down wall to outside area.
* #param remotex
* #param remotey
*/
protected void setExitPosition(int remotex, int remotey) {
int bit = 0;
if (remotex == 0)
bit = Constants.CW_LEFT;
else if (remotex == width-1)
bit = Constants.CW_RIGHT;
else if (remotey == 0)
bit = Constants.CW_TOP;
else if (remotey == height-1)
bit = Constants.CW_BOT;
else
dbg("Generate 1");
cells.setBitToZero(remotex, remotey, bit);
//System.out.println("exit position set to zero: " + remotex + " " + remotey + " " + bit + ":" + cells.hasMaskedBitsFalse(remotex, remotey, bit)
// + ", Corner case: " + ((0 == remotex && 0 == remotey) || (0 == remotex && height-1 == remotey) || (width-1 == remotex && 0 == remotey) || (width-1 == remotex && height-1 == remotey)));
}
static final int MIN_ROOM_DIMENSION = 3 ;
static final int MAX_ROOM_DIMENSION = 8 ;
/**
* Allocates space for a room of random dimensions in the maze.
* The position of the room is chosen randomly. The method is not sophisticated
* such that the attempt may fail even if the maze has ample space to accommodate
* a room of the chosen size.
* #return true if room is successfully placed, false otherwise
*/
private boolean placeRoom() {
// get width and height of random size that are not too large
// if too large return as a failed attempt
final int rw = random.nextIntWithinInterval(MIN_ROOM_DIMENSION, MAX_ROOM_DIMENSION);
if (rw >= width-4)
return false;
final int rh = random.nextIntWithinInterval(MIN_ROOM_DIMENSION, MAX_ROOM_DIMENSION);
if (rh >= height-4)
return false;
// proceed for a given width and height
// obtain a random position (rx,ry) such that room is located on as a rectangle with (rx,ry) and (rxl,ryl) as corner points
// upper bound is chosen such that width and height of room fits maze area.
final int rx = random.nextIntWithinInterval(1, width-rw-1);
final int ry = random.nextIntWithinInterval(1, height-rh-1);
final int rxl = rx+rw-1;
final int ryl = ry+rh-1;
// check all cells in this area if they already belong to a room
// if this is the case, return false for a failed attempt
if (cells.areaOverlapsWithRoom(rx, ry, rxl, ryl))
return false ;
// since the area is available, mark it for this room and remove all walls
// from this on it is clear that we can place the room on the maze
cells.markAreaAsRoom(rw, rh, rx, ry, rxl, ryl);
return true;
}
static void dbg(String str) {
System.out.println("MazeBuilder: "+str);
}
/**
* Fill the given maze object with a newly computed maze according to parameter settings
* #param mz maze to be filled
* #param w width of requested maze
* #param h height of requested maze
* #param roomct number of rooms
* #param pc number of expected partiters
*/
public void build(Maze mz, int w, int h, int roomct, int pc) {
init(mz, w, h, roomct, pc);
buildThread = new Thread(this);
buildThread.start();
}
/**
* Initialize internal attributes, method is called by build() when input parameters are provided
* #param mz maze to be filled
* #param w width of requested maze
* #param h height of requested maze
* #param roomct number of rooms
* #param pc number of expected partiters
*/
private void init(Maze mz, int w, int h, int roomct, int pc) {
// store parameters
maze = mz;
width = w;
height = h;
rooms = roomct;
expectedPartiters = pc;
// initialize data structures
cells = new Cells(w,h) ;
dists = new Distance(w,h) ;
//colchange = random.nextIntWithinInterval(0, 255); // used in the constructor for Segments class Seg
}
static final long SLEEP_INTERVAL = 100 ; //unit is millisecond
/**
* Main method to run construction of a new maze with a MazeBuilder in a thread of its own.
* This method is called internally by the build method when it sets up and starts a new thread for this object.
*/
public void run() {
// try-catch block to recognize if thread is interrupted
try {
// create an initial invalid maze where all walls and borders are up
cells.initialize();
// place rooms in maze
generateRooms();
Thread.sleep(SLEEP_INTERVAL) ; // test if thread has been interrupted, i.e. notified to stop
// put pathways into the maze, determine its starting and end position and calculate distances
generate();
Thread.sleep(SLEEP_INTERVAL) ; // test if thread has been interrupted, i.e. notified to stop
final int colchange = random.nextIntWithinInterval(0, 255); // used in the constructor for Segments class Seg
final BSPBuilder b = new BSPBuilder(maze, dists, cells, width, height, colchange, expectedPartiters) ;
BSPNode root = b.generateBSPNodes();
Thread.sleep(SLEEP_INTERVAL) ; // test if thread has been interrupted, i.e. notified to stop
// dbg("partiters = "+partiters);
// communicate results back to maze object
maze.newMaze(root, cells, dists, startx, starty);
}
catch (InterruptedException ex) {
// necessary to catch exception to avoid escalation
// exception mechanism basically used to exit method in a controlled way
// no need to clean up internal data structures
// dbg("Catching signal to stop") ;
}
}
static final int MAX_TRIES = 250 ;
/**
* Generate all rooms in a given maze where initially all walls are up. Rooms are placed randomly and of random sizes
* such that the maze can turn out to be too small to accommodate the requested number of rooms (class attribute rooms).
* In that case less rooms are produced.
* #return generated number of rooms
*/
private int generateRooms() {
// Rooms are randomly positioned such that it may be impossible to place the all rooms if the maze is too small
// to prevent an infinite loop we limit the number of failed to MAX_TRIES == 250
int tries = 0 ;
int result = 0 ;
while (tries < MAX_TRIES && result <= rooms) {
if (placeRoom())
result++ ;
else
tries++ ;
}
return result ;
}
/**
* Notify the maze builder thread to stop the creation of a maze and to terminate
*/
public void interrupt() {
buildThread.interrupt() ;
}
}
To unit test your protected methods, simply put your test class in the same package as the class you are looking to test (in this case falsted). Just because they are in the same package, it doesn't mean they have to be in the same directory (just a parallel test directory hierarchy).
For example, if you are using maven, your source would be in src/main/java/falsted and your tests would be in src/test/java/falsted. From a maven perspective, these are separate directories and therefore can easily be managed separately, while from a Java perspective, they are the same package (so protected methods are visible).
Test your constructors by probing the state of the object to ensure that all values got their default or initial value.
You can use protected in test method. Recommended way to structure your project is.
In src/main/java
package falstad;
public class MazeBuilder {}
In src/test/java
package falstad;
public class MazeBuilderTest {}
Related
Just to be clear, I have looked at problems somewhat similar to this on Stack Overflow and other websites before asking for help. I also included all of the code below just in case it could help anyone understand the problem.
In the game Othello, also known as Reversi, there are two players who use tiles of opposite colors. The player needs to place a tile so it is adjacent to a tile of the opposite color and the opposite color must be surrounded by a tile on either side in the same direction. For example, if there is a white tile to the left of a black tile, then another black tile needs to be placed on the left of the white tile so it is surrounded. If a tile is surrounded it flips.
(Black - White - Black) --> (Black - Black - Black)
Surrounding can happen either horizontally, diagonally or vertically.
The problem I'm having is I do not know how to check all of the indices and see if they work at once. I have tried checking for the values adjacent to a tile of the opposite color, by checking all possible values next to it. This doesn't work properly as it can't make sure that a tile is surrounded on both sides or apply to a line of more than one tile in a row.
/**
* Checks to see if a valid move can be made at the indicated OthelloCell,
* for the given player.
* #param xt The horizontal coordinate value in the board.
* #param yt The vertical coordinate value in the board.
* #param bTurn Indicates the current player, true for black, false for white
* #return Returns true if a valid move can be made for this player at
* this position, false otherwise.
*/
public boolean isValidMove(int xt, int yt, boolean bTurn)
{
int length = board[0].length;
// checks if the tile has already been picked, meaning it can no longer be selected
if(board[xt][yt].hasBeenPlayed())
{
return false;
}
else
{
/* For BLACK (Working) */
if(bTurn)
{
// checks tiles one row above
if(xt + 1 < length && board[xt + 1][yt].getBlackStatus() == false)
{
System.out.println("the one 1 row up and in the same column doesn't work");
return true;
}
if(xt + 1 < length && board[xt + 1][yt + 1].getBlackStatus() == false)
{
System.out.println("the one 1 row up and in the right column doesn't work");
return true;
}
if(xt + 1 < length && board[xt + 1][yt - 1].getBlackStatus() == false)
{
System.out.println("the one 1 row up and in the left column doesn't work");
return true;
}
// checks tiles left and right
if(yt + 1 < length && board[xt][yt + 1].getBlackStatus() == false)
{
System.out.println("the one in the same row and in the right column doesn't work");
return true;
}
if(yt > 1 && board[xt][yt - 1].getBlackStatus() == false)
{
System.out.println("the one in the same row and in the left column doesn't work");
return true;
}
// checks tiles one row below
if(xt > 1 && board[xt - 1][yt].getBlackStatus() == false)
{
System.out.println("The one 1 row down and in the same column doesn't work");
return true;
}
if(xt > 1 && board[xt - 1][yt + 1].getBlackStatus() == false)
{
System.out.println("The one 1 row down and in the right column doesn't work");
return true;
}
if(xt > 1 && board[xt - 1][yt - 1].getBlackStatus() == false)
{
System.out.println("The one 1 row down and in the left column doesn't work");
return true;
}
}
}
return false;
}
/**
* Checks to see if a valid move can be made at the indicated OthelloCell, in a
* particular direction (there are 8 possible directions). These are indicated by:
* (1,1) is up and right
* (1,0) is right
* (1,-1) is down and right
* (0,-1) is down
* (-1,-1) is down and left
* (-1,0) is left
* (-1,1) is left and up
* (0,1) is up
* #param xt The horizontal coordinate value in the board.
* #param yt The vertical coordinate value in the board.
* #param i -1 is left, 0 is neutral, 1 is right,
* #param j -1 is down, - is neutral, 1 is up.
* #param bTurn Indicates the current player, true for black, false for white.
* #return Returns true if this direction has pieces to be flipped, false otherwise.
*/
public boolean directionValid(int xt, int yt, int i, int j, boolean bTurn)
{
return true;
}
Above are the two methods I'm having trouble with.
public class Othello
{
/** The board object. This board will be 8 x 8, and filled with OthelloCells.
* The cell may be empty, hold a white game piece, or a black game piece. */
private OthelloCell [][] board;
/** The coordinates of the active piece on the board. */
private int x, y;
/** Booleans indicating that the mouse is ready to be pressed, that it is
* black's turn to move (false if white's turn), and that the game is over. */
private boolean mousePressReady, blackTurn, gameOver;
/**
* Creates an Othello object, with a sized graphics canvas, and a 2D (8 x 8) array
* of OthelloCell, setting up initial values.
*/
/* COMPLETE */
public Othello ( )
{
StdDraw.setCanvasSize(500,650);
StdDraw.setXscale(0,1);
StdDraw.setYscale(0,1.3);
StdDraw.enableDoubleBuffering();
Font font = new Font("Arial", Font.BOLD, 30);
StdDraw.setFont(font);
startBoard();
}
/**
* Called by the constructor, or when the player hits the "RESET" button,
* initializing the game board (an 8 x 8 array of OthelloCell).
*/
/* COMPLETE */
public void startBoard ( )
{
mousePressReady = blackTurn = true;
gameOver = false;
board = new OthelloCell[8][8];
for ( int i = 0; i < board.length; i++ )
{
for ( int j = 0; j < board[i].length; j++ )
{
board[i][j] = new OthelloCell(i,j);
}
}
board[3][3].playIt();
board[3][3].setBlack(true);
board[4][4].playIt();
board[4][4].setBlack(true);
board[4][3].playIt();
board[4][3].setBlack(false);
board[3][4].playIt();
board[3][4].setBlack(false);
}
/**
* Sets up and runs the game of Othello.
*/
/* COMPLETE */
public static void main(String [] args)
{
Othello game = new Othello();
game.run();
}
/**
* Runs an endless loop to play the game. Even if the game is over, the
* loop is still ready for the user to press "RESET" to play again.
*/
/* COMPLETE */
public void run ( )
{
do
{
drawBoard();
countScoreAnddrawScoreBoard();
StdDraw.show();
StdDraw.pause(30);
makeChoice();
gameOver = checkTurnAndGameOver();
}
while(true);
}
/**
* Draws the board, in its current state, to the GUI.
*/
/* COMPLETE */
public void drawBoard ( )
{
StdDraw.setPenColor(new Color(150,150,150));
StdDraw.filledRectangle(0.5,0.75,0.5,0.75);
StdDraw.setPenColor(new Color(0,110,0));
StdDraw.filledSquare(0.5,0.5,0.45);
StdDraw.setPenColor(new Color(0,0,0));
StdDraw.filledSquare(0.5,0.5,0.42);
for ( int i = 0; i < board.length; i++ )
{
for ( int j = 0; j < board[i].length; j++ )
{
board[i][j].drawCell();
}
}
}
/**
* Waits for the user to make a choice. The user can make a move
* placing a black piece or the white piece (depending on whose turn
* it is), or click on the "RESET" button to reset the game.
*/
/* COMPLETE */
public void makeChoice ( )
{
boolean moveChosen = false;
while(!moveChosen)
{
if(mousePressReady && StdDraw.isMousePressed())
{
mousePressReady = false;
double xval = StdDraw.mouseX();
double yval = StdDraw.mouseY();
if(xval > 0.655 && xval < 0.865 && yval > 1.15 && yval < 1.23) // This if checks for a reset.
{
startBoard();
return;
}
if(xval < 0.1 || xval > 0.9 || yval < 0.1 || yval > 0.9) // This if checks for a press off the board.
{
return;
}
int tempx = (int)(10 * (xval - 0.1));
int tempy = (int)(10 * (yval - 0.1));
if(isValidMove(tempx,tempy,blackTurn)) // This if checks to see if the move is valid.
{
x = tempx;
y = tempy;
playAndFlipTiles();
blackTurn = !blackTurn;
System.out.println(x + " " + y);
}
}
if(!StdDraw.isMousePressed() && !mousePressReady) // This if gives back control when the mouse is released.
{
mousePressReady = true;
return;
}
StdDraw.pause(20);
}
}
/**
* Checks to see if a valid move can be made at the indicated OthelloCell,
* for the given player.
* #param xt The horizontal coordinate value in the board.
* #param yt The vertical coordinate value in the board.
* #param bTurn Indicates the current player, true for black, false for white
* #return Returns true if a valid move can be made for this player at
* this position, false otherwise.
*/
public boolean isValidMove(int xt, int yt, boolean bTurn)
{
int length = board[0].length;
// checks if the tile has already been picked, meaning it can no longer be selected
if(board[xt][yt].hasBeenPlayed())
{
return false;
}
else
{
}
return false;
}
/**
* Checks to see if a valid move can be made at the indicated OthelloCell, in a
* particular direction (there are 8 possible directions). These are indicated by:
* (1,1) is up and right
* (1,0) is right
* (1,-1) is down and right
* (0,-1) is down
* (-1,-1) is down and left
* (-1,0) is left
* (-1,1) is left and up
* (0,1) is up
* #param xt The horizontal coordinate value in the board.
* #param yt The vertical coordinate value in the board.
* #param i -1 is left, 0 is neutral, 1 is right,
* #param j -1 is down, - is neutral, 1 is up.
* #param bTurn Indicates the current player, true for black, false for white.
* #return Returns true if this direction has pieces to be flipped, false otherwise.
*/
public boolean directionValid(int xt, int yt, int i, int j, boolean bTurn)
{
return true;
}
/**
* Places a game piece on the current cell for the current player. Also flips the
* appropriate neighboring game pieces, checking the 8 possible directions from the
* current cell.
*/
public void playAndFlipTiles ( )
{
board[x][y].setBlack(blackTurn);
board[x][y].playIt();
// To be completed by you.
}
/**
* A helper method for playAndFlipTiles. Flips pieces in a given direction. The
* directions are as follows:
* (1,1) is up and right
* (1,0) is right
* (1,-1) is down and right
* (0,-1) is down
* (-1,-1) is down and left
* (-1,0) is left
* (-1,1) is left and up
* (0,1) is up
* #param xt The horizontal coordinate value in the board.
* #param yt The vertical coordinate value in the board.
* #param i -1 is left, 0 is neutral, 1 is right,
* #param j -1 is down, - is neutral, 1 is up.
*/
public void flipAllInThatDirection(int xt, int yt, int i, int j)
{
}
/**
* Counts the white pieces on the board, and the black pieces on the board.
* Displays these numbers toward the top of the board, for the current state
* of the board. Also prints whether it is "BLACK'S TURN" or "WHITE'S TURN"
* or "GAME OVER".
*/
/* COMPLETE */
public void countScoreAnddrawScoreBoard ( )
{
int whiteCount = 0, blackCount = 0;
for(int i = 0; i < board.length; i++)
{
for(int j = 0; j < board[i].length; j++)
{
if(board[i][j].hasBeenPlayed())
{
if(board[i][j].getBlackStatus())
{
blackCount++;
}
else
{
whiteCount++;
}
}
}
}
drawScoresAndMessages(whiteCount,blackCount);
}
/**
* A helper method for countScoreAnddrawScoreBoard. Draws the scores
* and messages.
* #param whiteCount The current count of the white pieces on the board.
* #param blackCount The current count of the black pieces on the board.
*/
/* COMPLETE */
public void drawScoresAndMessages(int whiteCount, int blackCount)
{
StdDraw.setPenColor(new Color(0,0,0));
StdDraw.filledRectangle(0.41,1.05,0.055,0.045);
StdDraw.filledRectangle(0.80,1.05,0.055,0.045);
StdDraw.filledRectangle(0.76,1.19,0.11,0.045);
StdDraw.setPenColor(new Color(255,255,255));
StdDraw.filledRectangle(0.41,1.05,0.05,0.04);
StdDraw.filledRectangle(0.80,1.05,0.05,0.04);
StdDraw.filledRectangle(0.76,1.19,0.105,0.04);
StdDraw.setPenColor(new Color(0,0,0));
StdDraw.text(0.24,1.04,"BLACK");
StdDraw.text(0.41,1.04,"" + blackCount);
StdDraw.text(0.63,1.04,"WHITE");
StdDraw.text(0.80,1.04,"" + whiteCount);
StdDraw.text(0.76,1.18,"RESET");
if(gameOver)
{
StdDraw.text(0.34,1.18,"GAME OVER");
}
else if(blackTurn)
{
StdDraw.text(0.34,1.18,"BLACK'S TURN");
}
else
{
StdDraw.text(0.34,1.18,"WHITE'S TURN");
}
}
/**
* Checks to see if black can play. Checks to see if white can play.
* If neither can play, the game is over. If black can't go, then set
* blackTurn to false. If white can't go, set blackTurn to true.
* #return Returns true if the game is over, false otherwise.
*/
/* COMPLETE */
public boolean checkTurnAndGameOver ( )
{
boolean whiteCanGo = false, blackCanGo = false;
// To be completed by you.
return false;
}
}
/**
* Represents a single cell in the game of Othello. By default, a cell is black, and
* has not been played. When a game piece is "placed" on the board, the boolean played
* is set to true. If the game piece is black, then the boolean black is true, and if
* the game piece is white, then the boolean black is false. The ints x and y
* represent the coordinate values of the cell within the game board, with the lower
* left at (0,0) and the upper right at (7,7).
*/
class OthelloCell
{
/** The coordinates of the active piece on the board. */
private int x, y;
/** Booleans indicating if a piece has been played (or is empty), and indicating
* if the piece is black (or white) */
private boolean played, black;
/**
* Creates an OthelloCell object, at the given coordinate pair.
* #param i The horizontal coordinate value for the cell on the board.
* #param j The vertical coordinate value for the cell on the board.
*/
/* COMPLETE */
public OthelloCell(int i, int j)
{
played = false;
x = i;
y = j;
black = true;
}
/**
* Draws the cell on the board, in its current state.
*/
/* COMPLETE */
public void drawCell ( )
{
StdDraw.setPenColor(new Color(0,0,0));
StdDraw.filledSquare(0.15 + 0.1 * x, 0.15 + 0.1 * y, 0.05);
StdDraw.setPenColor(new Color(0,110,0));
StdDraw.filledSquare(0.15 + 0.1 * x, 0.15 + 0.1 * y, 0.048);
if(played)
{
for(int i = 0; i <= 20; i++)
{
if(black)
{
StdDraw.setPenColor(new Color(5+8*i,5+8*i,5+8*i));
}
else
{
StdDraw.setPenColor(new Color(255-8*i,255-8*i,255-8*i));
}
StdDraw.filledCircle(0.15 + 0.1 * x - i*0.001, 0.15 + 0.1 * y + i*0.001, 0.043-i*0.002);
}
}
}
/**
* Sets the piece to black (black true) or white (black false).
* #param bool The value to be assigned to the game piece.
*/
/* COMPLETE */
public void setBlack(boolean bool)
{
if(bool)
{
black = true;
}
else
{
black = false;
}
}
/**
* Return the status of black; true for a black piece, false for a white piece.
* #return Returns true for a black piece, false for a white piece.
*/
/* COMPLETE */
public boolean getBlackStatus ( )
{
return black;
}
/**
* Sets the value of played to true, to indicate that a piece has been placed on this cell.
*/
/* COMPLETE */
public void playIt ( )
{
played = true;
}
/**
* Return the status of played, indicating whether or not there is a game piece on this cell.
* #return Returns true if a game piece is on this cell, false otherwise.
*/
/* COMPLETE */
public boolean hasBeenPlayed ( )
{
return played;
}
}
You can get the 8 adjacent cells using two different arrays. These arrays are used to get row and column numbers of 8 neighbors of a given cell
int rowNbr[] = new int[] {-1, -1, -1, 0, 0, 1, 1, 1};
int colNbr[] = new int[] {-1, 0, 1, -1, 1, -1, 0, 1};
And iterate the given matrix by adding the current row/col to above arrays like :
for (int k = 0; k < 8; ++k) {
sop(matrix[row + rowNbr[k], col + colNbr[k]])
}
Also,you might want to check https://www.geeksforgeeks.org/find-number-of-islands/
Hope this will get you the further thought process. Thnx
This is my approach, although its in C# I am sure its of some use.
Also uses part of the solution from Ashutosh.
My Board is the two dimensional array "pieces", lowercase "length" is just the size of the board and num is an indicator for a color: Empty is 0, num is whats currently being played, 1 for White and 2 for Black.
All its doing is looking for the closest matching color in either direction without empty spaces inbetween and then placing the current playing color in all the array spaces inbetween.
This can probably be done way smarter, I dont even like my approach of always checking for the full size of the field in every direction and just ignoring index out of range exceptions, but it was the simplest
int[] rowNbr = { -1, -1, -1, 0, 0, 1, 1, 1 };
int[] colNbr = { -1, 0, 1, -1, 1, -1, 0, 1 };
for (int x = 0; x < 8; x++)
{
int facX = rowNbr[x];
int facY = colNbr[x];
try
{
for (int i = 1; i < length; i++)
{
if (pieces[click.X + i * facX, click.Y + i * facY] == 0) break;
if (pieces[click.X + i * facX, click.Y + i * facY] == (byte)num)
{
for (int j = i - 1; j > 0; j--)
{
pieces[click.X + j * facX, click.Y + j * facY] = (byte)num;
}
break;
}
}
}
catch { }
}
I understand the concept but I have no idea how to write the code out in java. From my understanding you travel down to check if the next node is a leaf, if not you keep going down, then you go back up and do it for the others. But how do I code this?
Here's my constructor for the quadtree
public class QuadtreeBitmap {
// location
private final int x;
private final int y;
// height and width
private final int size;
// if leaf
private boolean leaf;
// either Colour.BLACK or Colour.WHITE
private Colour colour;
// otherwise
private QuadtreeBitmap northWest;
private QuadtreeBitmap northEast;
private QuadtreeBitmap southWest;
private QuadtreeBitmap southEast;
/**
* Constructs a new quadtree bitmap with height and width equal to the specified size, and
* every pixel initialized to the given colour. The specified size must be a power of 2,
* and must be greater than zero.
*
* #param size the height and width of this quadtree bitmap
* #param colour the colour with which to initialize every pixel in this quadtree bitmap
*/
public QuadtreeBitmap(int size, Colour colour) {
this(0, 0, size, colour);
}
/**
* Constructs a new quadtree bitmap with height and width equal to the specified size, and
* every pixel initialized to white. The specified size must be a power of 2, and must be
* greater than zero.
*
* #param size the height and width of this quadtree bitmap
*/
public QuadtreeBitmap(int size) {
this(0, 0, size, Colour.WHITE);
}
// specifying location only supported internally
private QuadtreeBitmap(int x, int y, int size, Colour colour) {
// only supporting power-of-2 dimensions
if (!powerOfTwo(size)) {
throw new IllegalArgumentException("Size not power of 2.");
}
this.x = x;
this.y = y;
this.size = size;
this.leaf = true;
this.colour = colour;
this.northWest = null;
this.northEast = null;
this.southWest = null;
this.southEast = null;
}
// combining quads to form tree only supported internally, assumes well-positioned
private QuadtreeBitmap(int x, int y, int size, List<QuadtreeBitmap> quads) {
this(x, y, size, Colour.WHITE);
northWest = quads.get(0);
northEast = quads.get(1);
southWest = quads.get(2);
southEast = quads.get(3);
this.leaf = false;
}
// for any basic task which needs to be repeated all four quadrants
private List<QuadtreeBitmap> quadrants() {
return Arrays.asList(northWest, northEast, southWest, southEast);
}
// retrieves the quadrant within which the specified location lies
private QuadtreeBitmap quadrantOf(int x, int y) {
for (QuadtreeBitmap quad : quadrants()) {
if (quad.containsPoint(x, y)) {
return quad;
}
}
return null;
}
public int getSize() {
return size;
}
Essentially I need to implement a whole bunch of methods for an assignment, like count pixels of certain colour, etc but I have no idea on how to get started
Let's simplify. How would you write a traversal on a binary tree?
Well, you'd write a function like
public int CountNodes(){
int leftcount = (this.left==null) ? 0 : this.left.CountNodes();
int rightcount = (this.right==null) ? 0 : this.right.CountNodes();
return 1 + leftcount + rightcount;
}
So you want to implement this with your fixed internal values northEast, northWest, southEast, southWest instead of 'left' and 'right'. Notice that the +1 in the node value accounts for the node itself, making an explicit 'leaf check' unnecessary.
It should be mentioned that you need to be aware of stack size limits in your environment. Foxpro used to have a limited stack height of 32 calls, and recursive calls like this can get deep with very large subject materials.
Hello Stack Community,
I thought long and hard about posting this seeing as I did not want to attract yet another "duplicate" thread. However I have run out of ideas and do not know of any forums or other stacks where I could post this to get some help.
I wrote this application as a fun project in an attempt to generate some height-maps. However whenever I try to generate more than one height-map at a time all my duplicates appear as either black voids or if the MAP_SIZE variable is low enough white voids. (Example, 16 && 33 create white voids, 1025 creates black)
My output folder appears as follows: low value vrs higher value
Why is this? Is it simply a mathematical fluke that I am missing at 3:15 am?
I wrote the printMap specifically for the function of checking the values of the map data and while they are within ranges that would designate them to be black/white. I see no reason for this to exist continuously after the first iteration.
Just for fun I printed 44 more maps, and after the first one they all were black, MAP_SIZE was set at 1025. Feel free to check this out yourselves.
I created my diamond square algorithm based off my readings from here: http://www.gameprogrammer.com/fractal.html#heightmaps
And my greyWriteImage from a older stack overflow thread about simplex noise maps.
EDIT
Thanks to I was able to solve my problem, turns out it was just a simple fact that for each new map you attempted to create using the populateMap function I forgot to reset avgOffset to 1. Essentially the problem was you were dividing the avgOffset continuously by 2 getting smaller and smaller results, which always which would always be cast a certain way.
Below I have included my completed source code for anyone who would like to work with my algorithm and output. Have fun.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import java.util.concurrent.ThreadLocalRandom;
public class generateHeightMap {
// https://stackoverflow.com/questions/43179809/diamond-square-improper-implementation
private static final Random RAND = new Random();
// Size of map to generate, must be a value of (2^n+1), ie. 33, 65, 129
// 257,1025 are fun values
private static final int MAP_SIZE = 1025;
// initial seed for corners of map
private static final double SEED = ThreadLocalRandom.current().nextInt(0, 1 + 1);
// average offset of data between points
private static double avgOffSetInit = 1;
private static final String PATH = "C:\\Users\\bcm27\\Desktop\\grayScale_export";
private static String fileName = "\\grayscale_map00.PNG";
public generateHeightMap(int howManyMaps) {
System.out.printf("Seed: %s\nMap Size: %s\nAverage Offset: %s\n",
SEED, MAP_SIZE, avgOffSetInit);
System.out.println("-------------------------------------------");
for(int i = 1; i <= howManyMaps; i++){ // how many maps to generate
double[][] map = populateMap(new double[MAP_SIZE][MAP_SIZE]);
//printMap(map);
generateHeightMap.greyWriteImage(map);
fileName = "\\grayscale_map0" + i + ".PNG";
System.out.println("Output: " + PATH + fileName);
}
}
/*************************************************************************************
* #param requires a 2d map array of 0-1 values, and a valid file path
* #post creates a image file saved to path + file_name
************************************************************************************/
private static void greyWriteImage(double[][] data) {
BufferedImage image =
new BufferedImage(data.length, data[0].length, BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < data[0].length; y++)
{
for (int x = 0; x < data.length; x++)
{// for each element in the data
if (data[x][y]>1){
// tells the image whether its white
data[x][y]=1;
}
if (data[x][y]<0){
// tells the image whether its black
data[x][y]=0;
}
Color col = // RBG colors
new Color((float)data[x][y],
(float)data[x][y],
(float)data[x][y]);
// sets the image pixel color equal to the RGB value
image.setRGB(x, y, col.getRGB());
}
}
try {
// retrieve image
File outputfile = new File( PATH + fileName);
outputfile.createNewFile();
ImageIO.write(image, "png", outputfile);
} catch (IOException e) {
throw new RuntimeException("I didn't handle this very well. ERROR:\n" + e);
}
}
/****************************************************************************
* #param requires map double[MAPSIZE][MAPSIZE]
* #return returns populated map
*
* [1] Taking a square of four points, generate a random value at the square
* midpoint, where the two diagonals meet. The midpoint value is calcul-
* ated by averaging the four corner values, plus a random amount. This
* gives you diamonds when you have multiple squares arranged in a grid.
*
* [2] Taking each diamond of four points, generate a random value at the
* center of the diamond. Calculate the midpoint value by averaging the
* corner values, plus a random amount generated in the same range as
* used for the diamond step. This gives you squares again.
*
* '*' equals a new value
* '=' equals a old value
*
* * - - - * = - - - = = - * - = = - = - = = * = * =
* - - - - - - - - - - - - - - - - * - * - * = * = *
* - - - - - - - * - - * - = - * = - = - = = * = * =
* - - - - - - - - - - - - - - - - * - * - * = * = *
* * - - - * = - - - = = - * - = = - = - = = * = * =
* A B C D E
*
* A: Seed corners
* B: Randomized center value
* C: Diamond step
* D: Repeated square step
* E: Inner diamond step
*
* Rinse and repeat C->D->E until data map is filled
*
***************************************************************************/
private static double[][] populateMap(double[][] map) {
// assures us we have a fresh map each time
double avgOffSet = avgOffSetInit;
// assigns the corners of the map values to SEED
map[0][0] =
map[0][MAP_SIZE-1] =
map[MAP_SIZE-1][0] =
map[MAP_SIZE-1][MAP_SIZE-1] = SEED;
// square and diamond loop start
for(int sideLength = MAP_SIZE-1; sideLength >= 2; sideLength /=2,avgOffSet/= 2.0) {
int halfSide = sideLength / 2;
double avgOfPoints;
/********************************************************************
* [1] SQUARE FRACTAL [1]
*********************************************************************/
// loops through x & y values of the height map
for(int x = 0; x < MAP_SIZE-1; x += sideLength) {
for(int y = 0; y <MAP_SIZE-1; y += sideLength) {
avgOfPoints = map[x][y] + //top left point
map[x + sideLength][y] + //top right point
map[x][y + sideLength] + //lower left point
map[x + sideLength][y + sideLength];//lower right point
// average of surrounding points
avgOfPoints /= 4.0;
// random value of 2*offset subtracted
// by offset for range of +/- the average
map[x+halfSide][y+halfSide] = avgOfPoints +
(RAND.nextDouble()*2*avgOffSet) - avgOffSet;
}
}
/********************************************************************
* [2] DIAMOND FRACTAL [2]
*********************************************************************/
for(int x=0; x < MAP_SIZE-1; x += halfSide) {
for(int y = (x + halfSide) % sideLength; y < MAP_SIZE-1;
y += sideLength) {
avgOfPoints =
map[(x - halfSide + MAP_SIZE) % MAP_SIZE][y] +//left of center
map[(x + halfSide) % MAP_SIZE][y] + //right of center
map[x][(y + halfSide) % MAP_SIZE] + //below center
map[x][(y - halfSide + MAP_SIZE) % MAP_SIZE]; //above center
// average of surrounding values
avgOfPoints /= 4.0;
// in range of +/- offset
avgOfPoints += (RAND.nextDouble()*2*avgOffSet) - avgOffSet;
//update value for center of diamond
map[x][y] = avgOfPoints;
// comment out for non wrapping values
if(x == 0) map[MAP_SIZE-1][y] = avgOfPoints;
if(y == 0) map[x][MAP_SIZE-1] = avgOfPoints;
} // end y
} // end x
} // end of diamond
return map;
} // end of populateMap
/*************************************************************************************
* #param requires a 2d map array to print the values of at +/-0.00
************************************************************************************/
#SuppressWarnings("unused")
private static void printMap(double[][] map) {
System.out.println("---------------------------------------------");
for (int x = 0; x < map.length; x++) {
for (int y = 0; y < map[x].length; y++) {
System.out.printf("%+.2f ", map[x][y] );
}
System.out.println();
}
}
} // end of class
Is it possible that avgOffSet must be initialized before creating each map (start of populateMap)?
It is being divided by 2 but never reset to 1. I suppose each map is independent, that is, does not depend on the previous one, so there is no reason to not reset the variable. But I do not know that algorithm and have no time to learn it... [:-|
private static double[][] populateMap(double[][] map) {
avgOffSet = 1; // missing this one
map[0][0] = ...
if this is correct I would suggest that avgOffset should be a variable; eventually create a field avgOffsetInitial with the initial value (instead of the current field).
I am at wits end with this problem.
Please note I am a really novice coder (although I'm sure you will see by my code).
The basics:
I have an image that I would like to count the number of objects in. Objects in this instance are just joined up pixels (the image has been threshold-ed and undergone binarization and binary erosion to get to this stage, code not included).
My problem:
I am trying to write some code to count how many objects there are left in this image, and within that method I call another method which is meant to remove any objects that have already been included by searching for neighbouring pixels to which they are attached. However, my current implementation of this removal method is throwing up an error: "coordinates out of bounds". I'm asking for any help solving this issue.
Code for overall object counting:
/**
* countObjects in image
*
* #param binary image to count objects in
* #param original image to put labels on
*
* #return labelled original image for graphics overlay
*/
public static BufferedImage countObjects(BufferedImage image, BufferedImage original){
BufferedImage target = copyImage(image);
int rgbBand = 0;
boolean finished = false;
Graphics labelColour = original.getGraphics();
labelColour.setColor(Color.RED);
while(!finished){
finished = false;
for ( int i=0; i<= target.getRaster().getWidth() - 1; i++ ) {
for( int j=0; j< target.getRaster().getHeight() - 1; j++ ) {
int clrz = target.getRaster().getSample(i, j, rgbBand);
if (clrz == 1) {
System.out.println(clrz);
removeObject(i, j, target);
labelColour.drawString( ""+count, i, j);
finished=true;
}
}
}
}
return original;
Code for object removal:
/**
*
* #param x
* #param y
* #param newImage
*
*/
private static void removeObject( int x, int y, BufferedImage newImage ){
int rgbBand = 0;
int[] zero = new int[] { 0 };
newImage.getRaster().setPixel(x, y, zero);
for (int a = Math.max(0, x - 1); a <= Math.min(x + 1, newImage.getRaster().getWidth()); a++) {
for (int b = Math.max(0, y - 1); b <= Math.min(y + 1, newImage.getRaster().getHeight()); b++) {
int na = a;
int nb = b;
if (newImage.getRaster().getSample(na, nb, rgbBand) == 1) {
removeObject( nc, nd, newImage );
}
}
}
}
In the above removeObject method, I am trying to use a recursive technique to remove pixel coordinates from the image being counted once either they or neighbouring pixels have been labelled.
If any of this is unclear (and I know there are probably more than a few confusing parts of my code, please ask and I will explain further).
Thanks for any help.
I dont have enough reputation to comment hence writing my comment as answer .
Are u sure u dint messed up with the x and y coordinates ?I had faced a similar problem some time ago ,but I had messed up with height and width of the image.
I need a little help on an image analysis algorithm in Java. I basically have images like this:
So, as you might guessed, I need to count the lines.
What approach do you think would be best?
Thanks,
Smaug
A simple segmentation algorithm can help you out. Heres how the algorithm works:
scan pixels from left to right and
record the position of the first
black (whatever the color of your
line is) pixel.
carry on this process
unless you find one whole scan when
you don't find the black pixel.
Record this position as well.
We are
just interested in the Y positions
here. Now using this Y position
segment the image horizontally.
Now
we are going to do the same process
but this time we are going to scan
from top to bottom (one column at a
time) in the segment we just created.
This time we are interested in X
positions.
So in the end we get every
lines extents or you can say a
bounding box for every line.
The
total count of these bounding boxes
is the number of lines.
You can do many optimizations in the algorithm according to your needs.
package ac.essex.ooechs.imaging.commons.edge.hough;
import java.awt.image.BufferedImage;
import java.awt.*;
import java.util.Vector;
import java.io.File;
/**
* <p/>
* Java Implementation of the Hough Transform.<br />
* Used for finding straight lines in an image.<br />
* by Olly Oechsle
* </p>
* <p/>
* Note: This class is based on original code from:<br />
* http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm
* </p>
* <p/>
* If you represent a line as:<br />
* x cos(theta) + y sin (theta) = r
* </p>
* <p/>
* ... and you know values of x and y, you can calculate all the values of r by going through
* all the possible values of theta. If you plot the values of r on a graph for every value of
* theta you get a sinusoidal curve. This is the Hough transformation.
* </p>
* <p/>
* The hough tranform works by looking at a number of such x,y coordinates, which are usually
* found by some kind of edge detection. Each of these coordinates is transformed into
* an r, theta curve. This curve is discretised so we actually only look at a certain discrete
* number of theta values. "Accumulator" cells in a hough array along this curve are incremented
* for X and Y coordinate.
* </p>
* <p/>
* The accumulator space is plotted rectangularly with theta on one axis and r on the other.
* Each point in the array represents an (r, theta) value which can be used to represent a line
* using the formula above.
* </p>
* <p/>
* Once all the points have been added should be full of curves. The algorithm then searches for
* local peaks in the array. The higher the peak the more values of x and y crossed along that curve,
* so high peaks give good indications of a line.
* </p>
*
* #author Olly Oechsle, University of Essex
*/
public class HoughTransform extends Thread {
public static void main(String[] args) throws Exception {
String filename = "/home/ooechs/Desktop/vase.png";
// load the file using Java's imageIO library
BufferedImage image = javax.imageio.ImageIO.read(new File(filename));
// create a hough transform object with the right dimensions
HoughTransform h = new HoughTransform(image.getWidth(), image.getHeight());
// add the points from the image (or call the addPoint method separately if your points are not in an image
h.addPoints(image);
// get the lines out
Vector<HoughLine> lines = h.getLines(30);
// draw the lines back onto the image
for (int j = 0; j < lines.size(); j++) {
HoughLine line = lines.elementAt(j);
line.draw(image, Color.RED.getRGB());
}
}
// The size of the neighbourhood in which to search for other local maxima
final int neighbourhoodSize = 4;
// How many discrete values of theta shall we check?
final int maxTheta = 180;
// Using maxTheta, work out the step
final double thetaStep = Math.PI / maxTheta;
// the width and height of the image
protected int width, height;
// the hough array
protected int[][] houghArray;
// the coordinates of the centre of the image
protected float centerX, centerY;
// the height of the hough array
protected int houghHeight;
// double the hough height (allows for negative numbers)
protected int doubleHeight;
// the number of points that have been added
protected int numPoints;
// cache of values of sin and cos for different theta values. Has a significant performance improvement.
private double[] sinCache;
private double[] cosCache;
/**
* Initialises the hough transform. The dimensions of the input image are needed
* in order to initialise the hough array.
*
* #param width The width of the input image
* #param height The height of the input image
*/
public HoughTransform(int width, int height) {
this.width = width;
this.height = height;
initialise();
}
/**
* Initialises the hough array. Called by the constructor so you don't need to call it
* yourself, however you can use it to reset the transform if you want to plug in another
* image (although that image must have the same width and height)
*/
public void initialise() {
// Calculate the maximum height the hough array needs to have
houghHeight = (int) (Math.sqrt(2) * Math.max(height, width)) / 2;
// Double the height of the hough array to cope with negative r values
doubleHeight = 2 * houghHeight;
// Create the hough array
houghArray = new int[maxTheta][doubleHeight];
// Find edge points and vote in array
centerX = width / 2;
centerY = height / 2;
// Count how many points there are
numPoints = 0;
// cache the values of sin and cos for faster processing
sinCache = new double[maxTheta];
cosCache = sinCache.clone();
for (int t = 0; t < maxTheta; t++) {
double realTheta = t * thetaStep;
sinCache[t] = Math.sin(realTheta);
cosCache[t] = Math.cos(realTheta);
}
}
/**
* Adds points from an image. The image is assumed to be greyscale black and white, so all pixels that are
* not black are counted as edges. The image should have the same dimensions as the one passed to the constructor.
*/
public void addPoints(BufferedImage image) {
// Now find edge points and update the hough array
for (int x = 0; x < image.getWidth(); x++) {
for (int y = 0; y < image.getHeight(); y++) {
// Find non-black pixels
if ((image.getRGB(x, y) & 0x000000ff) != 0) {
addPoint(x, y);
}
}
}
}
/**
* Adds a single point to the hough transform. You can use this method directly
* if your data isn't represented as a buffered image.
*/
public void addPoint(int x, int y) {
// Go through each value of theta
for (int t = 0; t < maxTheta; t++) {
//Work out the r values for each theta step
int r = (int) (((x - centerX) * cosCache[t]) + ((y - centerY) * sinCache[t]));
// this copes with negative values of r
r += houghHeight;
if (r < 0 || r >= doubleHeight) continue;
// Increment the hough array
houghArray[t][r]++;
}
numPoints++;
}
/**
* Once points have been added in some way this method extracts the lines and returns them as a Vector
* of HoughLine objects, which can be used to draw on the
*
* #param percentageThreshold The percentage threshold above which lines are determined from the hough array
*/
public Vector<HoughLine> getLines(int threshold) {
// Initialise the vector of lines that we'll return
Vector<HoughLine> lines = new Vector<HoughLine>(20);
// Only proceed if the hough array is not empty
if (numPoints == 0) return lines;
// Search for local peaks above threshold to draw
for (int t = 0; t < maxTheta; t++) {
loop:
for (int r = neighbourhoodSize; r < doubleHeight - neighbourhoodSize; r++) {
// Only consider points above threshold
if (houghArray[t][r] > threshold) {
int peak = houghArray[t][r];
// Check that this peak is indeed the local maxima
for (int dx = -neighbourhoodSize; dx <= neighbourhoodSize; dx++) {
for (int dy = -neighbourhoodSize; dy <= neighbourhoodSize; dy++) {
int dt = t + dx;
int dr = r + dy;
if (dt < 0) dt = dt + maxTheta;
else if (dt >= maxTheta) dt = dt - maxTheta;
if (houghArray[dt][dr] > peak) {
// found a bigger point nearby, skip
continue loop;
}
}
}
// calculate the true value of theta
double theta = t * thetaStep;
// add the line to the vector
lines.add(new HoughLine(theta, r));
}
}
}
return lines;
}
/**
* Gets the highest value in the hough array
*/
public int getHighestValue() {
int max = 0;
for (int t = 0; t < maxTheta; t++) {
for (int r = 0; r < doubleHeight; r++) {
if (houghArray[t][r] > max) {
max = houghArray[t][r];
}
}
}
return max;
}
/**
* Gets the hough array as an image, in case you want to have a look at it.
*/
public BufferedImage getHoughArrayImage() {
int max = getHighestValue();
BufferedImage image = new BufferedImage(maxTheta, doubleHeight, BufferedImage.TYPE_INT_ARGB);
for (int t = 0; t < maxTheta; t++) {
for (int r = 0; r < doubleHeight; r++) {
double value = 255 * ((double) houghArray[t][r]) / max;
int v = 255 - (int) value;
int c = new Color(v, v, v).getRGB();
image.setRGB(t, r, c);
}
}
return image;
}
}
Source: http://vase.essex.ac.uk/software/HoughTransform/HoughTransform.java.html
I've implemented a simple solution (must be improved) using Marvin Framework that finds the vertical lines start and end points and prints the total number of lines found.
Approach:
Binarize the image using a given threshold.
For each pixel, if it is black (solid), try to find a vertical line
Save the x,y, of the start and end points
The line has a minimum lenght? It is an acceptable line!
Print the start point in red and the end point in green.
The output image is shown below:
The programs output:
Vertical line fount at: (74,9,70,33)
Vertical line fount at: (113,9,109,31)
Vertical line fount at: (80,10,76,32)
Vertical line fount at: (137,11,133,33)
Vertical line fount at: (163,11,159,33)
Vertical line fount at: (184,11,180,33)
Vertical line fount at: (203,11,199,33)
Vertical line fount at: (228,11,224,33)
Vertical line fount at: (248,11,244,33)
Vertical line fount at: (52,12,50,33)
Vertical line fount at: (145,13,141,35)
Vertical line fount at: (173,13,169,35)
Vertical line fount at: (211,13,207,35)
Vertical line fount at: (94,14,90,36)
Vertical line fount at: (238,14,236,35)
Vertical line fount at: (130,16,128,37)
Vertical line fount at: (195,16,193,37)
Vertical lines total: 17
Finally, the source code:
import java.awt.Color;
import java.awt.Point;
import marvin.image.MarvinImage;
import marvin.io.MarvinImageIO;
import marvin.plugin.MarvinImagePlugin;
import marvin.util.MarvinPluginLoader;
public class VerticalLineCounter {
private MarvinImagePlugin threshold = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.thresholding");
public VerticalLineCounter(){
// Binarize
MarvinImage image = MarvinImageIO.loadImage("./res/lines.jpg");
MarvinImage binImage = image.clone();
threshold.setAttribute("threshold", 127);
threshold.process(image, binImage);
// Find lines and save an output image
MarvinImage imageOut = findVerticalLines(binImage, image);
MarvinImageIO.saveImage(imageOut, "./res/lines_out.png");
}
private MarvinImage findVerticalLines(MarvinImage binImage, MarvinImage originalImage){
MarvinImage imageOut = originalImage.clone();
boolean[][] processedPixels = new boolean[binImage.getWidth()][binImage.getHeight()];
int color;
Point endPoint;
int totalLines=0;
for(int y=0; y<binImage.getHeight(); y++){
for(int x=0; x<binImage.getWidth(); x++){
if(!processedPixels[x][y]){
color = binImage.getIntColor(x, y);
// Black?
if(color == 0xFF000000){
endPoint = getEndOfLine(x,y,binImage,processedPixels);
// Line lenght threshold
if(endPoint.x - x > 5 || endPoint.y - y > 5){
imageOut.fillRect(x-2, y-2, 5, 5, Color.red);
imageOut.fillRect(endPoint.x-2, endPoint.y-2, 5, 5, Color.green);
totalLines++;
System.out.println("Vertical line fount at: ("+x+","+y+","+endPoint.x+","+endPoint.y+")");
}
}
}
processedPixels[x][y] = true;
}
}
System.out.println("Vertical lines total: "+totalLines);
return imageOut;
}
private Point getEndOfLine(int x, int y, MarvinImage image, boolean[][] processedPixels){
int xC=x;
int cY=y;
while(true){
processedPixels[xC][cY] = true;
processedPixels[xC-1][cY] = true;
processedPixels[xC-2][cY] = true;
processedPixels[xC-3][cY] = true;
processedPixels[xC+1][cY] = true;
processedPixels[xC+2][cY] = true;
processedPixels[xC+3][cY] = true;
if(getSafeIntColor(xC,cY,image) < 0xFF000000){
// nothing
}
else if(getSafeIntColor(xC-1,cY,image) == 0xFF000000){
xC = xC-2;
}
else if(getSafeIntColor(xC-2,cY,image) == 0xFF000000){
xC = xC-3;
}
else if(getSafeIntColor(xC+1,cY,image) == 0xFF000000){
xC = xC+2;
}
else if(getSafeIntColor(xC+2,cY,image) == 0xFF000000){
xC = xC+3;
}
else{
return new Point(xC, cY);
}
cY++;
}
}
private int getSafeIntColor(int x, int y, MarvinImage image){
if(x >= 0 && x < image.getWidth() && y >= 0 && y < image.getHeight()){
return image.getIntColor(x, y);
}
return -1;
}
public static void main(String args[]){
new VerticalLineCounter();
System.exit(0);
}
}
It depends on how much they look like that.
Bring the image to 1-bit (black and white) in a way that preserves the lines and brings the background to pure white
Perhaps do simple cleanup like speck removal (remove any small black components).
Then,
Find a black pixel
Use flood-fill algorithms to find its extent
See if the shape meets the criteria for being a line (lineCount++ if so)
remove it
Repeat this until there are no black pixels
A lot depends on how good you do #3, some ideas
Use Hough just on this section to check that you have one line, and that it is vertical(ish)
(after #1) rotate it to the vertical and check its width/height ratio