hammoudeh_puzzle package

Submodules

hammoudeh_puzzle.best_buddy_image_analyzer module

Best Buddy Analyzer for Normal Images

class hammoudeh_puzzle.best_buddy_image_analyzer.ImageBestBuddyStatistics(image_filepath, piece_width, puzzle_type, distance_function)[source]

Bases: object

Class used to get the best buddy accuracy statistics for any image.

PICKLE_DIRECTORY = '.\\pickle_files\\'
analyze_piece_best_buddy_info(piece)[source]

Analyze the best buddy information for a single piece.

Parameters:piece (PuzzlePiece) – Puzzle piece whose best buddy info will be analyzed
static best_buddies_versus_accuracy_tuple(numb_bb, numb_wrong_interior_bb, numb_wrong_exterior_bb)[source]
Parameters:
  • numb_bb (int) – Total number of best buddies for a piece
  • numb_wrong_interior_bb (int) – Number of best buddies for a piece that were wrong on an internal location (i.e. where it had a neighbor)
  • numb_wrong_exterior_bb (int) – Number of best buddies for a piece that were wrong when it had no neighbor
Returns (Tuple[int]):
Tuple for accessing the numpy array
calculate_results()[source]

Calculates the best buddy accuracy results.

density

Calculates the best buddy density for the original image. It is defined as the total number of best buddies divided by the total number of possible best buddies (i.e. number of pieces multipled by the number of sides per piece).

Returns (float):
Best buddy density across the entire image.
file_extension

Returns the file extension (e.g. “jpg”, “bmp”, “png”, etc.)

Returns (str):
File extension of the original image
filename_root

Returns the file name of the original image used without file extension of path information.

Returns (str):
Filename of the original image with the file extension and file path removed.
interior_accuracy

Gets the best buddy accuracy considering only interior best buddies. It is defined as\(interior_accuracy = 1 - (numb_wrong_interior_bb)/(total_numb_interior_best_buddy)\)

Returns (float):
Best buddy accuracy considering only interior pieces.
output_results_image()[source]

Creates an image showing the best buddy accuracy distribution of an image.

print_results()[source]

Prints the best buddy results to the console.

total_accuracy

Gets the best buddy accuracy across the entire image It is defined as\(accuracy = 1 - (numb_wrong_interior_bb + numb_wrong_exterior_bb)/(total_numb_best_buddy)\)

Returns (float):
Best buddy accuracy for the entire image
total_number_of_best_buddies

Gets the total of best buddies (both interior/exterior and right/wrong).

Returns (int):
Number of best buddies in the image
hammoudeh_puzzle.best_buddy_image_analyzer.run_best_buddies_analyzer(image_file, piece_width, puzzle_type)[source]

Runs the Best Buddy Analyzer on an image and outputs the best buddy results and generates a results image.

Parameters:
  • image_file (str) – Path to an image file
  • piece_width (int) – Width of a puzzle piece in number of pixels
  • puzzle_type (PuzzleType) – Type of the puzzle to solve

hammoudeh_puzzle.best_buddy_placer module

This contains classes that will be used by the best buddy placer technique developed by Zayd Hammoudeh as an extension of Paikin and Tal’s solver.

class hammoudeh_puzzle.best_buddy_placer.BestBuddyPlacerCollection[source]

Bases: object

A container object used to store all the data used by the best buddy placer.

get_open_slot_dictionary(numb_neighbors)[source]

Gets all the open slots with the specified number of neighbors.

Parameters:numb_neighbors (int) – Number of neighbors adjacent to the set of open slots
Returns (dict):
Dictionary containing the open slots in the puzzles with the specified number of neighbors.
remove_open_slot(piece_location)[source]

After a piece is placed, this function updates the data structures in teh best buddy placer to reflect this is no longer an open slot.

Parameters:piece_location (PuzzleLocation) – Location (both (row, column) and puzzle ID) where the last piece was placed
update_open_slot(puzzle_location, side, neighbor_side_info)[source]

When a piece is placed, some set of adjacent slots will need to be updated. This performs that neighbor updating.

Parameters:
  • puzzle_location (PuzzleLocation) – Unique location of the open slot
  • side (PuzzlePieceSide) – Side of the open slot where neighbor information is going to be added.
  • neighbor_side_info (NeighborSidePair) – Information regarding the piece neighbor
class hammoudeh_puzzle.best_buddy_placer.MultisidePuzzleOpenSlot(puzzle_location)[source]

Bases: object

Represents a single open slot in a puzzle being solved.

get_neighbor_info(open_slot_side)[source]

Gets the neighbor identification number of a neighboring piece.

Parameters:open_slot_side (PuzzlePieceSide) – Side of the open slot
Returns (NeighborSidePair):
If the piece has a neighbor on the specified side, it returns a NeighborSidePair containing the neighbor id and the neighbor’s side.
key

Gets the key of a MultisidePuzzleOpenSlot object.

Returns (str):
Unique key for a multisided open slot
location

Returns the actual location of the open slot.

Returns (PuzzleLocation):
Location of the open slot
numb_neighbors

Determines the number of neighbors (i.e. pieces) directly adjacent to this open location.

Returns(int):
Number neighbors for this open slot.
update_side_neighbor_info(side, neighbor_side_info)[source]

Updates the side neighbor information for a piece.

Parameters:
  • side (PuzzlePieceSide) – Side of the open slot of interest
  • neighbor_side_info (NeighborSidePair) – Information on the neighbor including the side of the neighbor
  • is adjacent to this piece. (that) –

hammoudeh_puzzle.puzzle_importer module

Jigsaw Puzzle Object

class hammoudeh_puzzle.puzzle_importer.BestBuddyAccuracy(puzzle_id)[source]

Bases: object

Store the best buddy accuracy information for a single puzzle

add_correct_best_buddy(piece_id, side)[source]

Side of the piece where the BB is being referred.

Parameters:
  • piece_id (int) – Identification number ofr the piece of interest
  • side (PuzzlePieceSide) – Puzzle piece side of reference for the correct best buddy
add_open_best_buddy(piece_id, side)[source]

Deletes an unpaired open best buddy from the list

Parameters:
  • piece_id (int) – Piece identification number of the as of yet unpaired best buddy
  • side (PuzzlePieceSide) – Side of the unpaired best buddy
static add_piece_side_tuple_to_dict(bb_dict, piece_id, side)[source]

Adds a best buddy information to the specified best buddy dictionary.

Parameters:
  • bb_dict (dict) – Dictionary containing best buddy information
  • piece_id (int) – Identification number of the piece
  • side (PuzzlePieceSide) – Side of the piece that is referred to for best buddy.
add_wrong_best_buddy(piece_id, side)[source]

Adds a new piece and side to the list of wrong best buddies.

Args:
piece_id (int): Identification number of the piece with the wrong best buddy side (PuzzlePieceSide): Side of the piece with the wrong best buddy
static check_if_piece_side_tuple_in_dict(bb_dict, piece_id, side)[source]

Checks whether the piece and side exists in the specified best buddy dictionary.

Parameters:
  • bb_dict (dict) – Best buddy information dictionary
  • piece_id (int) – Identification number for the piece
  • side (PuzzlePieceSide) – Side of the piece where the BB is being referred.
Returns (bool):
True if the pairing of piece_id and side exists in the BB dictionary.
delete_open_best_buddy(piece_id, side)[source]

Adds an unpaired open best buddy to the list

Parameters:
  • piece_id (int) – Piece identification number of the as of yet unpaired best buddy
  • side (PuzzlePieceSide) – Side of the unpaired best buddy
exists_correct_best_buddy(piece_id, side)[source]

Checks if a pairing of a piece identification number and side exists in the pool of CORRECT best buddies.

Parameters:
  • piece_id (int) – Piece identification number
  • side (PuzzlePieceSide) – Possible neighbor side
Returns (bool):
True if the key is in the dictionary and False otherwise.
exists_open_best_buddy(piece_id, side)[source]

Checks if a pairing of a piece identification number and side exists in the pool of open best buddies.

Parameters:
  • piece_id (int) – Piece identification number
  • side (PuzzlePieceSide) – Possible neighbor side
Returns (bool):
True if the key is in the dictionary and False otherwise.
exists_wrong_best_buddy(piece_id, side)[source]

Checks if a pairing of a piece identification number and side exists in the pool of WRONG best buddies.

Parameters:
  • piece_id (int) – Piece identification number
  • side (PuzzlePieceSide) – Possible neighbor side
Returns (bool):
True if the key is in the dictionary and False otherwise.
get_piece_side_result(piece_id, side)[source]

Gets the best buddy result for the combination of puzzle piece and side.

Parameters:
  • piece_id (int) – Identification number of the piece
  • side (PuzzlePieceSide) – Side of the puzzle piece of puzzle piece of interest
Returns (PieceSideBestBuddyAccuracyResult):
Best buddy accuracy result
numb_correct_best_buddies

Gets the number of correct best buddies who are next to their best buddy

Returns (int):
Total number of correct best buddies
numb_open_best_buddies

Property to get the total number of best buddies where one of the pair has not been placed.

Returns (int):
Total number of best buddies whose best buddies have not yet been placed.
numb_wrong_best_buddies

Gets the number of correct best buddies who are NOT next to their best buddy

Returns (int):
Total number of WRONG best buddies
static piece_side_tuple_key(piece_id, side)[source]

Creates a unique dictionary key for storing the piece side tuple.

Parameters:
Returns (str):
Dictionary key in the form “<piece_id>_<side_int_value>”
class hammoudeh_puzzle.puzzle_importer.BestBuddyResultsCollection[source]

Bases: object

Stores the best buddy result accuracies in a single object.

best_buddy_accuracy

Property to get access to all the best buddy information.

Returns (List[BestBuddyAccuracy]):
The best buddy accuracy objects for all puzzles.
create_best_buddy_accuracy_for_new_puzzle(puzzle_id)[source]

Creates a best buddy accuracy for a new puzzle.

Parameters:puzzle_id (int) – Creates a new best buddy accuracy for a puzzle
output_results_images(solved_puzzles, puzzle_type, timestamp, orig_img_filename=None)[source]

Converts the results information to a data visualization to see where there are right and wrong best buddies.

Parameters:
  • solved_puzzles (List[Puzzle]) – List of puzzles.
  • puzzle_type (PuzzleType) – Type of the solved puzzle.
  • timestamp (float) – Timestamp as a floating point number. Converted to a string by this function.
  • orig_img_filename (Optional str) – Filename of the original image
print_results()[source]

Prints the best buddy accuracy information to the console.

total_best_buddy_count()[source]

Gets the total number of best buddies represented by this collection.

Returns (int):
Total number of best buddies in the collection
class hammoudeh_puzzle.puzzle_importer.DirectAccuracyPuzzleResults(original_puzzle_id, solved_puzzle_id, numb_pieces_in_original_puzzle)[source]

Bases: object

Structure used for managing puzzle placement results.

add_correct_placement(piece)[source]

Correctly Placed Piece Tracker

Adds a piece that has been placed correctly

Parameters:piece (PuzzlePiece) – Puzzle Piece that was placed CORRECTLY.
add_different_puzzle(piece)[source]

Wrong Puzzle ID Tracker

Adds a piece that was assigned to a DIFFERENT PUZZLE ID number to the tracker.

Parameters:piece (PuzzlePiece) – Puzzle Piece that was placed with the different PUZZLE IDENTIFICATION NUMBER
add_wrong_location(piece)[source]

Wrong Piece Location Tracker

Adds a piece that was assigned to the wrong location number to the tracker.

Parameters:piece (PuzzlePiece) – Piece placed in the wrong LOCATION
add_wrong_rotation(piece)[source]

Wrong Piece Rotation Tracker

Adds a piece that had the wrong rotation

Parameters:piece (PuzzlePiece) – Puzzle Piece that was placed with the wrong Rotation (i.e. not 0 degrees)
static check_if_update_direct_accuracy(current_best_direct_accuracy, new_direct_accuracy)[source]

Determines whether the current best direct accuracy should be replaced with a newly calculated direct accuracy.

Parameters:
Returns (bool):
True if the current best direct accuracy should be replaced with the new direct accuracy and False otherwise.
get_piece_result(piece_id)[source]

Gets the direct accuracy results (e.g. wrong puzzle, wrong id, wrong rotation, etc.) for an individual piece.

Parameters:piece_id (int) – Identification number of the piece
Returns (PieceDirectAccuracyResult):
Direct accuracy result for an individual piece
numb_correct_placements

Number of Pieces Placed Correctly Property

Gets the number of pieces placed correctly.

Returns (int):
Number of pieces correctly placed with the right puzzle ID, location, and rotation.
numb_different_puzzle

Number of Pieces in the Wrong Puzzle

Gets the number of pieces placed in entirely the wrong puzzle.

Returns (int):
Number of pieces placed in the wrong puzzle
numb_pieces_from_original_puzzle_in_solved_puzzle

Number of pieces from the original puzzle in the solved result

Returns (int):
Only the number of included pieces
numb_wrong_location

Number of Pieces Placed in the Wrong Location

Gets the number of pieces placed in the wrong LOCATION.

Returns (int):
Number of pieces placed in the wrong location.
numb_wrong_rotation

Number of Pieces with the Wrong Rotation

Gets the number of pieces placed with the wrong ROTATION.

Returns (int):
Number of pieces placed with the incorrect rotation (i.e. not 0 degrees)
original_puzzle_id

Direct Accuracy Original Puzzle ID Number Accessor

Returns (int):
The puzzle ID associated with the ORIGINAL set of puzzle results
solved_puzzle_id

Direct Accuracy Solved Puzzle ID Number Accessor

Returns (int):
The puzzle ID associated with the SOLVED set of puzzle pieces
total_numb_pieces_in_solved_puzzle

Total Number of Pieces in the solved image

Returns (int):
Total number of pieces (both with expected puzzle id and wrong puzzle id(s))
weighted_accuracy

Calculates and returns the weighted accuracy score for this puzzle.

Returns (float):
Weighted accuracy score for this puzzle solution
class hammoudeh_puzzle.puzzle_importer.DirectAccuracyType[source]

Bases: enum.Enum

Defines the direct accuracy types.

Modified_Direct_Accuracy = <DirectAccuracyType.Modified_Direct_Accuracy: 0>
Standard_Direct_Accuracy = <DirectAccuracyType.Modified_Direct_Accuracy: 0>
class hammoudeh_puzzle.puzzle_importer.ModifiedNeighborAccuracy(original_puzzle_id, solved_puzzle_id, number_of_pieces)[source]

Bases: object

Encapsulating structure for the modified neighbor based accuracy approach.

add_correct_neighbor(piece_id, side)[source]

Stores information on a CORRECT neighbor

Parameters:
  • piece_id (int) – Identification number of the CORRECT puzzle piece
  • side (PuzzlePieceSide) – Side of the puzzle piece with the CORRECT neighbor
add_wrong_neighbor(piece_id, side)[source]

Stores information on a wrong neighbor

Parameters:
  • piece_id (int) – Identification number of the wrong puzzle piece
  • side (PuzzlePieceSide) – Side of the puzzle piece with the wrong neighbor
add_wrong_puzzle_id(piece_id, side)[source]

Stores information on piece assigned to the wrong puzzle ID.

Parameters:
  • piece_id (int) – Identification number of the wrong puzzle piece
  • side (PuzzlePieceSide) – Side of the puzzle piece with the wrong neighbor
static check_if_update_neighbor_accuracy(current_best_neighbor_accuracy, new_neighbor_accuracy)[source]

Determines whether the current best direct accuracy should be replaced with a newly calculated direct accuracy.

Parameters:
Returns (bool):
True if accuracy should be updated and False otherwise.
correct_neighbor_count

Gets the CORRECT neighbor count for this puzzle.

Returns (int):
Number of CORRECT neighbors in the puzzle
exists_correct_neighbor(piece_id, side)[source]

Determines whether the pairing of the piece id and the side are in the CORRECT neighbors list.

Parameters:
  • piece_id (int) – Identification number of the wrong puzzle piece
  • side (PuzzlePieceSide) – Side of the puzzle piece which is being checked for a CORRECT neighbor
exists_wrong_neighbor(piece_id, side)[source]

Determines whether the pairing of the piece id and the side are in the WRONG neighbors list.

Parameters:
  • piece_id (int) – Identification number of the wrong puzzle piece
  • side (PuzzlePieceSide) – Side of the puzzle piece which is being checked for a WRONG neighbor
exists_wrong_puzzle_id(piece_id, side)[source]

Determines whether the pairing of the piece id and the side are in the WRONG PUZZLE ID list.

Parameters:
  • piece_id (int) – Identification number of the wrong puzzle piece
  • side (PuzzlePieceSide) – Side of the puzzle piece which is being checked for a WRONG PUZZLE ID
get_piece_side_result(piece_id, side)[source]

Gets the best buddy result for the combination of puzzle piece and side.

Parameters:
  • piece_id (int) – Identification number of the piece
  • side (PuzzlePieceSide) – Side of the puzzle piece of puzzle piece of interest
Returns (PieceSideBestBuddyAccuracyResult):
Best buddy accuracy result
numb_pieces_from_original_puzzle_in_solved_puzzle

Number of pieces from the original puzzle in the solved result

Returns (int):
Only the number of included pieces
numb_pieces_in_original_puzzle

Property to extract the number of pieces in the original (input) puzzle.

Returns (int):
Piece count in the original, input puzzle
original_puzzle_id

Original/Input Puzzle ID Number Property

This method is used to access puzzle identification number information of the original/input puzzle.

Returns (int):
Original puzzle identification number associated with this set of modified neighbor accuracy information.
solved_puzzle_id

Solved Puzzle ID Number Property

This method is used to access puzzle identification number information of the puzzle that was output by the solved.

Returns (int):
Solved puzzle identification number associated with this set of modified neighbor accuracy information.
total_numb_pieces_in_solved_puzzle

Number of Included Pieces

This function returns the number of puzzle pieces in the solved image.

Returns (int):
Number of pieces in the solved
weighted_accuracy

Calculates and returns the weighted neighbor accuracy

Returns (float):
Weighted neighbor accuracy.
wrong_neighbor_count

Gets the wrong neighbor count for this puzzle.

Returns (int):
Number of wrong neighbors in the puzzle
wrong_puzzle_id

Gets the number of pieces assigned to the wrong puzzle

Returns (int):
Number pieces in the wrong puzzle
class hammoudeh_puzzle.puzzle_importer.PickleHelper[source]

Bases: object

The Pickle Helper class is used to simplify the importing and exporting of objects via the Python Pickle Library.

static exporter(obj, filename)[source]

Generic Pickling Exporter Method

Helper method used to export any object to a Pickle file.

::Note::: This function does not support objects of type “Puzzle.” They should use the class’ specialized Pickling functions.

Parameters:
  • obj – Object to be exported to a specified Pickle file.
  • filename (str) – Name of the Pickle file.
static importer(filename)[source]

Generic Pickling Importer Method

Helper method used to import any object from a Pickle file.

::Note::: This function does not support objects of type “Puzzle.” They should use the class’ specialized Pickling functions.

Parameters:filename (str) – Pickle Filename
Returns:The object serialized in the specified filename.
class hammoudeh_puzzle.puzzle_importer.PieceDirectAccuracyResult[source]

Bases: enum.Enum

Enumerated type used to represent the direct accuracy results for a single individual piece. Each enumerated value is a tuple representing the color of the puzzle piece in BGR format.

correct_placement = <PieceDirectAccuracyResult.correct_placement: (0, 204, 0)>
different_puzzle = <PieceDirectAccuracyResult.different_puzzle: (255, 0, 0)>
wrong_location = <PieceDirectAccuracyResult.wrong_location: (0, 0, 255)>
wrong_rotation = <PieceDirectAccuracyResult.wrong_rotation: (51, 153, 255)>
class hammoudeh_puzzle.puzzle_importer.PieceSideBestBuddyAccuracyResult[source]

Bases: enum.Enum

Enumerated type used to represent the direct accuracy results for a single individual piece. Each enumerated value is a tuple representing the color of the puzzle piece in BGR format.

correct_best_buddy = <PieceSideBestBuddyAccuracyResult.correct_best_buddy: (0, 204, 0)>
no_best_buddy = <PieceSideBestBuddyAccuracyResult.no_best_buddy: (255, 255, 255)>
open_best_buddy = <PieceSideBestBuddyAccuracyResult.open_best_buddy: (255, 0, 0)>
wrong_best_buddy = <PieceSideBestBuddyAccuracyResult.wrong_best_buddy: (0, 0, 255)>
class hammoudeh_puzzle.puzzle_importer.PieceSideNeighborAccuracyResult[source]

Bases: enum.Enum

Defines the color for tuples of piece ids and sides according to the neighbor accuracy metric.

correct_neighbor = <PieceSideNeighborAccuracyResult.correct_neighbor: (0, 204, 0)>
different_puzzle_id = <PieceSideNeighborAccuracyResult.different_puzzle_id: (255, 0, 0)>
wrong_neighbor = <PieceSideNeighborAccuracyResult.wrong_neighbor: (0, 0, 255)>
class hammoudeh_puzzle.puzzle_importer.Puzzle(id_number, image_filename=None, piece_width=None, starting_piece_id=0)[source]

Bases: object

Puzzle Object represents a single Jigsaw Puzzle. It can import a puzzle from an image file and create the puzzle pieces.

DEFAULT_PIECE_WIDTH = 25
MISSING_PIECE_PUZZLE_INFO_VALUE = -1
NUMBER_BGR_DIMENSIONS = 3
OUTPUT_IMAGE_DIRECTORY = '.\\solved\\'
assign_all_piece_id_numbers_to_original_id()[source]

Sets the piece ID number to its original ID number. Should not generally be used in a puzzle solver.

assign_all_pieces_to_original_location()[source]

Piece Correct Assignment

Assigns each piece to its original location for debug purposes.

::Note:: This should NOT be used in a solver; that would be cheating.

assign_all_pieces_to_same_rotation(rotation)[source]

Pieces Rotation Assigner

Assigns each piece to a specified, single rotation

::Note:: This should NOT be used in a solver; that would be cheating.

Parameters:rotation (PuzzlePieceRotation) – Rotation to assign to all pieces.
border_outer_stripe_width = 1
border_width = 3
build_placed_piece_info()[source]

Placed Piece Info Builder

For a puzzle, this function builds two Numpy 2D arrays. They are:

  1. Piece Locations - A Numpy 2D matrix showing the PUZZLE PIECE ID NUMBER in each puzzle location. If a puzzle
piece location has no assigned piece, then the cell is filled with the Puzzle class’s static property “MISSING_PIECE_PUZZLE_INFO_VALUE”
  1. Piece Rotations - A Numpy 2D matrix showing the ROTATION VALUE NUMBER the puzzle piece in each puzzle
location. If no puzzle piece is assigned to a specific location, then the cell is filled in with the Puzzle class’s static property “MISSING_PIECE_PUZZLE_INFO_VALUE”
Returns (Tuple[Numpy[int]]):
Location of each puzzle piece in the grid
build_puzzle_image(use_results_coloring=False)[source]

Makes a puzzle image.

Parameters:use_results_coloring (Optional bool) – If set to true, each piece’s image is not based off the original image but what was stored based off the results.
Returns (Puzzle):
Puzzle constructed from the pieces.
static create_solid_bgr_image(size, color)[source]

Solid BGR Image Creator

Creates a BGR Image (i.e. NumPy) array of the specified size.

RIGHT NOW ONLY BLACK is supported.

Parameters:
  • size ([int]) – Size of the image in height by width
  • color (ImageColor) – Solid color of the image.
Returns:

NumPy array representing a BGR image of the specified solid color

determine_modified_direct_accuracy(expected_puzzle_id, upper_left, numb_pieces_in_original_puzzle)[source]

Modified Direct Accuracy Finder

Determines the accuracy of the placement using the modified direct accuracy method where by the piece accuracy is determined by something other than the exact upper-most left piece (i.e. location (0, 0)).

Parameters:
  • expected_puzzle_id (int) – Expected puzzle identification number
  • upper_left (Tuple[int]) – In the direct method, the upper-left most location is the origin. In the
  • Direct Method", this can be a tuple in the format ("Modified) –
  • numb_pieces_in_original_puzzle (int) – Number of pieces in the original puzzle
Returns (DirectAccuracyPuzzleResults):
Information regarding the modified direct accuracy of the placement
determine_standard_direct_accuracy(expected_puzzle_id, numb_pieces_in_original_puzzle)[source]

Standard Direct Accuracy Finder

Determines the accuracy of the placement using the standard direct accuracy method.

Parameters:
  • expected_puzzle_id (int) – Expected puzzle identification number
  • numb_pieces_in_original_puzzle (int) – Number of pieces in the original puzzle
Returns (DirectAccuracyPuzzleResults):
Information regarding the direct accuracy of the placement
static display_image(img)[source]

Displays the image in a window for debug viewing.

Parameters:img – OpenCV image in the form of a Numpy array
export_with_border = True
static extract_subimage(img, upper_left, size)[source]

Given an image (in the form of a Numpy array) extract a subimage.

Parameters:
  • img – Image in the form of a numpy array.
  • upper_left ([int]) – upper left location of the image to extract
  • size ([int]) – Size of the of the sub
Returns (Numpy[int]):
Sub image as a numpy array
static get_file_extension(filename)[source]

Get the file extension of an object.

Parameters:filename (str) – Filename of an object
Returns (str):
File extension of the specified filename (without the period)
static get_filename_without_extension(filename_and_path)[source]

Get the file extension of an object.

Parameters:filename_and_path (str) – Filename of an object
Returns (str):
Filename of the object with the path and file extension removed.
get_min_and_max_row_and_columns(update_board_dimension_information)[source]

Min/Max Row and Column Finder

For a given set of pieces, this function returns the minimum and maximum of the columns and rows across all of the pieces.

Parameters:
  • update_board_dimension_information (bool) – Selectively update the board dimension information (e.g.
  • left location, grid_size, puzzle width, puzzle height, etc.). (upper) –
Returns ([int]):
Tuple in the form: (min_row, max_row, min_column, max_column)
static get_side_of_primary_adjacent_to_other_piece(primary_piece_location, other_piece_location)[source]

Given two adjacent pieces (i.e. a primary piece and an other piece), return the side of the primary piece that is adjacent (i.e. touching) the other piece.

Parameters:
  • primary_piece_location (PuzzleLocation) – Location of the primary piece
  • other_piece_location (PuzzleLocation) – Location of the other piece
Returns (PuzzlePieceSide):
Side of the primary piece adjacent to the other piece.
grid_size

Puzzle Grid Size Property

Used to get the maximum dimensions of the puzzle in number of rows by number of columns.

Returns ([int)):
Grid size of the puzzle as a tuple in the form (number_rows, number_columns)
id_number

Puzzle Identification Number

Gets the identification number for a puzzle.

Returns (int):
Identification number for the puzzle
insert_piece_into_image(piece, use_results_coloring=False)[source]

Takes a puzzle piece and converts its image into BGR then adds it to the master image.

Parameters:
  • piece (PuzzlePiece) – Puzzle piece to be inserted into the puzzle’s image.
  • use_results_coloring (Optional bool) – If set to true, each piece’s image is not based off the original image but what was stored based off the results.
static insert_subimage(master_img, upper_left, subimage)[source]

Given an image (in the form of a NumPy array), insert another image into it.

Parameters:
  • master_img – Image in the form of a NumPy array where the sub-image will be inserted
  • upper_left ([int]) – upper left location of the the master image where the sub image will be inserted
  • subimage ([int]) – Sub-image to be inserted into the master image.
Returns (Numpy[int]):
Sub image as a numpy array
static make_image_filename(image_descriptor, output_directory, puzzle_type, timestamp, orig_img_filename=None, puzzle_id=None)[source]

Builds an image file name using a set of standard parameters.

Parameters:
  • image_descriptor (str) – Descriptor of the output puzzle.
  • output_directory (str) – Path where the file should be output
  • puzzle_type (PuzzleType) – Type of the puzzle
  • timestamp (float) – Timestamp to be associated with the file
  • orig_img_filename (Optional str) – Path to the original file name
  • puzzle_id (Optional int) – Identification number of the puzzle.
Returns (str):
Image file name constructed from the specified parameters.
make_pieces(starting_id_numb=0)[source]

Puzzle Generator

Given a puzzle, this function turns the puzzle into a set of pieces.

Note: When creating the pieces, some of the source image may need to be discarded if the image size is not evenly divisible by the number of pieces specified as parameters to this function.

Parameters:
  • starting_id_numb (Optional int) – Identification number of the first piece in the puzzle. If it is not
  • it defaults to 0. (specified) –
numb_pieces

Gets the number of pieces. Note missing pieces are not counted in this statistic.

Returns (int):
Number of pieces in the puzzle
piece_width

Gets the size of a puzzle piece.

Returns (int):
Height/width of each piece in number of pixels.
pieces

Gets all of the pieces in this puzzle.

Returns (List[PuzzlePiece]):
A list of the pieces in the puzzle
print_debug_messages = True
randomize_puzzle_piece_locations()[source]

Puzzle Piece Location Randomizer

Randomly assigns puzzle pieces to different locations.

randomize_puzzle_piece_rotations()[source]

Puzzle Piece Rotation Randomizer

Assigns a random rotation to each piece in the puzzle.

static reconstruct_from_pieces(pieces, id_numb=-1, display_image=False)[source]

Constructs a puzzle from a set of pieces.

Parameters:
  • pieces ([PuzzlePiece]) – Set of puzzle pieces that comprise the puzzle.
  • id_numb (Optional int) – Identification number for the puzzle
  • display_image (Optional bool) – Select whether to display the image at the end of reconstruction
Returns (Puzzle):
Puzzle constructed from the pieces.
reset_upper_left_location()[source]

Reset Upper Left Location

“Upper Left” refers to the coordinate of the upper-leftmost piece. By running this function, you update this reference point to (0, 0)

save_to_file(filename)[source]

Save Puzzle to a File

Saves a puzzle to the specified file name.

Parameters:filename (str) – Filename and path to save the OpenCV image.
set_piece_color_for_direct_accuracy(direct_acc_results)[source]

Colorizes a piece based off the direct accuracy results.

Parameters:
class hammoudeh_puzzle.puzzle_importer.PuzzleDimensions(puzzle_id, starting_point)[source]

Bases: object

Stores the information regarding the puzzle dimensions including its top left and bottom right corners as well as its total size.

update_dimensions()[source]

Puzzle Dimensions Updater

Updates the total dimensions of the puzzle.

class hammoudeh_puzzle.puzzle_importer.PuzzleResultsCollection(pieces_partitioned_by_puzzle, image_filepaths)[source]

Bases: object

Stores all the puzzle results information in a single collection.

calculate_accuracies(solved_puzzles)[source]

Results Accuracy Calculator

Calculates the standard direct, modified direct, and modified neighbor accuracies for a set of solved puzzles.

Parameters:solved_puzzles (List[Puzzle]) – A set of solved puzzles
output_results_images(solved_puzzles, puzzle_type, timestamp)[source]

Creates images showing the results of the image.

Parameters:
  • solved_puzzles (List[Puzzle]) – A set of solved puzzles.
  • puzzle_type (PuzzleType) – Type of the solved image
  • timestamp (float) – Timestamp
print_results()[source]

Solver Accuracy Results Printer

Prints the accuracy results of a solver to the console.

results

Puzzle Results Accessor

Returns (PuzzleResultsInformation):
Puzzle results information for a single puzzle.
class hammoudeh_puzzle.puzzle_importer.PuzzleResultsInformation(puzzle_id, original_filename)[source]

Bases: object

Encapsulates all of the accuracy results information for a puzzle.

numb_pieces

Gets the piece count for an implicit puzzle id

Returns (int):
Number of pieces in original puzzle with this puzzle id
original_filename

Property for accessing an image’s filename.

Returns (str):
Original filename of the input image
resolve_direct_accuracies(puzzle)[source]

Direct Accuracy Resolver

In the case of multiple puzzles, there will be multiple direct accuracies for each

Parameters:puzzle (Puzzle) – A solved puzzle
resolve_neighbor_accuracies(puzzle)[source]

Neighbor Accuracy Resolved

This function is used to calculate the neighbor accuracy of a solved puzzle and compare it to the results of previously calculated accuracies to select the best one.

Parameters:puzzle (Puzzle) – A solved Puzzle
class hammoudeh_puzzle.puzzle_importer.PuzzleTester[source]

Bases: object

Puzzle tester class used for debugging the solver.

GRID_SIZE = (3, 3)
NUMB_PIXEL_DIMENSIONS = 3
NUMB_PUZZLE_PIECES = 9
PIECE_WIDTH = 5
TEST_ARRAY_FIRST_PIXEL_VALUE = 0
TEST_IMAGE_FILENAME = '.\\test\\test.jpg'
TEST_IMAGE_HEIGHT = 200
TEST_IMAGE_WIDTH = 300
static build_dummy_puzzle()[source]

Dummy Puzzle Builder

Using an image on the disk, this function builds a dummy puzzle using a Numpy array that is manually loaded with sequentially increasing pixel values.

Returns (Puzzle):
A puzzle where each pixel dimension from left to right sequentially increases by one.
static build_pixel_list(start_value, is_row, reverse_list=False)[source]

Pixel List Builder

Given a starting value for the first pixel in the first dimension, this function gets the pixel values in an array similar to a call to “get_row_pixels” or “get_column_pixels” for a puzzle piece.

Parameters:
  • start_value (int) – Value of the first (i.e. lowest valued) pixel’s first dimension
  • is_row (bool) – True if building a pixel list for a row and “False” if it is a column. This is used to
  • the stepping factor from one pixel to the next. (determine) –
  • reverse_list (bool) – If “True”, HIGHEST valued pixel dimension is returned in the first index of the list
  • all subsequent pixel values are monotonically DECREASING. If "False", the LOWEST valued pixel dimension (and) –
  • returned in the first index of the list and all subsequent pixel values are monotonically increasing. (is) –
Returns ([int]):
An array of individual values simulating a set of pixels
static piece_to_piece_step_size()[source]

Piece to Piece Step Size

For a given pixel’s given dimension, this function returns the number of dimensions between this pixel and the matching pixel exactly one puzzle piece away.

It is essentially the number of dimensions multiplied by the width of a puzzle piece (in pixels).

Returns (int):
Offset in dimensions.
static row_to_row_step_size()[source]

Row to Row Step Size

For a given pixel’s given dimension, this function returns the number of dimensions between this pixel and the matching pixel exactly one row below.

It is essentially the number of dimensions multiplied by the width of the original image (in pixels).

Returns (int):
Offset in dimensions.
class hammoudeh_puzzle.puzzle_importer.PuzzleType[source]

Bases: enum.Enum

Type of the puzzle to solve. Type 1 has no piece rotation while type 2 allows piece rotation.

type1 = <PuzzleType.type1: 1>
type2 = <PuzzleType.type2: 2>

hammoudeh_puzzle.puzzle_importer_tester module

Jigsaw Puzzle and Puzzle Piece Unittest Module

class hammoudeh_puzzle.puzzle_importer_tester.PuzzleImporterTester(methodName='runTest')[source]

Bases: unittest.case.TestCase

test__get_neighbor_piece_rotated_side()[source]
test_accuracy_calculator()[source]
test_calculate_placed_piece_rotation_degree_0()[source]
test_calculate_placed_piece_rotation_degree_180()[source]
test_calculate_placed_piece_rotation_degree_90()[source]
test_determine_unrotated_side()[source]
test_get_neighbor_locations_and_sides()[source]
test_neighbor_id_numbers()[source]

Test the functionality where the module gets the neighbor identification numbers for different puzzle pieces

test_puzzle_creation()[source]

Puzzle Import Parameter Checker

Checks that for an image, the parameters of the image are successfully parsed.

test_puzzle_piece_maker()[source]

Puzzle Piece Maker Checker

Checks that puzzle pieces are made as expected. It also checks the get puzzle piece row/column values.

test_puzzle_polygon()[source]
test_side_of_primary_adjacent_to_other_piece()[source]

hammoudeh_puzzle.puzzle_piece module

Created by Zayd Hammoudeh (zayd.hammoudeh@sjsu.edu)

class hammoudeh_puzzle.puzzle_piece.Location[source]

Bases: object

Location Object

Used to represent any two dimensional location in matrix row/column notation.

class hammoudeh_puzzle.puzzle_piece.PuzzlePiece(puzzle_id, location, lab_img, piece_id=None, puzzle_grid_size=None)[source]

Bases: object

Puzzle Piece Object. It is a very simple object that stores the puzzle piece’s pixel information in a NumPY array. It also stores the piece’s original information (e.g. X/Y location and puzzle ID) along with what was determined by the solver.

NUMB_LAB_COLORSPACE_DIMENSIONS = 3
actual_puzzle_id

Actual Puzzle Identification Number

Gets the actual (i.e. correct) puzzle identification number of the puzzle.

Returns (int):
Actual (correct) puzzle identification number this piece originated from.
static add_results_image_border(image)[source]

Optionally add an image border around the piece image. This is primarily intended for use with the solid results images.

Parameters:image (Numpy[int]) – Piece image with no border
Returns (Numpy[int]):
Piece image with a border around the solid image.
bgr_image()[source]

Get’s a puzzle piece’s image in the BGR colorspace.

Returns (Numpy[int]):
Numpy array of the piece’s BGR image.
border_average_color(side)[source]

Border Average Color Accessor

Gets the average color for a border piece.

Parameters:side (PuzzlePieceSide) – Side of the puzzle piece whose average value will be returned.
Returns (float):
The average pixel value for the puzzle piece border.
calculate_actual_neighbor_id_numbers(puzzle_grid_size)[source]

Neighbor ID Calculator

Given a grid size, this function calculates the identification number of this piece’s neighbors. If a piece has no neighbor, then location associated with that puzzle piece is filled with “None”.

Parameters:puzzle_grid_size ([int]) – Grid size (number of rows, number of columns) for this piece’s puzzle.
static calculate_asymmetric_distance(piece_i, piece_i_side, piece_j, piece_j_side)[source]

Uses the Asymmetric Distance function to calculate the distance between two puzzle pieces.

Parameters:
Returns (double):
Distance between the sides of two puzzle pieces.
static create_side_polygon_image(bgr_color_by_side, width, height=None)[source]

Create a solid image for displaying in output images.

Parameters:
  • bgr_color_by_side (Tuple[(Tuple[int], PuzzlePieceSide) – Color in BLUE, GREEN, RED notation for each specified puzzle piece side. Draws four triangles based off the
  • width (int) – Width of the image in pixels.
  • height (Optional int) – Height of the image in number of pixels. If it is not specified, then the image is a square.
Returns (Numpy[int]):
Image in the form of a NumPy matrix of size: (length by width by 3)
static create_solid_image(bgr_color, width, height=None)[source]

Create a solid image for displaying in output images.

Parameters:
  • bgr_color (Tuple[int]) – Color in BLUE, GREEN, RED notation. Each element for blue, green, or red must be between 0 and 255 inclusive.
  • width (int) – Width of the image in pixels.
  • height (Optional int) – Height of the image in number of pixels. If it is not specified, then the image is a square.
Returns (Numpy[int]):
Image in the form of a NumPy matrix of size: (length by width by 3)
get_column_pixels(col_numb, reverse=False)[source]

Extracts a row of pixels from a puzzle piece.

Parameters:
  • col_numb (int) – Pixel column in the image. Must be between 0 and the width of the piece - 1 (inclusive).
  • reverse (Optional bool) – Select whether to reverse the pixel information.
Returns (Numpy[int]):
A vector of 3-dimensional pixel values for a column in the image.
get_neighbor_locations_and_sides()[source]

Neighbor Locations and Sides

Given a puzzle piece, this function returns the four surrounding coordinates/location and the sides of THIS puzzle piece that corresponds to those locations so that it can be added to the open slot list.

Returns ([([int], PuzzlePieceSide)]):
Valid puzzle piece locations and the respective puzzle piece side.
get_row_pixels(row_numb, reverse=False)[source]

Extracts a row of pixels from a puzzle piece.

Parameters:
  • row_numb (int) – Pixel row in the image. Must be between 0 and the width of the piece - 1 (inclusive).
  • reverse (Optional bool) – Select whether to reverse the pixel information.
Returns (Numpy[int]):
A vector of 3-dimensional pixel values for a row in the image.
id_number

Puzzle Piece ID Getter

Gets the identification number for a puzzle piece.

Returns (int):
Puzzle piece identification number
is_correctly_placed(puzzle_offset_upper_left_location)[source]

Piece Placement Checker

Checks whether the puzzle piece is correctly placed.

Parameters:puzzle_offset_upper_left_location (Tuple[int]) – Modified location for the origin of the puzzle
Returns (bool):
True if the puzzle piece is in the correct location and False otherwise.
lab_image

Get’s a puzzle piece’s image in the LAB colorspace.

Returns (Numpy[int]):
Numpy array of the piece’s lab image.
location

Gets the location of the puzzle piece on the board.

Returns ([int]):
Tuple of the (row, column)
original_neighbor_id_numbers_and_sides

Neighbor Identification Number Property

In a puzzle, each piece has up to four neighbors. This function access that identification number information.

Returns (List[int, PuzzlePieceSide]):
Identification number for the puzzle piece on the specified side of the original object.
original_piece_id

Original Piece ID Number

Gets the original piece identification number

Returns (int):
Original identification number assigned to the piece at its creation. Should be globally unique.
puzzle_id

Assigned Puzzle Identification Number

Gets the location of the puzzle piece on the board.

Returns (int):
Assigned Puzzle ID number.
reset_image_coloring_for_polygons()[source]

Sets up the results image coloring for

results_image_coloring

Gets the results color image for the piece.

Returns(List):
Either a single BGR integer list when a solid color is used. If it is using polygon print, then the return is a List[(List[int], PuzzlePieceSide)].
results_image_polygon_coloring(side, color)[source]

Sets the image coloring when only a single color is needed.

Parameters:
  • side (PuzzlePieceSide) – Side of the piece that will be assigned a color.
  • color (List[int]) – Color of the image in BGR format
rotation

Rotation Accessor

Gets the puzzle piece’s rotation.

Returns (PuzzlePieceRotation):
The puzzle piece’s rotation
set_placed_piece_rotation(placed_side, neighbor_piece_side, neighbor_piece_rotation)[source]

Placed Piece Rotation Setter

Given an already placed neighbor piece’s adjacent side and rotation, this function sets the rotation of some newly placed piece that is put adjacent to that neighbor piece.

Parameters:
  • placed_side (PuzzlePieceSide) – Side of the placed puzzle piece that is adjacent to the neighbor piece
  • neighbor_piece_side (PuzzlePieceSide) – Side of the neighbor piece that is adjacent to the newly
  • piece. (placed) –
  • neighbor_piece_rotation (PuzzlePieceRotation) – Rotation of the already placed neighbor piece
side_adjacent_to_location(location)[source]

Given an adjacent puzzle location, this function returns the side that is touching that adjacent location.

Parameters:location (Tuple[int]) – A puzzle piece location adjacent to this piece.
Returns (PuzzlePieceSide):
Side of this piece that is touching the adjacent location
width

Gets the size of the square puzzle piece. Since it is square, width its width equals its length.

Returns (int):
Width of the puzzle piece in pixels.
class hammoudeh_puzzle.puzzle_piece.PuzzlePieceRotation[source]

Bases: enum.Enum

Puzzle Piece PieceRotation

Enumerated type for representing the amount of rotation for a puzzle piece.

Note

Pieces can only be rotated in 90 degree increments.

static all_rotations()[source]

All Rotation Accessor

Gets a list of all supported rotations for a puzzle piece. The list is ascending from 0 degrees to 270 degrees increasing.

Returns ([PuzzlePieceRotation]): List of all puzzle rotations.

degree_0 = <PuzzlePieceRotation.degree_0: 0>
degree_180 = <PuzzlePieceRotation.degree_180: 180>
degree_270 = <PuzzlePieceRotation.degree_270: 270>
degree_360 = <PuzzlePieceRotation.degree_360: 360>
degree_90 = <PuzzlePieceRotation.degree_90: 90>
static random_rotation()[source]

Random Rotation

Generates and returns a random rotation.

Returns (PuzzlePieceRotation): A random puzzle piece rotation

class hammoudeh_puzzle.puzzle_piece.PuzzlePieceSide[source]

Bases: enum.Enum

Puzzle Piece Side

Enumerated type for representing the four sides of the a puzzle piece.

Note

Pieces can only be rotated in 90 degree increments.

bottom = <PuzzlePieceSide.bottom: 2>
complementary_side

Determines and returns the complementary side of this implicit side parameter. For example, if this side is “left” then the function returns “right” and vice versa.

Returns (PuzzlePieceSide):
Complementary side of the piece.
static get_all_sides()[source]

Static method to extract all the sides of a piece.

Returns ([PuzzlePieceSide]):
List of all sides of a puzzle piece starting at the top and moving clockwise.
static get_numb_sides()[source]

Accessor for the number of sizes for a puzzle piece.

Returns (int):
Since these are rectangular pieces, it returns size 4. This is currently fixed.
left = <PuzzlePieceSide.left: 3>
right = <PuzzlePieceSide.right: 1>
side_name

Gets the name of a puzzle piece side without the class name

Returns (str):
The name of the side as a string
top = <PuzzlePieceSide.top: 0>
class hammoudeh_puzzle.puzzle_piece.SolidColor[source]

Bases: enum.Enum

Solid color in Blue, Green, Red (BGR) format.

black = <SolidColor.black: (0, 0, 0)>
white = <SolidColor.white: (255, 255, 255)>

hammoudeh_puzzle.solver_driver module

Main Puzzle Solver Driver

hammoudeh_puzzle.solver_driver.paikin_tal_driver(image_files, puzzle_type=None, piece_width=None)[source]

Runs the Paikin and Tal image solver.

Parameters:
  • image_files ([str]) – An array of one or more image file path(s).
  • puzzle_type (Optional PuzzleType) – Type of the puzzle to solve
  • piece_width (Optional int) – Width of a puzzle piece in pixels.
hammoudeh_puzzle.solver_driver.print_elapsed_time(elapsed_time, task_name)[source]

Elapsed Time Printer

Prints the elapsed time for a task in nice formatting.

Parameters:
  • elapsed_time (int) – Elapsed time in seconds
  • task_name (string) – Name of the task that was performed
hammoudeh_puzzle.solver_driver.run_paikin_tal_solver(image_files, puzzle_type, piece_width, pickle_placement_start_filename, pickle_placement_complete_filename)[source]

Paikin & Tal Solver

This function takes a set of inputs and runs the Paikin and Tal solver. It can be sped-up by importing the calculations of distances from existing Pickle files.

Parameters:
  • image_files (List[String]) – Path to the image files used to create the puzzles
  • puzzle_type (PuzzleType) – Type of the puzzle to be solved
  • piece_width (int) – Width/length of all puzzle pieces
  • pickle_placement_start_filename (String) – Filename to export a pickle file after calculating all inter-piece distances and before starting placement. If recalculating distances is disabled, then this serves as the filename to import calculated distances from.
  • pickle_placement_complete_filename (String) – Filename to e
Returns (PaikinTalSolver):
Solved Paikin & Tal result.

hammoudeh_puzzle.solver_helper_classes module

This module contains classes that would be helpful to any solver largely irrespective of the technique used by the solver.

class hammoudeh_puzzle.solver_helper_classes.NeighborSidePair(neighbor_piece_id, neighbor_side)[source]

Bases: object

Structure for storing information about a pairing of neighbor side and piece id

id_number

Gets the identification number of a neighbor piece in the neighbor side tuple.

Returns (int):
Identification number of a neighbor piece
side

Gets the side of the neighbor piece of interest.

Returns (PuzzlePieceSide):
Side of the neighbor piece
class hammoudeh_puzzle.solver_helper_classes.NextPieceToPlace(open_slot_location, next_piece_id, next_piece_side, neighbor_piece_id, neighbor_piece_side, compatibility, is_best_buddy, numb_best_buddies=None)[source]

Bases: object

Contains all the information on the next piece in the puzzle to be placed.

class hammoudeh_puzzle.solver_helper_classes.PuzzleLocation(puzzle_id, row, column)[source]

Bases: object

Structure for formalizing a puzzle location

key

Returns a unique key for a given puzzle location on a given board.

Returns (str):
Key for this puzzle location
location

Puzzle location as a tuple of (row, column)

Returns (Tuple[int]):
Tuple in the form (row, column)

Module contents