Module pipettin-piper.piper.plugins.tools.camera

Classes

class Camera (tool_data: dict, gcode_builder: GcodeBuilder)
Expand source code
class Camera(Tool):
    def snap(self):
        img = None
        try:
            # Open a connection to the webcam (usually device 0).
            cap = cv2.VideoCapture(0)

            # Check if the webcam is opened successfully.
            if not cap.isOpened():
                logging.error("Error: Could not open webcam.")
                return

            # Capture a frame from the webcam
            ret, frame = cap.read()

            # Check.
            if not ret:
                logging.error("Error: Failed to capture a frame.")
                return None

            # Convert the frame to RGB format (OpenCV uses BGR by default).
            frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

            # Convert the frame to a PIL Image
            img = Image.fromarray(frame_rgb)
        except Exception:
            logging.error("Failed to acquire an image.")
        finally:
            # Release the webcam and close all OpenCV windows.
            cap.release()

        # Return the image.
        return img

    def snap_and_save(self, file_path="snapshot.png"):
        """
        Captures an image using the snap function and saves it to a custom file path.

        Parameters:
            file_path (str): The path where the captured image will be saved.
        """
        try:
            # Ensure the directory exists
            os.makedirs(os.path.dirname(file_path), exist_ok=True)

            # Capture the image
            img = self.snap()

            # Check if image is valid
            if img is None:
                logging.error("Error: No image to save.")
                return

            # Save the image
            img.save(file_path)
            print(f"Image saved to {file_path}")
        except Exception as e:
            logging.error(f"Failed to save the image. Exception: {e}")

Represents a tool in the system, encapsulating its parameters, offsets, and GCODE sequences for operations such as pickup, parking, and activation. A Tool object is responsible for generating GCODE commands required to interact with the physical toolhead, ensuring proper tool management and collision avoidance.

The Tool class extends TrackedDict to provide dynamic access to tool parameters stored in a database or JSON file, while exposing commonly used offsets and clearances as properties.

Attributes

name : str
The unique name of the tool.
parameters : dict
Tool parameters as loaded from the database or JSON file.
parked : bool
Used to track whether the tool is currently parked.
builder : GcodeBuilder
GCODE builder instance for generating movement commands.
controller : Controller
Controller instance managing tools and tool data.
gcode : GcodePrimitives
Object providing basic GCODE commands.
tool_data : dict
Complete data for the tool, including parameters and metadata.

Properties

tool_offset (dict): Tool offset parameters for the tool's active center. x_offset (float): X-axis offset for the tool. y_offset (float): Y-axis offset for the tool. z_offset (float): Z-axis offset for the tool. clearance (dict): Clearance properties to avoid collisions. safe_x (float): X clearance added by the tool to the toolhead's sides. safe_y (float): Y clearance added by the tool to the toolhead's front. safe_y_parked (float): Minimum Y coordinate for the tool when parked. safe_y_post (float): Minimum Y coordinate for the tool's empty parking post. safe_y_loaded (float): Y coordinate when the tool clears its parking post. tool_post (dict): Coordinates and offsets of the tool parking post.

Notes

  • The class assumes that tools have parameters like "tool_post" and "docking_commands" for GCODE operations.
  • It ensures safe tool-changing by using predefined clearances and docking sequences to avoid collisions during operations.

Initializes the TrackedDict instance.

Args

file_path : str
The path to the YAML file.
data : dict
Altertative (and sufficient) data source. Used to update the YAML file if any.

Ancestors

  • Tool
  • TrackedDict
  • YAMLReader
  • collections.UserDict
  • collections.abc.MutableMapping
  • collections.abc.Mapping
  • collections.abc.Collection
  • collections.abc.Sized
  • collections.abc.Iterable
  • collections.abc.Container

Methods

def snap(self)
Expand source code
def snap(self):
    img = None
    try:
        # Open a connection to the webcam (usually device 0).
        cap = cv2.VideoCapture(0)

        # Check if the webcam is opened successfully.
        if not cap.isOpened():
            logging.error("Error: Could not open webcam.")
            return

        # Capture a frame from the webcam
        ret, frame = cap.read()

        # Check.
        if not ret:
            logging.error("Error: Failed to capture a frame.")
            return None

        # Convert the frame to RGB format (OpenCV uses BGR by default).
        frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # Convert the frame to a PIL Image
        img = Image.fromarray(frame_rgb)
    except Exception:
        logging.error("Failed to acquire an image.")
    finally:
        # Release the webcam and close all OpenCV windows.
        cap.release()

    # Return the image.
    return img
def snap_and_save(self, file_path='snapshot.png')
Expand source code
def snap_and_save(self, file_path="snapshot.png"):
    """
    Captures an image using the snap function and saves it to a custom file path.

    Parameters:
        file_path (str): The path where the captured image will be saved.
    """
    try:
        # Ensure the directory exists
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        # Capture the image
        img = self.snap()

        # Check if image is valid
        if img is None:
            logging.error("Error: No image to save.")
            return

        # Save the image
        img.save(file_path)
        print(f"Image saved to {file_path}")
    except Exception as e:
        logging.error(f"Failed to save the image. Exception: {e}")

Captures an image using the snap function and saves it to a custom file path.

Parameters

file_path (str): The path where the captured image will be saved.

Inherited members