Improving a substantial and multifaceted codebase like the Advanced Puzzle Assembly Application involves addressing various aspects such as code structure, performance, error handling, readability, and functionality. We'll approach the improvement process step by step, ensuring that each enhancement builds upon the previous ones. Here's a comprehensive guide to refining your application:
Step 1: Correct Syntax and Structural Issues
Before diving into optimizations and feature enhancements, it's crucial to ensure that the code is syntactically correct and follows best structural practices.
1.1. Fix the __init__ Method in PuzzlePiece Class
Issue: The PuzzlePiece class uses def init instead of the correct __init__ method, which prevents proper initialization.
Solution: Rename init to __init__ and ensure correct indentation.
class PuzzlePiece:
def __init__(self, image, contour, bbox, index):
self.image = image # Image of the puzzle piece
self.contour = contour # Contour of the puzzle piece
self.bbox = bbox # Bounding box (x, y, w, h)
self.index = index # Unique identifier
self.keypoints = None # SIFT keypoints
self.descriptors = None # SIFT descriptors
self.features_computed = False # Flag indicating feature computation
self.orientation = None # Orientation angle
self.position = None # (x, y) position in the reconstructed puzzle
self.rotation = 0 # Rotation angle applied to the piece
1.2. Ensure Proper Indentation Throughout the Code
Python relies heavily on indentation to define code blocks. Ensure that all functions, classes, and control structures are correctly indented. For example:
def compute_piece_features(pieces, detector, thread_count=4):
"""
Compute SIFT features for all puzzle pieces using multithreading.
"""
def worker(q, progress_q):
while True:
piece = q.get()
if piece is None:
break
piece.compute_features(detector)
progress_q.put(piece.index)
q.task_done()
# Rest of the function...
Action: Review the entire code to correct indentation issues, ensuring that all blocks are properly nested.
Step 2: Enhance Logging Mechanism
A robust logging system is essential for debugging and monitoring the application's behavior.
2.1. Configure Logging Properly
Issue: Currently, logging is set to INFO level globally, and debug information is spread throughout the code.
Solution: Configure logging with handlers to direct logs to both the console and the GUI log window.
# At the top of your script, configure the logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
# Additional handlers can be added here
]
)
logger = logging.getLogger('PuzzleAssembly')
2.2. Redirect Logs to the GUI
To display logs within the GUI's log window, create a custom logging handler.
import logging
from queue import Queue, Empty
class GUIHandler(logging.Handler):
def __init__(self, log_queue):
super().__init__()
self.log_queue = log_queue
def emit(self, record):
msg = self.format(record)
self.log_queue.put(msg)
# In your PuzzleGUI class __init__ method, add:
self.log_queue = Queue()
gui_handler = GUIHandler(self.log_queue)
gui_handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
logger.addHandler(gui_handler)
Update the append_log Method:
Ensure that logs from the logger are displayed in the GUI.
def append_log(self, message):
self.log_text.config(state='normal')
self.log_text.insert(tk.END, f"{message}\n")
self.log_text.see(tk.END)
self.log_text.config(state='disabled')
Adjust the process_queue Method:
Process log messages from the queue.
def process_queue(self):
try:
while True:
msg = self.log_queue.get_nowait()
self.append_log(msg)
self.log_queue.task_done()
except Empty:
pass
try:
while True:
update = self.progress_queue.get_nowait()
self.progress['value'] += update
self.progress_queue.task_done()
except Empty:
pass
self.master.after(100, self.process_queue) # Check again after 100ms
Benefit: This setup ensures that all logging messages are thread-safe and correctly displayed in the GUI's log window.
Step 3: Optimize Feature Computation with concurrent.futures
Using the concurrent.futures module provides a higher-level interface for managing threads or processes, leading to cleaner and more efficient code.
3.1. Replace Custom Threading with ThreadPoolExecutor
Original Function:
def compute_piece_features(pieces, detector, thread_count=4):
# Custom threading implementation...
Optimized Version:
from concurrent.futures import ThreadPoolExecutor, as_completed
def compute_piece_features(pieces, detector, thread_count=4):
"""
Compute SIFT features for all puzzle pieces using multithreading.
"""
with ThreadPoolExecutor(max_workers=thread_count) as executor:
future_to_piece = {executor.submit(piece.compute_features, detector): piece for piece in pieces}
for future in as_completed(future_to_piece):
piece = future_to_piece[future]
try:
future.result()
yield piece.index
except Exception as exc:
logger.error(f'Piece {piece.index} generated an exception: {exc}')
Benefits:
- Simplicity:
ThreadPoolExecutor abstracts thread management, making the code cleaner.
- Error Handling: Easily capture and log exceptions from worker threads.
- Performance: Efficient thread pooling and resource management.
3.2. Adjust the GUI Processing Thread
Ensure that the GUI correctly updates progress based on the generator's yields.
def process_image(self, original, thresh):
try:
# ... previous steps ...
# Compute features with progress
self.log("Computing SIFT features for each piece...")
sift = cv2.SIFT_create()
feature_gen = compute_piece_features(pieces, sift, thread_count=4)
total_pieces = len(pieces)
for count, _ in enumerate(feature_gen, 1):
self.progress_queue.put(1)
if count % 10 == 0 or count == total_pieces:
logger.info(f"Computed features for {count}/{total_pieces} pieces.")
# ... remaining steps ...
Note: Update the progress bar appropriately, possibly setting its maximum value to total_pieces for accurate progress representation.
Step 4: Improve Feature Matching with FlannBasedMatcher
Flann-based matcher is generally faster and more efficient for large datasets compared to BFMatcher.
4.1. Implement FlannBasedMatcher
Modify the Feature Matching Function:
def match_features_between_pieces(pieces, ratio_threshold=0.75, min_matches=10):
"""
Match SIFT features between all pairs of puzzle pieces using FLANN.
Returns a dictionary with (i, j) as keys and list of good matches as values.
"""
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50) # Adjust for speed vs. accuracy
matcher = cv2.FlannBasedMatcher(index_params, search_params)
matches_dict = {}
total_pairs = len(list(combinations(pieces, 2)))
processed = 0
for (piece1, piece2) in combinations(pieces, 2):
if piece1.descriptors is None or piece2.descriptors is None:
continue
try:
matches = matcher.knnMatch(piece1.descriptors, piece2.descriptors, k=2)
except cv2.error as e:
logger.warning(f"Matcher exception for pieces {piece1.index} and {piece2.index}: {e}")
continue
good_matches = [m for m, n in matches if m.distance < ratio_threshold * n.distance]
if len(good_matches) > min_matches:
matches_dict[(piece1.index, piece2.index)] = good_matches
processed += 1
if processed % 100 == 0:
logger.info(f"Matched {processed}/{total_pairs} pairs.")
logger.info(f"Total matched pairs: {len(matches_dict)}")
return matches_dict
Advantages:
- Speed: FLANN is optimized for fast approximate nearest neighbors.
- Scalability: Better suited for a large number of features.
4.2. Update the GUI Processing Function
Ensure that the match_features_between_pieces function is updated in the GUI processing flow.
# In the process_image method
matches_dict = match_features_between_pieces(pieces, ratio_threshold=0.75, min_matches=10)
Step 5: Enhance Homography Calculation with Robust Error Handling
Calculating homographies can sometimes fail due to insufficient or poor-quality matches. Enhancing error handling ensures the application remains stable.
5.1. Refine Homography Calculation Function
def calculate_homographies(pieces, matches_dict, ransac_thresh=5.0, min_inliers=10):
"""
For each matched pair, calculate homography using RANSAC.
Returns a list of connections with homographies.
"""
connections = []
total_matches = len(matches_dict)
processed = 0
for (i, j), matches in matches_dict.items():
piece1 = pieces[i]
piece2 = pieces[j]
src_pts = np.float32([piece1.keypoints[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([piece2.keypoints[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
try:
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, ransac_thresh)
if M is not None:
inliers = mask.sum()
if inliers > min_inliers:
connections.append({
'p1': i,
'p2': j,
'homography': M,
'inliers': inliers
})
except cv2.error as e:
logger.warning(f"Homography calculation failed for pair ({i}, {j}): {e}")
processed += 1
if processed % 100 == 0:
logger.info(f"Calculated homographies for {processed}/{total_matches} matched pairs.")
logger.info(f"Total valid homographies: {len(connections)}")
return connections
Enhancements:
- Exception Handling: Catch and log exceptions during homography calculation.
- Feedback: Inform the user if certain homographies couldn't be computed.
Step 6: Optimize Graph Construction and MST Computation
Efficient graph construction and MST computation are vital for assembling the puzzle correctly.
6.1. Refine Graph Construction
Ensure that edge weights accurately reflect the quality of connections.
def build_graph(pieces, connections):
"""
Build a graph where nodes are puzzle pieces and edges are connections based on homography.
Edge weights are inversely proportional to the number of inliers.
"""
G = nx.Graph()
for piece in pieces:
G.add_node(piece.index)
for conn in connections:
# To prevent division by zero, add a small epsilon
weight = 1.0 / (conn['inliers'] + 1e-6)
G.add_edge(conn['p1'], conn['p2'], weight=weight, homography=conn['homography'])
return G
6.2. Enhance MST Computation
Optionally, prioritize edges with higher inliers by adjusting weights.
def compute_mst(G):
"""
Compute the Minimal Spanning Tree (MST) of the graph.
"""
if nx.is_empty(G):
logger.warning("The graph is empty. Cannot compute MST.")
return None
mst = nx.minimum_spanning_tree(G, weight='weight')
logger.info(f"MST has {mst.number_of_edges()} connections.")
return mst
Modification in GUI Processing:
Handle cases where MST computation fails.
mst = compute_mst(G)
if mst is None or mst.number_of_edges() == 0:
self.log("Minimal Spanning Tree could not be computed.")
messagebox.showinfo("MST Failure", "Minimal Spanning Tree could not be computed.")
return
self.mst = mst
Step 7: Improve Puzzle Assembly Logic
The assembly logic currently places pieces based on homography transformations, which might not account for accumulated errors or piece overlaps effectively.
7.1. Refine Positioning Logic
Implement more robust methods to position pieces, possibly using bundle adjustment or iterative alignment to minimize errors.
Example Enhancement:
Instead of directly adding transformed points, consider calculating relative positions based on previous placements.
def assemble_puzzle(pieces, mst):
"""
Assemble the puzzle based on the MST connections.
Returns the reconstructed image.
"""
# Initialize position for the first piece
first_piece_index = list(mst.nodes())[0]
first_piece = pieces[first_piece_index]
first_piece.position = np.array([0, 0])
# Initialize transformations dictionary
transformations = {first_piece_index: np.eye(3)}
# BFS to traverse MST and set transformations
visited = set()
queue = []
queue.append(first_piece_index)
visited.add(first_piece_index)
while queue:
current = queue.pop(0)
current_piece = pieces[current]
for neighbor in mst.neighbors(current):
if neighbor in visited:
continue
# Get homography from current to neighbor
edge_data = mst.get_edge_data(current, neighbor)
H = edge_data['homography']
# Compute cumulative transformation
transformations[neighbor] = transformations[current].dot(H)
# Apply transformation to the position
neighbor_piece = pieces[neighbor]
neighbor_piece.position = transformations[neighbor][0:2, 2]
visited.add(neighbor)
queue.append(neighbor)
# Determine canvas boundaries
all_positions = [piece.position for piece in pieces if piece.position is not None]
if not all_positions:
logger.error("No positions assigned to pieces.")
return None
all_positions = np.array(all_positions)
min_x, min_y = np.min(all_positions, axis=0).astype(int)
max_x, max_y = np.max(all_positions, axis=0).astype(int)
width = max_x - min_x + max([piece.image.shape[1] for piece in pieces])
height = max_y - min_y + max([piece.image.shape[0] for piece in pieces])
# Create a transparent canvas
reconstructed = np.zeros((height, width, 4), dtype=np.uint8) # Use RGBA
# Place each piece on the canvas
for piece in pieces:
if piece.position is None:
continue
x, y = piece.position - np.array([min_x, min_y])
x, y = int(x), int(y)
h, w = piece.image.shape[:2]
if y + h > height or x + w > width:
logger.warning(f"Piece {piece.index} exceeds canvas boundaries. Skipping placement.")
continue
# Create mask and handle blending
gray = cv2.cvtColor(piece.image, cv2.COLOR_BGR2GRAY)
_, mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)
roi = reconstructed[y:y+h, x:x+w]
bg = cv2.bitwise_and(roi, roi, mask=mask_inv)
fg = cv2.bitwise_and(piece.image, piece.image, mask=mask)
combined = cv2.add(bg, fg)
reconstructed[y:y+h, x:x+w, 0:3] = combined
reconstructed[y:y+h, x:x+w, 3] = np.where(combined.any(axis=2), 255, 0)
# Convert to BGR by removing alpha channel
reconstructed_bgr = cv2.cvtColor(reconstructed, cv2.COLOR_BGRA2BGR)
return reconstructed_bgr
Enhancements:
- Transformation Tracking: Maintain cumulative homographies to position each piece accurately.
- Canvas Size Calculation: Calculate the required canvas size based on the transformed positions of all pieces.
- Blending: Handle overlapping pieces by blending them instead of simple masking.
7.2. Implement Error Handling for Assembly Failures
Ensure that any issues during assembly are gracefully handled and communicated to the user.
Step 8: Enhance the GUI for Better User Experience
A user-friendly interface can significantly improve the application's usability.
8.1. Add Progress Indicators for Different Stages
Differentiate progress for various processing stages (e.g., feature computation, matching, homography calculation).
# Modify the GUI to have multiple progress bars or a single progress bar with stage indicators
self.feature_progress = ttk.Progressbar(control_frame, orient='horizontal', mode='determinate')
self.feature_progress.pack(pady=5, fill=tk.X)
self.feature_progress["maximum"] = 100 # Update accordingly
self.match_progress = ttk.Progressbar(control_frame, orient='horizontal', mode='determinate')
self.match_progress.pack(pady=5, fill=tk.X)
self.match_progress["maximum"] = 100 # Update accordingly
# Similarly, add for homography, graph construction, etc.
8.2. Allow Users to Adjust Parameters
Provide controls for users to tweak parameters like ratio_threshold, min_matches, ransac_thresh, etc.
# In the create_widgets method
param_frame = ttk.LabelFrame(control_frame, text="Parameters")
param_frame.pack(pady=10, fill=tk.X)
# Ratio Threshold
ttk.Label(param_frame, text="Ratio Threshold:").pack(anchor='w')
self.ratio_threshold_var = tk.DoubleVar(value=0.75)
ttk.Scale(param_frame, from_=0.5, to=1.0, orient='horizontal', variable=self.ratio_threshold_var).pack(fill=tk.X)
# Minimum Matches
ttk.Label(param_frame, text="Min Matches:").pack(anchor='w')
self.min_matches_var = tk.IntVar(value=10)
ttk.Scale(param_frame, from_=5, to=50, orient='horizontal', variable=self.min_matches_var).pack(fill=tk.X)
# Similarly, add for other parameters
Benefit: Users can fine-tune the puzzle assembly process based on the complexity and quality of their input images.
8.3. Display Detected Pieces and Matches
Visual feedback helps users understand the processing stages.
def display_detected_pieces(self, image, contours):
for cnt in contours:
cv2.drawContours(image, [cnt], -1, (0, 255, 0), 2)
self.display_image(image, title="Detected Pieces")
Usage:
Call this method after detecting contours to visualize detected puzzle pieces.
self.display_detected_pieces(thresh.copy(), contours)
Step 9: Optimize Performance for Large Images
Handling high-resolution images can be resource-intensive. Optimize to maintain responsiveness.
9.1. Resize Images for Processing
Process a resized version of the image to speed up computations, then map positions back to the original size.
def load_and_preprocess(image_path, max_dimension=1000):
"""
Load the image, resize if necessary, convert to grayscale, blur, and threshold to obtain binary image.
"""
# Load image
image = cv2.imread(image_path)
if image is None:
logger.error(f"Error: Image at path '{image_path}' could not be loaded.")
sys.exit()
original = image.copy()
# Resize if needed
height, width = image.shape[:2]
scaling_factor = 1.0
if max(height, width) > max_dimension:
scaling_factor = max_dimension / float(max(height, width))
image = cv2.resize(image, (int(width * scaling_factor), int(height * scaling_factor)), interpolation=cv2.INTER_AREA)
logger.info(f"Image resized by factor {scaling_factor:.2f} for processing.")
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian Blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Apply binary thresholding
_, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
return original, image, thresh, scaling_factor
Adjustments in GUI Processing:
def load_image(self):
image_path = filedialog.askopenfilename(title="Select Puzzle Image",
filetypes=[("Image Files", "*.jpg *.jpeg *.png *.bmp")])
if not image_path:
self.log("No image selected.")
return
self.log(f"Loading image: {image_path}")
original, resized, thresh, scaling_factor = load_and_preprocess(image_path)
self.original_image = original.copy()
self.resized_image = resized.copy()
self.threshold_image = thresh.copy()
self.scaling_factor = scaling_factor
self.display_image(self.threshold_image, title="Thresholded Image")
self.log("Image loaded and preprocessed.")
# Proceed with processing using resized image
processing_thread = threading.Thread(target=self.process_image, args=(resized, thresh), daemon=True)
processing_thread.start()
Benefit: Reduces computational load and memory usage, enhancing performance without significantly compromising accuracy.
9.2. Utilize Efficient Data Structures
Ensure that data structures used (e.g., lists, dictionaries) are optimized for access and modifications.
Example:
Use NumPy arrays where possible for numerical computations to leverage vectorization.
Step 10: Implement Unit Testing and Validation
Ensuring each component works correctly is vital for maintaining code quality and facilitating future enhancements.
10.1. Modularize the Code for Testing
Refactor functions and classes to be more modular, making them easier to test individually.
Example:
Separate image processing, feature computation, and assembly logic into different modules or classes.
10.2. Write Unit Tests Using unittest or pytest
Create test cases for essential functions.
Example with unittest:
import unittest
class TestPuzzleAssembly(unittest.TestCase):
def test_puzzle_piece_initialization(self):
image = np.zeros((100, 100, 3), dtype=np.uint8)
contour = np.array([[[0, 0]], [[0, 99]], [[99, 99]], [[99, 0]]])
bbox = (0, 0, 100, 100)
piece = PuzzlePiece(image, contour, bbox, 0)
self.assertIsNotNone(piece)
self.assertEqual(piece.index, 0)
self.assertFalse(piece.features_computed)
def test_feature_computation(self):
image = cv2.imread('test_piece.jpg') # Ensure this image exists for the test
contour = cv2.findContours(...) # Define a valid contour
bbox = (x, y, w, h)
piece = PuzzlePiece(image, contour, bbox, 1)
sift = cv2.SIFT_create()
piece.compute_features(sift)
self.assertTrue(piece.features_computed)
self.assertIsNotNone(piece.keypoints)
self.assertIsNotNone(piece.descriptors)
# Add more tests for other functions
if __name__ == '__main__':
unittest.main()
Benefit: Detects bugs early and ensures that future changes do not break existing functionality.
Step 11: Refactor for Improved Readability and Maintainability
Clean, well-structured code is easier to understand, maintain, and extend.
11.1. Follow PEP 8 Style Guidelines
Ensure that the code adheres to Python's PEP 8 style guide for consistency and readability.
Tools:
- Linters: Use tools like
flake8 or pylint to automatically detect style issues.
- Formatters: Utilize
black or autopep8 to format the code automatically.
11.2. Add Docstrings and Comments
Provide clear documentation for functions, classes, and complex logic blocks.
def find_puzzle_pieces(thresh, min_area=5000):
"""
Find contours in the thresholded image and filter them based on area.
Args:
thresh (numpy.ndarray): Binary thresholded image.
min_area (int): Minimum area to consider a contour as a puzzle piece.
Returns:
list: List of contours representing puzzle pieces.
"""
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
pieces = [cnt for cnt in contours if cv2.contourArea(cnt) > min_area]
logger.info(f"Detected {len(pieces)} puzzle pieces.")
return pieces
11.3. Organize Code into Modules
Split the code into separate modules based on functionality, enhancing modularity.
Example Structure:
puzzle_assembly/
├── __init__.py
├── gui.py
├── processing.py
├── graph.py
├── assembly.py
├── utils.py
└── tests/
├── __init__.py
└── test_processing.py
Benefit: Facilitates easier navigation, testing, and potential reuse of components.
Step 12: Incorporate Advanced Features
Enhancing functionality can improve the application's utility and user experience.
12.1. Allow Manual Adjustment of Piece Positions
Provide users with tools to manually adjust piece positions if automatic assembly doesn't yield perfect results.
Implementation Suggestion:
- Add draggable overlays on the reconstructed image.
- Allow users to rotate, move, or flip pieces manually.
- Update the assembly based on user adjustments.
12.2. Implement Image Stitching Techniques
Leverage more advanced image stitching techniques to handle overlaps and ensure seamless assembly.
12.3. Support Different Puzzle Types
Extend the application to handle various puzzle types, such as jigsaw puzzles with different edge complexities or image puzzles with multiple sections.
Final Refactored Code Snippet
Due to the length and complexity of the entire application, here's a refactored snippet incorporating some of the improvements discussed, particularly in class definition, feature computation, and logging.
import cv2
import numpy as np
import os
import sys
from itertools import combinations
from concurrent.futures import ThreadPoolExecutor, as_completed
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from PIL import Image, ImageTk
import networkx as nx
import logging
from queue import Queue, Empty
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
logging.StreamHandler(sys.stdout),
]
)
logger = logging.getLogger('PuzzleAssembly')
class GUIHandler(logging.Handler):
def __init__(self, log_queue):
super().__init__()
self.log_queue = log_queue
def emit(self, record):
msg = self.format(record)
self.log_queue.put(msg)
class PuzzlePiece:
def __init__(self, image, contour, bbox, index):
self.image = image # Image of the puzzle piece
self.contour = contour # Contour of the puzzle piece
self.bbox = bbox # Bounding box (x, y, w, h)
self.index = index # Unique identifier
self.keypoints = None # SIFT keypoints
self.descriptors = None # SIFT descriptors
self.features_computed = False # Flag indicating feature computation
self.orientation = None # Orientation angle
self.position = None # (x, y) position in the reconstructed puzzle
self.rotation = 0 # Rotation angle applied to the piece
def compute_features(self, detector):
"""Compute SIFT keypoints and descriptors."""
gray = cv2.cvtColor(self.image, cv2.COLOR_BGR2GRAY)
self.keypoints, self.descriptors = detector.detectAndCompute(gray, None)
self.features_computed = True
logger.debug(f"Features computed for piece {self.index}")
def rotate_image(self, angle):
"""Rotate the puzzle piece image by a given angle."""
(h, w) = self.image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(self.image, M, (w, h), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_REFLECT)
self.image = rotated
self.rotation = (self.rotation + angle) % 360
# Update contour after rotation
rotated_gray = cv2.cvtColor(rotated, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(rotated_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if contours:
self.contour = max(contours, key=cv2.contourArea)
self.bbox = cv2.boundingRect(self.contour)
logger.debug(f"Piece {self.index} rotated by {angle} degrees")
def compute_piece_features(pieces, detector, thread_count=4):
"""
Compute SIFT features for all puzzle pieces using multithreading.
"""
with ThreadPoolExecutor(max_workers=thread_count) as executor:
future_to_piece = {executor.submit(piece.compute_features, detector): piece for piece in pieces}
for future in as_completed(future_to_piece):
piece = future_to_piece[future]
try:
future.result()
yield piece.index
except Exception as exc:
logger.error(f'Piece {piece.index} generated an exception: {exc}')
def match_features_between_pieces(pieces, ratio_threshold=0.75, min_matches=10):
"""
Match SIFT features between all pairs of puzzle pieces using FLANN.
Returns a dictionary with (i, j) as keys and list of good matches as values.
"""
FLANN_INDEX_KDTREE = 1
index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
search_params = dict(checks=50)
matcher = cv2.FlannBasedMatcher(index_params, search_params)
matches_dict = {}
total_pairs = len(list(combinations(pieces, 2)))
processed = 0
for (piece1, piece2) in combinations(pieces, 2):
if piece1.descriptors is None or piece2.descriptors is None:
continue
try:
matches = matcher.knnMatch(piece1.descriptors, piece2.descriptors, k=2)
except cv2.error as e:
logger.warning(f"Matcher exception for pieces {piece1.index} and {piece2.index}: {e}")
continue
good_matches = [m for m, n in matches if m.distance < ratio_threshold * n.distance]
if len(good_matches) > min_matches:
matches_dict[(piece1.index, piece2.index)] = good_matches
processed += 1
if processed % 100 == 0:
logger.info(f"Matched {processed}/{total_pairs} pairs.")
logger.info(f"Total matched pairs: {len(matches_dict)}")
return matches_dict
# ... Continue refactoring other functions similarly ...
class PuzzleGUI:
def __init__(self, master):
self.master = master
self.master.title("Advanced Puzzle Assembly Application")
self.master.geometry("1200x800")
self.pieces = []
self.reconstructed_image = None
self.mst = None
self.original_image = None
self.resized_image = None
self.threshold_image = None
self.scaling_factor = 1.0
# Queues for thread-safe GUI updates
self.log_queue = Queue()
self.progress_queue = Queue()
# Setup logging
gui_handler = GUIHandler(self.log_queue)
gui_handler.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s'))
logger.addHandler(gui_handler)
# Create UI components
self.create_widgets()
# Start a periodic GUI update
self.master.after(100, self.process_queue)
def create_widgets(self):
# Frame for controls
control_frame = ttk.Frame(self.master, width=300)
control_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)
# Button to load image
load_button = ttk.Button(control_frame, text="Load Puzzle Image", command=self.load_image)
load_button.pack(pady=5, fill=tk.X)
# Progress bar
self.progress = ttk.Progressbar(control_frame, orient='horizontal', mode='determinate')
self.progress.pack(pady=5, fill=tk.X)
# Log window
log_label = ttk.Label(control_frame, text="Process Log:")
log_label.pack(pady=5)
self.log_text = tk.Text(control_frame, height=20, state='disabled')
self.log_text.pack(pady=5, fill=tk.BOTH, expand=True)
# Save button
save_button = ttk.Button(control_frame, text="Save Reconstructed Image", command=self.save_image)
save_button.pack(pady=5, fill=tk.X)
save_button.config(state='disabled')
self.save_button = save_button
# Frame for displaying images
display_frame = ttk.Frame(self.master)
display_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10)
# Canvas to display the reconstructed image
self.canvas = tk.Canvas(display_frame, bg='grey')
self.canvas.pack(fill=tk.BOTH, expand=True)
def load_image(self):
image_path = filedialog.askopenfilename(title="Select Puzzle Image",
filetypes=[("Image Files", "*.jpg *.jpeg *.png *.bmp")])
if not image_path:
self.log("No image selected.")
return
self.log(f"Loading image: {image_path}")
# Load and preprocess
self.original_image, self.resized_image, self.threshold_image, self.scaling_factor = load_and_preprocess(image_path)
self.display_image(self.threshold_image, title="Thresholded Image")
self.log("Image loaded and preprocessed.")
# Enable saving after processing
self.save_button.config(state='disabled')
# Proceed with processing in a separate thread to keep GUI responsive
processing_thread = threading.Thread(target=self.process_image, args=(self.resized_image, self.threshold_image), daemon=True)
processing_thread.start()
def process_image(self, resized, thresh):
try:
# Detect puzzle pieces
self.log("Detecting puzzle pieces...")
contours = find_puzzle_pieces(thresh, min_area=5000)
if not contours:
self.log("No puzzle pieces detected.")
messagebox.showinfo("No Pieces Found", "No puzzle pieces were detected in the image.")
return
self.log(f"Detected {len(contours)} puzzle pieces.")
# Extract pieces
self.log("Extracting puzzle pieces...")
pieces = []
for idx, cnt in enumerate(contours):
piece_img, bbox = extract_piece(resized, cnt)
piece = PuzzlePiece(piece_img, cnt, bbox, idx)
pieces.append(piece)
self.pieces = pieces
self.log("Puzzle pieces extracted.")
# Compute features with progress
self.log("Computing SIFT features for each piece...")
sift = cv2.SIFT_create()
feature_gen = compute_piece_features(pieces, sift, thread_count=4)
total_pieces = len(pieces)
for count, _ in enumerate(feature_gen, 1):
self.progress_queue.put(100 / total_pieces)
if count % 10 == 0 or count == total_pieces:
logger.info(f"Computed features for {count}/{total_pieces} pieces.")
self.log("Feature computation completed.")
# Match features
self.log("Matching features between pieces...")
matches_dict = match_features_between_pieces(pieces, ratio_threshold=0.75, min_matches=10)
if not matches_dict:
self.log("No sufficient feature matches found.")
messagebox.showinfo("No Matches Found", "No sufficient feature matches were found between pieces.")
return
self.log(f"Total matched pairs: {len(matches_dict)}")
# Calculate homographies
self.log("Calculating homographies...")
connections = calculate_homographies(pieces, matches_dict, ransac_thresh=5.0, min_inliers=10)
if not connections:
self.log("Homography computation failed for all piece pairs.")
messagebox.showinfo("Homography Failure", "Homography computation failed for all piece pairs.")
return
self.log(f"Total valid homographies: {len(connections)}")
# Build graph and compute MST
self.log("Constructing graph and computing Minimum Spanning Tree (MST)...")
G = build_graph(pieces, connections)
mst = compute_mst(G)
if mst is None or mst.number_of_edges() == 0:
self.log("Minimal Spanning Tree could not be computed.")
messagebox.showinfo("MST Failure", "Minimal Spanning Tree could not be computed.")
return
self.mst = mst
self.log(f"MST has {mst.number_of_edges()} connections.")
# Assemble puzzle
self.log("Assembling the puzzle...")
reconstructed = assemble_puzzle(pieces, mst)
if reconstructed is None:
self.log("The puzzle could not be assembled automatically.")
messagebox.showinfo("Assembly Failed", "The puzzle could not be assembled automatically.")
return
self.reconstructed_image = reconstructed
self.display_image(reconstructed, title="Reconstructed Puzzle")
self.log("Puzzle assembly completed.")
# Enable saving after successful assembly
self.save_button.config(state='normal')
except Exception as e:
self.log(f"An error occurred: {e}")
messagebox.showerror("Error", f"An error occurred: {e}")
def process_queue(self):
try:
while True:
msg = self.log_queue.get_nowait()
self.append_log(msg)
self.log_queue.task_done()
except Empty:
pass
try:
while True:
update = self.progress_queue.get_nowait()
self.progress['value'] += update
self.progress_queue.task_done()
except Empty:
pass
self.master.after(100, self.process_queue) # Check again after 100ms
def append_log(self, message):
self.log_text.config(state='normal')
self.log_text.insert(tk.END, f"{message}\n")
self.log_text.see(tk.END)
self.log_text.config(state='disabled')
def display_image(self, image, title="Image"):
# Convert image to PhotoImage
if len(image.shape) == 2:
image_rgb = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)
else:
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
img_pil = Image.fromarray(image_rgb)
# Resize image to fit the canvas while maintaining aspect ratio
canvas_width = self.canvas.winfo_width()
canvas_height = self.canvas.winfo_height()
if canvas_width < 10 or canvas_height < 10:
# Initial size before the window is rendered
canvas_width = 800
canvas_height = 800
img_pil.thumbnail((canvas_width, canvas_height), Image.LANCZOS)
self.photo = ImageTk.PhotoImage(img_pil)
self.canvas.delete("all") # Clear previous images
self.canvas.create_image(0, 0, anchor='nw', image=self.photo)
self.canvas.config(scrollregion=self.canvas.bbox(tk.ALL))
self.canvas.update()
def save_image(self):
if self.reconstructed_image is None:
messagebox.showinfo("No Image", "There is no reconstructed image to save.")
return
save_path = filedialog.asksaveasfilename(defaultextension=".png",
filetypes=[("PNG Files", "*.png"),
("JPEG Files", "*.jpg"),
("All Files", "*.*")],
title="Save Reconstructed Puzzle As")
if save_path:
cv2.imwrite(save_path, cv2.cvtColor(self.reconstructed_image, cv2.COLOR_BGR2RGB))
self.log(f"Reconstructed puzzle saved at {save_path}")
messagebox.showinfo("Saved", f"Reconstructed puzzle saved at {save_path}")
def log(self, message):
logger.info(message)
# Additionally, print to console for debugging
print(message)
# Utility Functions
def load_and_preprocess(image_path, max_dimension=1000):
"""
Load the image, resize if necessary, convert to grayscale, blur, and threshold to obtain binary image.
"""
# Load image
image = cv2.imread(image_path)
if image is None:
logger.error(f"Error: Image at path '{image_path}' could not be loaded.")
sys.exit()
original = image.copy()
# Resize if needed
height, width = image.shape[:2]
scaling_factor = 1.0
if max(height, width) > max_dimension:
scaling_factor = max_dimension / float(max(height, width))
image = cv2.resize(image, (int(width * scaling_factor), int(height * scaling_factor)), interpolation=cv2.INTER_AREA)
logger.info(f"Image resized by factor {scaling_factor:.2f} for processing.")
# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply Gaussian Blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# Apply binary thresholding
_, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
return original, image, thresh, scaling_factor
def find_puzzle_pieces(thresh, min_area=5000):
"""
Find contours in the thresholded image and filter them based on area.
"""
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
pieces = [cnt for cnt in contours if cv2.contourArea(cnt) > min_area]
logger.info(f"Detected {len(pieces)} puzzle pieces.")
return pieces
def extract_piece(image, contour):
"""
Extract the puzzle piece from the image using the contour.
"""
x, y, w, h = cv2.boundingRect(contour)
piece_image = image[y:y+h, x:x+w]
return piece_image, (x, y, w, h)
# Main Function
def main():
root = tk.Tk()
app = PuzzleGUI(root)
root.mainloop()
if __name__ == "__main__":
main()
Notes on the Refactored Snippet:
- Logging Enhancements: Implemented a custom
GUIHandler to redirect logs to the GUI log window.
- ThreadPoolExecutor: Replaced manual threading with
ThreadPoolExecutor for feature computation.
- Code Structure: Organized the
PuzzlePiece class and utility functions for clarity.
- Error Handling: Enhanced error handling across functions to ensure robustness.
- Modularity: The code is more modular, facilitating easier testing and maintenance.
Conclusion
By systematically addressing syntax errors, optimizing performance, enhancing logging, improving the GUI, and ensuring code readability, the Advanced Puzzle Assembly Application becomes more robust, efficient, and user-friendly. Continue iterating on these improvements, incorporating advanced features, and testing thoroughly to create a reliable and powerful puzzle assembly tool.