Surgical robot for automation of craniotomies in rodents
Abstract
This project presents a prototype of an advanced system for the execution of craniotomies in small rodents. A neural network has been used as a calibration tool, refining it by means of an automatic semi-calibration process based on autonomous contour detection by means of advanced computer vision techniques. A user-friendly interface has been developed with several functionalities for the start-up and use of the system. The results show a high accuracy of the trajectories on the desired contours.
Full text
Lab Internship: "Surgical Robot for Automation of Craniotomies in Rodents" December 20, 2024 Alberto Nicolás Rinaldi Polytechnique Montréal Biomedical Engineering Program
"Learning never exhausts the mind." Leonardo da Vinci
Surgical Robot for Automation of Craniotomies in Rodents Abstract This project presents a prototype of an advanced system for the execution of craniotomies in small rodents. A neural network has been used as a calibration tool, refining it by means of an automatic semi-calibration process based on autonomous contour detection by means of advanced computer vision techniques. A user-friendly interface has been developed with several functionalities for the start-up and use of the system. The results show a high accuracy of the trajectories on the desired contours. December 2024 4
Surgical Robot for Automation of Craniotomies in Rodents Table of Contents Abstract 4 1 Introduction 10 2 Objectives and Scope of the Project 11 3 Tools and Resources 12 3.1 Hardware ........................................ 12 3.1.1 Genmitsu 3018-PROVer CNC Machine . . . . . . . . . . . . . . . . . . . . 12 3.1.2 Thorlabs DCC1645C Camera . . . . . . . . . . . . . . . . . . . . . . . . . 13 3.1.3 CameraLens .................................. 13 3.1.4 DrillBids.................................... 14 3.1.5 PrusaMK43DPrinter ............................. 15 3.2 Software......................................... 16 3.2.1 Candle ..................................... 16 3.2.2 Python ..................................... 16 3.2.3 QtDesignStudio ................................ 18 3.2.4 AutodeskFusion ................................ 19 3.2.5 ThorCam .................................... 20 4 Rodents and Mice Skull Anatomy 21 5 Installation and Assembly Process 23 6 Calibration 26 6.1 First Calibration Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26 6.1.1 First calibration approach setup . . . . . . . . . . . . . . . . . . . . . . . . 26 6.2 Final Calibration Approach . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 6.2.1 Convolutional Neural Network (CNN) . . . . . . . . . . . . . . . . . . . . . 29 6.3 First Calibration Steps: Set Up the Environment . . . . . . . . . . . . . . . . . . . . 30 6.4 Fine-TuningtheAccuracy ............................... 32 6.4.1 ZonesDefinition ................................ 32 6.5 Algorithm........................................ 33 6.6 TrainingtheFinalModel ................................ 37 6.7 Predictions ....................................... 39 7 Trajectory Generator 41 7.1 VectorNormalization.................................. 41 7.2 CircleComputation................................... 41 7.3 ParameterVariability .................................. 42 7.4 Trajectories in the X-Y Plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 7.4.1 Testing of 2D Trajectories in the X-Y Plane . . . . . . . . . . . . . . . . . . 44 7.5 Trajectories With an Inclination Angle . . . . . . . . . . . . . . . . . . . . . . . . . 44 7.5.1 Testing of 3D Trajectories . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 7.6 Conversion From Pixels to G-code . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 December 2024 5
Surgical Robot for Automation of Craniotomies in Rodents 8 User Interface 48 8.1 VideoLabel....................................... 48 8.2 Template Alignment & Calibration Boards . . . . . . . . . . . . . . . . . . . . . . . 49 8.2.1 StartandMoveButtons............................. 49 8.2.2 Bregma, Lambda and Align Template Buttons . . . . . . . . . . . . . . . . . 49 8.2.3 Position and Size Sliders . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52 8.3 TrajectoryManagerBoard ............................... 53 8.3.1 Center, Reset and Start Trajectory Buttons . . . . . . . . . . . . . . . . . . . 53 8.3.2 Trajectory Features Sliders . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 9 Function List 56 10 Project Planification 61 11 Economic Study of the Project 62 12 Environmental Study of the Project 63 13 Social Study of the Project 64 Conclusion 65 References 66 14 Annex 68 December 2024 6
Surgical Robot for Automation of Craniotomies in Rodents List of Figures 1 Genmitsu3018-PROVer ................................ 12 2 Image of the DCC1645C camera Thorlabs 2024a.................... 13 3 Cameralens....................................... 14 4 Defaultdrillbids .................................... 14 5 Surgicaldrillbid .................................... 15 6 PrusaMK43DPrinter ................................. 15 7 Candlesoftwareinterface................................ 16 8 QtDesignStudio software interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 9 Autodesk Fusion software interface . . . . . . . . . . . . . . . . . . . . . . . . . . 19 10 ThorCam software interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 11 Schematic diagram of stereotactic surgery and variations of bregma and lambda (Neuroanatomy 2022) .................................... 21 12 Labeotech small animal monitoring system (LabeoTech 2024) ............ 22 13 Attachments....................................... 23 14 Cameramountingbracket................................ 24 15 Calibrationbrick .................................... 24 16 Testbrick ........................................ 24 17 Calibrationbrick .................................... 26 18 Horizontal strategy to calibrate the system . . . . . . . . . . . . . . . . . . . . . . . 27 19 Horizontally pierced cardboard calibration brick . . . . . . . . . . . . . . . . . . . . 27 20 Vertical strategy to calibrate the system . . . . . . . . . . . . . . . . . . . . . . . . 28 21 Vertically pierced cardboard calibration brick . . . . . . . . . . . . . . . . . . . . . 28 22 CNN Structure (Fernández 2023)............................ 30 23 Calibrationbricksetup ................................. 31 24 Terminal output when clicked on the image . . . . . . . . . . . . . . . . . . . . . . 31 25 Piercedcalibrationblock ................................ 32 26 CNNfeedingschematic................................. 32 27 Zones of the calibration pad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 28 Frame took before the holes are done . . . . . . . . . . . . . . . . . . . . . . . . . . 34 29 Frame took after the holes are done . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 30 Differencebetweenimages............................... 35 31 Found contours and coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 32 Frame took with the detected circles and centres . . . . . . . . . . . . . . . . . . . . 36 33 Calibration messages in the terminal . . . . . . . . . . . . . . . . . . . . . . . . . . 38 34 Difference between both blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 35 Console outputs when prediction is done . . . . . . . . . . . . . . . . . . . . . . . . 39 36 Achievedhole...................................... 40 37 Trajectory coordinates commands (extract) . . . . . . . . . . . . . . . . . . . . . . . 42 38 Circulartrajectoriesin3D ............................... 42 39 Circular trajectory in X-Y plane . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 40 Circular trajectory in X-Y plane in the brick . . . . . . . . . . . . . . . . . . . . . . 44 41 Test brick with trajectory and director vector drawn on it . . . . . . . . . . . . . . . 45 42 Trajectorydisplays ................................... 45 43 Pre-visualization of the trajectory . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 44 Carvedcontour ..................................... 46 45 Pre-visualization of the trajectory overlapped with the carved contour . . . . . . . . 46 46 Pixels to mm conversion and adjustment . . . . . . . . . . . . . . . . . . . . . . . . 47 47 VideoLabelwidget ................................... 48 December 2024 7
Surgical Robot for Automation of Craniotomies in Rodents 48 MoveandStartbuttons ................................. 49 49 Lambda, Bregma and Align Template Buttons . . . . . . . . . . . . . . . . . . . . . 50 50 Braintemplate...................................... 50 51 Lambdadefinition.................................... 51 52 Bregmadefinition.................................... 51 53 Lambda and bregma console outputs . . . . . . . . . . . . . . . . . . . . . . . . . . 51 54 Alignedtemplate .................................... 52 55 Sliders for movement and size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 56 Buttons for centering, starting and resetting the trajectory . . . . . . . . . . . . . . . 53 57 Trajectorydisplays ................................... 54 58 Sliders for modifying the diameter of the contour, the total depth and step depth . . . 55 59 Gantdiagramoftheproject............................... 61 December 2024 8
Surgical Robot for Automation of Craniotomies in Rodents (a) Surgical drill bid (b) Surgical drill bid (detail) Figure 5: Surgical drill bid 3.1.5 Prusa MK4 3D Printer The Prusa MK4S is a high-performance 3D printer designed to deliver precision and reliability with every print. It boasts advanced features such as 360° cooling, a high-flow nozzle and an optimized system that allows higher speeds without compromising quality, producing smooth surfaces and precise details. Its robust and efficient design makes it ideal for both prototyping and manufacturing functional parts, being compatible with a wide variety of materials. In addition, it complies with strict emission standards, ensuring a safe working environment. (Research 2024) (a) Front view (b) Side view Figure 6: Prusa MK4 3D Printer In this project the Prusa MK4 3D Printer will be used to produce calibration bricks and testing bricks, reproducing the skull of the mice in order to perform better tests on different surfaces. December 2024 15
Surgical Robot for Automation of Craniotomies in Rodents 3.2 Software The software tools used were Candle for the manual management of the CNC system, QtDesignStudio for the design and management of the user interface, ThorCam for camera management and easier framing, and Python to coordinate all the tools mentioned above. Additionally, Autodesk Fusion was also used for the design of calibration and test parts. A detailed description of each of the aforementioned tools is provided below. 3.2.1 Candle Candle software is an open source application used basically for the control of GRBL-based CNC machines. It is a lightweight, intuitive and simple tool designed to facilitate the execution of G-code paths on computer numerical control (CNC) machines. (D. Developers 2024) The software is very useful when it is necessary to manually operate the CNC machine, to take certain coordinates at the time of calibration. It is also crucial to restart the machine, unlocking it after an emergency stop. The interface and different options of the program can be seen in Figure 7. Figure 7: Candle software interface 3.2.2 Python Python is a well-known open source, high-level programming language. This language has several configurable modules as add-ins called libraries. The following is a mention and a small description of all the packages used during the development of the project. Matplotlib: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations. Matplotlib was developed by neurobiologist John Hunter for processing EEG data. It has been used and developed by many people in many different fields. (Hunter and M. D. Team 2023) December 2024 16
Surgical Robot for Automation of Craniotomies in Rodents PySerial: This module encapsulates the access to the serial port. It provides backends for Python running on Windows, OSX, Linux, BSD (possibly any POSIX compliant system) and IronPython. The module named “serial” automatically selects the appropriate backend. (PySerial Developers 2023) Scikit-learn: Scikit-lear is an open source package built on NumPy, SciPy, and matplotlib. Its main applications are classification, regression, clustering , dimensionality reduction, model selection and pre-processing. In the project, it is crucial for normalization at the input and output of the neural net. (S.-l. Developers 2023) SciPy: SciPy is an open source package that provides algorithms for optimization, integration, interpolation, eigenvalue problems, algebraic equations, differential equations, statistics, and many other classes of problems.(S. Developers 2023) TensorFlow: TensorFlow is a package specialized in the context of creating machine learning models. In the project is used to built, train and apply the model, which is the base core of the calibration module. (T. Developers 2023) ThorLabs TSI SDK: Thorlabs TSI SDK package is used to control scientific cameras and other Thorlabs devices in imaging and scientific data processing applications. This Python package allows you to program, automate, and perform image capture and analysis tasks with Thorlabs devices. (Thorlabs 2023) NumPy: NumPy is a really important Python library for scientific computation and manipulation of large volumes of numerical data. It provides a multidimensional array object, called ndarray, which is more memory- and performance-efficient than traditional Python lists. It also provides a wide variety of mathematical, statistical, and linear algebra functions to perform operations on these arrays quickly and efficiently. It is widely used in data science, numerical analysis, simulation, and machine learning applications due to its high performance and ease of use. (Oliphant and N. Developers 2023) Opencv: Opencv is an open source python library that provides a wide selection of computer vision and pattern recognition tools. In the project is also crucial for system calibration, being responsible of detecting the different holes performed by the drill and having a direct impact on the calibration accuracy. (O. Team 2023) PyLabLib: PyLabLib is a Python library that makes it easier to communicate with laboratory devices such as cameras and other measurement equipment. In this project, it is used to control the Thorlabs camera, allowing image capture and parameter settings related to visual data acquisition. (Pylablib Developers 2023) December 2024 17
Surgical Robot for Automation of Craniotomies in Rodents PyQt: PyQt is a set of Python bindings for the Qt graphical library, which allows you to create desktop applications with graphical user interfaces (GUI). In the project PyQt is used to create and manage the user interface, allowing interaction with the system through windows, buttons and other graphical components. (Thompson 2023) All these libraries make up the project requirements. A “requirements.txt” file has been packaged in which the versions of each library to be used are specified for the user’s convenience. In this way, it is enough to execute the installations and the software is ready to use. The content of the previously mentioned document is the following: m a t p l o t l i b = =3.9 .3 numpy == 2. 1. 3 opencv _ python = = 4 . 1 0 . 0 . 8 4 P i l l o w = =1 1. 0. 0 p y l a b l i b = = 1 . 4 . 3 PyQt 5==5.15. 11 PyQt 5_ s i p = = 12. 15. 0 p y s e r i a l ==3.5 s c i k i t _ l e a r n = = 1 . 5 . 2 s c i p y ==1. 14. 1 t e n s o r f l o w ==2 .17 .0 t e n s o r f l o w _ i n t e l == 2.1 7.0 t h o r l a b s _ t s i _ sdk = = 0 . 0 . 8 t i f f f i l e ==2024.9.20 3.2.3 Qt DesignStudio Qt Design Studio is a user interface design and development tool created by Qt Company, which allows the creation of modern and functional UIs through a visual and interactive approach. It facilitates drag-and-drop design, integrating seamlessly with the QML language to define the behavior of interfaces. The tool includes real-time previewing, allowing functional prototypes to be validated and animations to be adjusted efficiently. Thanks to its cross-platform support (Windows, Linux, macOS, iOS and Android), Qt Design Studio is ideal for developing interfaces in desktop, mobile and embedded applications, especially in industrial and automotive contexts. (Company 2024) In this project it will be the tool in charge of creating, managing and editing the user interface showing on screen the frames captured by the camera, the different markers on the image, the buttons, sliders and incrementals. December 2024 18
Surgical Robot for Automation of Craniotomies in Rodents Figure 8: QtDesignStudio software interface 3.2.4 Autodesk Fusion Autodesk Fusion (formerly known as Fusion 360) is an advanced computer-aided design and manufacturing (CAD/CAM/CAE) tool developed by Autodesk. It is a cloud-based software that integrates parametric and direct 3D modeling, simulation, CAM path generation for manufacturing, and realtime collaboration. Its all-in-one approach enables engineers, designers, and manufacturers to create prototypes and products from conceptual design to manufacturing, with support for 3D printing, CNC milling, and engineering analysis. Autodesk Fusion is widely used in industrial, educational and design sectors because of its versatility, efficiency and collaborative environment. (Inc. 2024) Figure 9: Autodesk Fusion software interface In the present project, it will be used to design the calibration and test parts, which will later be 3D printed with the Prusa MK4. December 2024 19
Surgical Robot for Automation of Craniotomies in Rodents 3.2.5 ThorCam ThorCam is a software developed by Thorlabs for image acquisition and display on scientific cameras, such as the DCC, CS, and Quantalux series. Designed specifically for CCD and CMOS cameras, ThorCam offers an intuitive interface for controlling parameters such as exposure, gain, and real-time capture. In addition, it facilitates the storage of images and videos in different formats, the application of basic analysis tools, and integration with other systems through SDKs provided by Thorlabs. It is widely used in scientific, industrial and laboratory applications due to its robustness and ease of use. (Thorlabs 2024b) Figure 10: ThorCam software interface Thorcam software allows in this case to access the camera and crop the area of interest to later display the same frame in the user interface. Having a preview (Figure 10) makes the process of adjusting and obtaining the precise region of interest of the scene being captured by the camera much easier. December 2024 20
Surgical Robot for Automation of Craniotomies in Rodents 4 Rodents and Mice Skull Anatomy Studying the anatomy of the skull of rodents, particularly mice, is essential for projects such as this one, which require precise interventions on the brain. In this project, a detailed understanding of the skull and key anatomical points, such as bregma and lambda, is essential to ensure the accuracy of the trajectories generated by the CNC system. These points act as fundamental anatomical landmarks, marking easily identifiable and reproducible locations, used as the basis for defining a bidimensional coordinate system. The bregma point, where the sagittal and coronal sutures of the skull meet, and the lambda point, where the lambdoid and sagittal sutures intersect, are widely used in neurosurgical procedures due to their accessibility and stability as physical references (see Figure 11). In this project, these points allow calibration and alignment of the reference template, ensuring that the movements of the CNC system are accurate in both physical and virtual space. Accurate identification of bregma and lambda is essential for establishing reliable trajectories and minimizing errors in delicate operations, such as drilling or accessing internal brain structures. Figure 11: Schematic diagram of stereotactic surgery and variations of bregma and lambda (Neuroanatomy 2022) The design of automated systems for rodent neurosurgery relies on the replicability of these anatomical landmarks. Therefore, it is considered essential not only to understand their location and variability, but also to integrate them into computational processes, such as image pattern recognition and CNC trajectory generation. This section examines how mouse cranial anatomy is employed in this project to optimize both calibration and precise execution of operations, bridging anatomical biology and automated engineering. ((Paxinos and Watson 2013)), ((Schmued and Fallon 1994)). In this case, the aim is to position the mouse on the Labeotech vital signs monitoring device (Figure 12), providing sedation to the rodent and applying a stable fixation to the rodent’s skull. December 2024 21
Surgical Robot for Automation of Craniotomies in Rodents Figure 12: Labeotech small animal monitoring system (LabeoTech 2024) December 2024 22
Surgical Robot for Automation of Craniotomies in Rodents 5 Installation and Assembly Process The assembly of the device consists of six main elements that compose it: •CNC Machine (Genmitsu 3018-PROVer): The characteristics of this machine have been previously described in detail. It will be in charge of executing the movements and taking the drill to the different points of its working space. The assembly of the device was carried out following the company’s manual, taking into account both the physical assembly of the elements (joints, parts, sensors...) and the configuration and start-up of the software. •Attachments of the CNC Machine to the Table (which acts as a frame): The attachments are responsible for ensuring the stability and support of the CNC machine, in this type of applications vibrations are critical and any tiny oscillation can lead to major failures in the accuracy of the system. (a) Side-Front attachment (b) Side attachment (c) Back attachment Figure 13: Attachments •Camera-Optical Lens Assembly: The camera and the lens are the sensors in charge of the vision of the system. Without them, the system would be blind. Therefore, a clear focus is necessary to allow a clear and sharp view of the frame. For this, it is necessary to take into account that the distance from the camera lens to the calibration block is 41 cm, it is necessary to adjust the lens to this focal length, the aperture value is adjustable to the illumination level of each room, in this case the selected value was 2.1. •Camera Mounting Bracket: The frame ensures the rigidity of the whole system, immobilizing the camera in the above-mentioned ideal position. This is vital to guarantee the stability and invariance of the frames. The frame is composed of two prismatic pieces of square section and rails, one vertical of 49 cm and the other horizontal of 25 cm, both are joined by means of an December 2024 23
Surgical Robot for Automation of Craniotomies in Rodents angular joint. Finally, the assembly has a camera support attached to the frame piece by means of a rail adapter. (a) Side view of the framework (b) Camera frame (c) Horizontal rail Figure 14: Camera mounting bracket •Calibration Brick: The calibration block is an essential tool to calibrate the system based on a series of holes and hole detection. Without it, it would not be possible to establish a relationship between frame pixels and spatial movements in the real world. The dimensions of the calibrating pad are 2.4 x 4 x 1 cm. It is essential that the distance between the screw holes is the same as that of the mounting plate of the CNC machine. (a) 3D render of calibration brick (b) Pierced calibration brick Figure 15: Calibration brick •Skull Simulation Brick: This block simulates the skull of a rodent to perfection, allowing tests to be performed on the surface of the skull to test the accuracy of the system in trajectories and holes after the calibration stage. Its dimensions are analogous to the brick calibration pad, with the top of the skull being tangent to the upper surface of the calibration brick. The brick has two skulls to make the most of the design and avoid wasting plastic. (a) 3D render of test brick (b) Test brick Figure 16: Test brick December 2024 24
Surgical Robot for Automation of Craniotomies in Rodents (a) Calibration brick (b) Clear view of the calibration brick in the frame Figure 23: Calibration brick setup The basis of the whole calibration process to obtain the training values of the CNN is to first capture the clicks on the image displayed on the screen, and output them through the terminal. This is achieved with the function on_image_clicked (self, x_pixel, y_pixel), the output can be seen in Figure 24. Figure 24: Terminal output when clicked on the image After this, a calibration block is placed in the test slot to create holes manually using the Candle software. Once the hole is made, the value of the X and Y coordinates are entered in the NumPy array y_train. In this way, a NumPy matrix that stores the labels or target values used in training a machine learning model is created. This matrix defines the expected outputs corresponding to the X_train inputs, allowing the model to learn the relationship between the input data and the target values by adjusting its parameters. The values of the X_train will be extracted by clicking on the center of each previously drilled point and manually added to the NumPy array. In this way, a NumPy matrix that stores the input data used to train a machine learning model is created. Each row of X_train represents a sample with its relevant features or variables, which the model uses to learn patterns that allow it to predict the expected outputs defined in y_train. After completing 4 points on each side of the pad and two in the center, the process can be streamlined by running the script directly, without the need for Candle. In this way the user employs the function hole(self, x1, y1, z, depth) to make holes on the calibration pad. The function "hole" generates a sequence of G-code commands to drill a hole with a CNC machine. First, it moves the spindle to a reference height, then positions it at the specified coordinates (x1, y1), activates the drill at a speed of 8000 RPM, descends to the specified depth, returns to the initial height, December 2024 31
Surgical Robot for Automation of Craniotomies in Rodents and finally turns off the drill. Each step is sent by the send_command function, and the corresponding command is printed for follow-up. The holes done by the "hole" function can be seen in Figure 25. Figure 25: Pierced calibration block Once the hole has been made by the aforementioned function, the user clicks on the center of the circle again to obtain the exact coordinates in pixels of the hole that generated the movement. These coordinates are added to the X_train matrix manually, and the coordinates obtained by the “hole” function are added analogously to y_train. The block diagram regarding the first step of the feeding of the CNN can be seen in Figure 26. Figure 26: CNN feeding schematic 6.4 Fine-Tuning the Accuracy When the CNN is already fed, a complex calibration sequence is designed to fine-tune the accuracy according to the working conditions of each situation. This basically consists of performing the execution, detection and addition of new points to the neural network to ensure higher accuracy if for example the drill bit size is changed or there is a small variation of the angle or position of the camera or calibration block. The following process combines complex methods of computer vision and contour and center detection, as well as camera management to make a difference in terms of accuracy. Thus adding an important plus to the calibration process that is so relevant in such delicate projects as neurosurgery. 6.4.1 Zones Definition The idea behind the operation of this feature is to make a sequence of five holes over five different zones of the calibration block. Therefore, the first step in developing the method is to define these December 2024 32
Surgical Robot for Automation of Craniotomies in Rodents zones on the block. These zones will be two vertical pillars on the sides of the block (left and right) and three horizontal bands in the central part of the pad. The zones can be seen in Figure 27, numbered from one to five (please ignore the red points since they have been used for the previous feeding process). More concrete information about the dimensions of the different zones can be found in the code annex. Figure 27: Zones of the calibration pad 6.5 Algorithm After defining the zones, we get into the logic behind the algorithm, which starts when the “Start” flank is pressed, provided that the running calibration indicator is not already True. At this moment the camera takes the first capture, in which the flat calibration block, without holes, will be recorded (Figure 28). The algorithm takes this capture and saves it in the assigning directory, under the name “before_intervention.png”. December 2024 33
Surgical Robot for Automation of Craniotomies in Rodents Figure 28: Frame took before the holes are done After this first stage, the algorithm sends the commands to execute the trajectories corresponding to the five fixed calibration holes (by means of a for loop and the “hole” function). A sixty-second timer is also activated to give the machine time to execute all the trajectories. When the timer finishes, the holes are done, and the function “capture_after_intervention” is called, which captures the new image with the holes done and saves it in the assigning directory, under the name “after_intervention.png”, then calls the function "compare_images". Figure 29: Frame took after the holes are done The compare_images function aims to compare two images (one initial and one final) and detect significant differences between them by identifying circular contours and extracting the coordinates of their centers. First, it initializes a list called centers_calibration to store the calibration coordinates and ensures that a delayed action is not complete. Then, it loads the two grayscale images using December 2024 34
Surgical Robot for Automation of Craniotomies in Rodents OpenCV (cv2.imread) and checks if they are loaded correctly. If any image is not loaded, it prints an error and terminates the execution. It then calculates the absolute differences between the two images with cv2.absdiff, highlighting the modified regions, and applies a binary threshold with cv2.threshold to filter out only significant differences. Figure 30: Difference between images The function defines five zones of interest as rectangular regions, which it traverses one by one. Within each zone, it extracts the Region of Interest (ROI) from the thresholded image, draws a cyan rectangle around the zone in the final image and searches for contours using cv2.findContours. From the found contours, adjust minimum enclosing circles with cv2.minEnclosingCircle. The circle with the largest radius within an acceptable range (between 4 and 16 pixels) is considered the best contour. The function saves the coordinates of the center of the circle and its radius, prints them by console, and draws both the outline of the circle (in green) and its center (in red) in the final image. If no outline is detected in the area, it adds “no circle” to the calibration list to indicate the absence of a valid circle. December 2024 35
Surgical Robot for Automation of Craniotomies in Rodents Figure 31: Found contours and coordinates Finally, the function starts a 10-second timer using QTimer to perform a delayed action without blocking the GUI, while processing application events with QApplication.processEvents(). Once the timer is finished, it marks the calibration as completed, prints a message indicating to wait for the model to be trained, and returns the centers_calibration list with the coordinates of the detected centers (or “no circle” values if there was no detection). This function is useful in calibration processes where it is necessary to detect changes in specific regions of the images. Figure 32: Frame took with the detected circles and centres December 2024 36
Surgical Robot for Automation of Craniotomies in Rodents 6.6 Training the Final Model Next, the train_model function is responsible for processing and preparing the previously detected calibration coordinate data and training a regression neural network that maps the pixel coordinates to physical coordinates (millimeters). The main purpose of this function is to ensure that the model can learn the relationship between the points identified by the camera and their actual location in the CNC machine workspace. First, the function receives as input the list of centers, which contains the coordinates of the circles detected during calibration. Since this data may include invalid values, such as “no circle”, these are replaced by preprocessed values or by a predefined value acting as a marker. In this way, the structure and size of the data set are preserved, ensuring that the model can handle both valid and undetected values. Once this step is done, the coordinates are organized and formatted into NumPy matrices to ensure compatibility with machine learning libraries. The input matrix (X) represents the pixel coordinates captured by the camera, while the output matrix (y) corresponds to the target physical coordinates (in millimeters). After this preprocessing, the structure of the neural network is defined. The network is a multilayer perceptron (MLP) composed of an input layer with 2 neurons that receive the X, Y coordinates in pixels, two hidden layers with 16 neurons each and ReLU activation function to capture nonlinear relationships, and finally an output layer with 2 neurons that predict the resulting physical coordinates. To train the network, the Adam optimizer is used, which adjusts the network weights to minimize the mean square error (MSE) loss function, a common metric in regression problems. Training is carried out over a set number of epochs (500), during which the model analyzes the input data and iteratively adjusts its parameters. Once the training process is completed, the neural network is ready to predict new physical coordinates from pixel inputs. The trained model is stored or used directly to transform the coordinates detected by the camera into accurate positions for the CNC machine. December 2024 37
Surgical Robot for Automation of Craniotomies in Rodents Figure 33: Calibration messages in the terminal The train_model function replaces invalid data with preprocessed values, organizes the data into a suitable format, defines and trains a regression neural network, and stores the resulting model. This process allows for accurate conversion between captured image space and physical space, facilitating precise control of the CNC machine. In addition, possible distance differences between the calibration block and the test block must be taken into account, as these can introduce systematic offsets that must be compensated for during model training. It is important to take into account that there is a difference between the Y coordinates from the calibration and the testing bricks. This fact is not important in the first values provided to CNN, since the calibration block is put in the test slot during this process. But a Y-coordinate change has to be made when performing the calibration tuning. In this case, it is to subtract 39.895 millimeters from the Y coordinate. December 2024 38
Surgical Robot for Automation of Craniotomies in Rodents Figure 34: Difference between both blocks 6.7 Predictions The trained neural network is responsible for predicting the physical coordinates from the pixel coordinates obtained by image detection. These predictions allow the points detected on the camera to be transformed into exact positions within the CNC machine’s workspace. When the “move” edge is activated and clicked on the screen (as requested from the terminal, Figure 35) the CNC machine receives the G-code commands corresponding to the coordinates predicted by the neural network. Based on these commands, the drilling tool moves to the target position and descends to the specified depth, drilling the hole at the exact location. Figure 35: Console outputs when prediction is done The prediction and motion process is highly efficient due to the neural network’s ability to learn and generalize the relationship between pixel coordinates and physical positions. This results in high accuracy, as systematic errors are minimized by adjusting the coordinates through the model. The December 2024 39
Surgical Robot for Automation of Craniotomies in Rodents combination of image analysis with CNC machine control ensures that holes are accurately drilled at the desired points, meeting the calibration and positioning requirements of the system. In the Figure 36, the accuracy of the system can be observed. (a) Desired point in red (b) Clear view of the calibration brick in the frame Figure 36: Achieved hole December 2024 40
Surgical Robot for Automation of Craniotomies in Rodents 7.6 Conversion From Pixels to G-code There is the problem that the input to be entered by the user is the millimeters measured by the diameter of the contour to be traced, but the function that calculates the trajectory returns pixels, not millimeters. It is therefore necessary to establish a scale factor between the points of the circumference in the frame and in physical space. This is accomplished by fitting a circle to a set of two-dimensional points using the least squares method, calculating the center and radius that best describe the data. First, the points of the trajectory defined in G-Code are plotted and an estimate for the diameter and center is established. Then, it is fitted using the least squares method to adjust the parameters and refine it further. Finally, the diameter of the marked circumference is computed and a scale factor, calculated based on the ratio between the diameter in pixels and its real representation, is computed. Figure 46: Pixels to mm conversion and adjustment The found conversion was 21.40181 pixels/mm, this value is crucial for the correct performance of the whole system, it is used in CranioBot.py. December 2024 47
Surgical Robot for Automation of Craniotomies in Rodents 8 User Interface The user interface is a fundamental part of the project, it brings the craniotomy tool into contact with the standard user. It is therefore necessary to make the user interface as simple and intuitive as possible. Each part of the user interface is detailed below, all the user interface has been managed from the file cranioBot.ui, it can be seen in Figure 8. 8.1 Video Label In the code, the VideoLabel widget is used as a central element for displaying the frames captured by the camera. This widget is configured within the graphical interface to receive and render images dynamically, allowing the user to observe in real time what the camera is capturing. The widget works as a container that is constantly updated with the processed frame data, integrating seamlessly into the application flow. To display the captured frames, the system uses the OpenCV library to access the capture device and read the images in NumPy array format. These frames, once captured, are transformed into PyQt-compatible QImage objects, adapting their format and dimensions to the widget requirements. Subsequently, the processed frames are assigned to the VideoLabel widget using methods such as setPixmap, which allow the image to be rendered directly in the graphical interface. This cycle runs in a continuous loop, ensuring a constant update of the visual data displayed to the user. In addition to the basic frame display, the VideoLabel widget can also include additional graphical elements, such as marker overlays, outlines, or visual cues generated by other system processes, such as detection or recognition algorithms. These elements are drawn over the frame before being sent to the widget, enriching the visualization with relevant contextual information. This approach makes the VideoLabel widget a versatile tool not only for real-time observation, but also for interaction with the visual results of image processing. Figure 47: VideoLabel widget December 2024 48
Surgical Robot for Automation of Craniotomies in Rodents 8.2 Template Alignment & Calibration Boards This board contains the buttons that manage the commands for starting the calibration, as well as the “hole” command for the semi-manual calibration process and the management of the mouse skull template. In the next subsections, these buttons and sliders are introduced and explained in detail. 8.2.1 Start and Move Buttons The Start and Move buttons have key functions within the system to control the flow of CNC machine operations and interaction with the camera. The Start button initializes the video capture system, activating the camera and starting to display frames in real time within the corresponding widget. This starts the automatic calibration tuning sequence, initiating a series of cascading runs and locking all other buttons while calibration is in progress. On the other hand, the Move button is designed to execute a move command to specific previously calculated coordinates, (provided that the system is calibrated, otherwise a message will be output on the screen indicating that calibration must be performed first). This button uses the results of the neural network or generated trajectories, sending G-code commands to the CNC machine to move to the target position. Both buttons work together to provide efficient flow. Figure 48: Move and Start buttons 8.2.2 Bregma, Lambda and Align Template Buttons The Lambda, Bregma and Align Template buttons are designed to manage key points and template alignment on the workspace (Figure 49). December 2024 49
Surgical Robot for Automation of Craniotomies in Rodents Figure 49: Lambda, Bregma and Align Template Buttons As discussed earlier in the section 4, mouse skulls have very little variability between them, so it is very easy to determine their anatomy by knowing the Lambda and Bregma feature points, which can be seen with the naked eye. With this information what is sought is to be able to apply a template on them to know at all times to which section of the brain is being accessed (Figure 50. Figure 50: Brain template Lambda and Bregma work very similarly to each other, the user clicks on the button, then on the pixel where the point is and the program captures, points and stores it. Pressing the button twice cancels the selection. The operation and display of these buttons can be seen in the Figures 51 - 53. December 2024 50
Surgical Robot for Automation of Craniotomies in Rodents Figure 51: Lambda definition Figure 52: Bregma definition Figure 53: Lambda and bregma console outputs Align Template instead, has a deeper working mechanism. It is responsible for adjusting the position and orientation of the predefined template in relation to captured anatomical landmarks such as lambda and bregma. This function takes the recorded coordinates of both points and calculates a geometric transformation (rotation, translation or scaling, as required) to align the template accurately to December 2024 51
Surgical Robot for Automation of Craniotomies in Rodents the physical workspace. The process ensures that the template is correctly positioned in the coordinate system defined by these points, allowing planned trajectories and operations to match the actual dimensions and orientations of the work area. This is essential to ensure accuracy and reproducibility in applications where accuracy is critical, such as surgical or 3D modeling task. Figure 54: Aligned template All the marks in the frame (bregma, lambda and the template) can be deleted and reset at any moment pressing the button "Reset Template". 8.2.3 Position and Size Sliders Template adjustment sliders allow the user to precisely modify the position and size of the template within the workspace. These tools are essential to ensure that the template aligns correctly with the set reference points (such as lambda and bregma) and with the dimensions of the area of interest. Position sliders: These control the offsets of the template in the X and Y axes. As the sliders are moved, a translation transformation is applied that dynamically adjusts the position of the template in real time. This allows the user to perform a visual or mathematical alignment according to previously defined coordinates, ensuring that the template is properly centered in the work area. Sizing sliders: These allow to modify the scale of the template, i.e. increase or decrease its size to adjust it to the actual dimensions of the object or surface of interest. The adjustment is made uniformly to maintain the original proportion of the template, and modifications are applied in both width and height. This is especially useful in tasks where the template dimensions must match the physical size of an object captured by the camera. December 2024 52
Surgical Robot for Automation of Craniotomies in Rodents Figure 55: Sliders for movement and size 8.3 Trajectory Manager Board The trajectory manager board contains the buttons to manage the size of the contour to be carved, as well as its depth, number of passes and depth per pass. On the other hand, it also manages the user’s trajectory preview, reset and start of the trajectory. 8.3.1 Center, Reset and Start Trajectory Buttons The Center, Reset and Start Trajectory buttons are responsible for positioning the trajectory and displaying a preview of the trajectory through the user interface so that the user can determine whether the trajectory is valid or not. In case it is not valid, the “Reset Trajectory” button will delete it and empty the variable so that the user can determine it again correctly. The trajectory is overlaid with the camera frame, showing red tones for the deeper points and green tones for the points with higher z-dimension (Figure 57). Figure 56: Buttons for centering, starting and resetting the trajectory December 2024 53
Surgical Robot for Automation of Craniotomies in Rodents (a) Trajectory display (b) Trajectory coordinates display in color Figure 57: Trajectory displays If the trajectory is correct, just press the “Start Trajectory” button and the system will start to carve the desired contour on the skull. 8.3.2 Trajectory Features Sliders The sliders associated with the trajectory diameter, height and step parameters allow the user to interactively adjust the geometric characteristics of the toolpaths generated by the system. These controls provide flexibility and precision in setting up the trajectories prior to their execution by the CNC machine. “Trajectory Diameter": Controls the diameter of the circular path to be generated. This slider adjusts the diameter of the circle in the X and Y coordinates, modifying the overall size of the path. By changing the value of this slider, the selected value is used by the system to calculate the points of the circle, ensuring that it fits the area of interest or the dimensions of the physical object to be operated on. “Height": Defines the total height of the path on the Z-axis, that is, the total vertical movement of the path. This allows the user to set the depth or elevation of the path as needed. “Step": Adjusts the step size between each layer in the Z-axis direction. This slider controls the vertical distance traveled between one circular path and the next, allowing you to define the resolution of the movement. A smaller step generates more layers and therefore greater accuracy in tasks such as progressive drilling, while a larger step reduces the number of layers, optimizing run time in less demanding operations. Together, the sliders interact to give the user full control over the dimensions and resolution of threedimensional paths. This ensures that the generated trajectories are customized and suitable for the specific needs of each operation, optimizing both the accuracy and efficiency of the system. December 2024 54
Surgical Robot for Automation of Craniotomies in Rodents Figure 58: Sliders for modifying the diameter of the contour, the total depth and step depth December 2024 55
Surgical Robot for Automation of Craniotomies in Rodents 9 Function List In the development of this project, the efficient management of the different functionalities and their correct implementation is essential for the optimal behavior of the system. This section provides a detailed list of the functions and classes that make up the code structure. Each row in these tables contains a brief description of what the function or class does, as well as the input arguments to feed them and the output outcomes of the function. The functions and classes are designed to interact with each other in a modular fashion, allowing the system to be flexible and easy to maintain. This modular approach also facilitates the integration of new functionality, since each function or class has a specific and well-defined responsibility. In this way, the system is not only efficient, but also scalable and adaptable to possible future modifications. Each table below groups the functions and classes into categories according to their role within the project. Some functions are oriented towards interaction with the user interface, allowing the user to interact seamlessly with the system, while others are related to data processing logic, such as capturing images, handling machine learning models, or controlling external devices such as the GRBL controller or the connected camera. In addition to describing the main functionalities, the tables also specify how the various components of the system are connected to each other. For example, the functions that enable image manipulation communicate with the classes that manage the display in the user interface. Interactions with other modules that control hardware, such as machine movement or drilling in the robotic-assisted surgery process, are also detailed. Detailed knowledge of these functions is crucial for those who wish to thoroughly understand the system architecture or make modifications in the future. This list provides a clear view of how the various pieces of the system fit together, improving the transparency of the code and making it easier to maintain. The tables below provide a detailed description of the key functions and classes in the system, providing information on their purpose, the parameters they work with and the results they generate. It is important to note that some of these functions are dedicated to direct interaction with the hardware, while others deal with the internal logic of the system and the user interface. December 2024 56
Surgical Robot for Automation of Craniotomies in Rodents 12 Environmental Study of the Project During the environmental study of the project, an analysis of the tools and activities carried out during the development of the project and their possible environmental footprint was carried out. Without being a project with a great environmental impact, the greatest (and only possible) saving of negative impact on the environment has been given by optimizing the design of the calibration blocks to save as much plastic as possible, limiting pollution and the carbon footprint of this material. On the other hand, the chips released during calibrations have been collected for later recycling and possible reuse in filament rolls. The aim of all this is to maximize the sustainability of the project, contributing as far as possible to minimize the impact on the environment. December 2024 63
Surgical Robot for Automation of Craniotomies in Rodents 13 Social Study of the Project This prototype marks the first version of a device that will undoubtedly substantially improve the working conditions of laboratory technicians in the field of neurosurgery and neurology. The process of removing a part of the skull by hand took hours and generated fatigue, wear and tear, and in many cases frustration when the surgical intervention was not successful. The creation and use of this device is intended to greatly expedite the early stages of the process, allowing for faster advances in the surgical process. On the other hand, it avoids some of the ethical compromise intrinsic to in-vivo experiments, reducing to a minimum the cases of animals that die before the experiments are even carried out. Politechnique Montréal guarantees equal conditions and opportunities for all people regardless of gender, race, religion or sexual condition. The project has been smooth and I have been allowed to work comfortably thanks to the attitude of the whole department, who have helped me to integrate and make me feel at home. December 2024 64
Surgical Robot for Automation of Craniotomies in Rodents Conclusion In the project carried out, an automated device has been developed to perform precise trajectories in the field of craniotomies in small rodents (mice). From an approach that combines Deep Learning, computer vision and CNC control, it has been successfully achieved to carry out such trajectories with high accuracy. Throughout the project, several strategies for the calibration and start-up of the system have been tested, being a semi-automatic calibration the finally chosen one, refining the accuracy of the machine with each start-up. A user-friendly and user-friendly user interface has also been developed, allowing templates to be aligned for clearer access to the animal’s brain. This interface also allows to preview and modify trajectories. Tests performed on both 2D and 3D trajectories showed that the system is capable of generating accurate movements, adapting to experimental needs and minimizing errors in execution. Likewise, the incorporation of neural networks allowed precise mapping of the pixel coordinates captured by the camera to physical coordinates in the workspace, ensuring the correct interaction between the visual data and the CNC hardware. Although the developed system shows promising results, its practical implementation reveals certain limitations, such as dependence on specific calibration conditions and sensitivity to mechanical errors in the equipment. Nevertheless, these limitations open new opportunities for improvement, such as the optimization of the learning model and the integration of more advanced image processing techniques. In conclusion, this work lays the groundwork for a robust and adaptable system in rodent neurosurgery applications, contributing to the advancement in the automation of experimental procedures and highlighting the relevance of interdisciplinarity in the design and development of technological solutions. Future improvements will focus on increasing the accuracy, reliability and versatility of the system to face more complex and demanding scenarios. December 2024 65
References Company, Qt (2024). Qt Design Studio: UI Design and Development Tool.URL:https://www.qt. io/product/ui-design-tools. Developers, Denvi (2024). Candle: GRBL Controller Software for CNC Machines.URL:https : //github.com/Denvi/Candle. Developers, Pylablib (2023). Pylablib: Laboratory Instruments Control Library.URL:https : / / pylablib.readthedocs.io/. Developers, PySerial (2023). PySerial: Python Serial Port Extension.URL:https://pyserial. readthedocs.io/. Developers, Scikit-learn (2023). Scikit-learn: Machine Learning in Python.URL:https://scikitlearn.org/. Developers, SciPy (2023). SciPy: Scientific Computing with Python.URL:https://scipy.org/. Developers, TensorFlow (2023). TensorFlow: Open Source Machine Learning Framework.URL: https://www.tensorflow.org/. Fernández, Ander (2023). How to Code a Neural Network from Scratch in Python.URL:https : //anderfernandez. com/en/blog/ how- to- codeneural- networkfrom- scratchin- python/. Goodfellow, Ian, Yoshua Bengio, and Aaron Courville (2016). Deep Learning. MIT Press. URL: https://www.deeplearningbook.org/. Hunter, John D. and Matplotlib Development Team (2023). Matplotlib: Visualization with Python. URL:https://matplotlib.org/. Inc., Autodesk (2024). Autodesk Fusion: Integrated CAD, CAM, and CAE Software.URL:https: //www.autodesk.com/products/fusion-360. LabeoTech (2024). Small Animal Monitoring System.URL:https://www.labeotech.com/product/ small-animal-monitoring-system/. Neuroanatomy, Frontiers in (2022). “Atlas estereotáxico del cerebro de ratas jóvenes”. In: Frontiers in Neuroanatomy.URL:https://www.frontiersin.org/journals/neuroanatomy/articles/ 10.3389/fnana.2022.968320/full. Oliphant, Travis E. and NumPy Developers (2023). NumPy: The fundamental package for scientific computing with Python.URL:https://numpy.org/. Paxinos, G. and C. Watson (2013). The Rat Brain in Stereotaxic Coordinates. Academic Press. Research, Prusa (2024). Original Prusa MK4S 3D Printer.URL:https : / / www . prusa3d . com / product/original-prusa-mk4s-3d-printer-5/. Schmued, L. and J. Fallon (1994). “Markers for neuronal tracing”. In: Trends in Neurosciences. Team, OpenCV (2023). OpenCV: Open Source Computer Vision Library.URL:https://opencv. org/. Thompson, Phil (2023). PyQt5: Python bindings for the Qt5 application framework.URL:https: //riverbankcomputing.com/software/pyqt/intro. 66
Thorlabs, Inc. (2023). Thorlabs TSI SDK: Software Development Kit for Thorlabs Instruments.URL: https://www.thorlabs.com/. – (2024a). DCC1645C: 1.6 MP CMOS Camera, USB 2.0.URL:https://www.thorlabs.com/ thorProduct.cfm?partNumber=DCC1645C. – (2024b). ThorCam: Camera Control and Image Acquisition Software.URL:https://www.thorlabs. com/software_pages/ViewSoftwarePage.cfm?Code=ThorCam. 67
14 Annex The blueprints of the calibration and test pieces, as well as the code used in the project, are attached as an appendix. 68
BLUEPRINTS ANNEX 69
1 A 2345678 1 2 345678 B C D E F A B C D E F Dept. Technical reference Created by Approved by Document type Document status Title DWG No. Rev. Date of issue Sheet 20/12/2024 1/1 Calibration Brick Nicolas Rinaldi 22 40 22 20 10 6.98 Ø5.04 24
1 A 2345678 1 2 345678 B C D E F A B C D E F Dept. Technical reference Created by Approved by Document type Document status Title DWG No. Rev. Date of issue Sheet 20/12/2024 1/1 Test Brick Nicolas Rinaldi 20 10 10 84 Ø 6.98 24 18.87 31.58 33.55 5
CODE ANNEX 72
225 cv2.rectangle(img_after, (x, y), (x +w, y +h), (255,255,0), 2)# Rectángulo en cian,→ 226 227 # Looking for contours in the zone 228 contours, _ =cv2.findContours(roi, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE),→ 229 230 # Biggest radius circle 231 max_radius = 0 232 best_center =None 233 for contour in contours: 234 # Adjusting circle to the actual contour 235 (cx, cy), radius =cv2.minEnclosingCircle(contour) 236 if radius >max_radius: 237 max_radius =radius 238 best_center =(int(cx) +x, int(cy) +y) 239 240 # Drawing the biggest circle 241 if best_center and max_radius >4and max_radius < 16: 242 center =best_center 243 radius =int(max_radius) 244 245 # Printing the centre and radius of the biggest circle 246 print(f"Biggest circle in zone ({x},{y},{w},{h}):") 247 print(f"Centre of the circle: X={center[0]}, Y={center[1]}") 248 print(f"Radius of the circle: {radius}") 249 250 # Drawing the circle in the image 251 cv2.circle(img_after, center, radius, (0,255,0), 2)# Contour in green,→ 252 cv2.circle(img_after, center, 1, (255,0,0), 1)# Center in red 253 254 # Append circle to the circles list 255 self.video_label.circles.append((center[0], center[1], radius)) 256 self.video_label.show_marker =True 257 self.video_label.update() 258 259 # Append circle to calibration list 260 self.centers_calibration.append(center[0]) 261 self.centers_calibration.append(center[1]) 79
262 263 else: 264 # If there is no contour founded 265 self.centers_calibration.append("no circle") 266 self.centers_calibration.append("no circle") 267 print(f"No contour found in zone ({x},{y},{w},{h}).") 268 269 270 print("Calibration movements completed, wait 10 seconds") 271 # Showing the image with differences and found circles 272 #cv2.imshow("Differenc and detectionn", img_after) 273 274 # Wait 10 seconds 275 timer2 =QTimer(self) 276 timer2.setSingleShot(True) 277 timer2.timeout.connect(self.delayed_action2) 278 timer2.start(10000)# 10000 ms = 10 seconds 279 280 # Do not block graphic interface 281 while not self.delayed_action_complete2: 282 QtWidgets.QApplication.processEvents() 283 284 # Calibration completed flank 285 self.delayed_action_complete2 =False 286 self.calibration_completed =True 287 print("Please, wait for the model to be trained") 288 289 return self.centers_calibration 290 291 292 def pushButton_align_template_pressed(self): 293 294 if self.align_template_pushed == False: 295 self.align_template_pushed =True 296 self.lambda_pushed =False 297 self.bregma_pushed =False 298 self.move_pushed =False 299 80
300 if self.calibration_completed and self.align_template_pushed and not self.bregma_pushed and not self.lambda_pushed and not self.move_pushed and not self.center_trajectory_pushed: ,→ ,→ 301 302 if not self.bregma_defined and not self.lambda_defined: 303 print("Please define bregma and lambda before") 304 305 elif not self.bregma_defined and self.lambda_defined: 306 print("Please define bregma before") 307 308 elif self.bregma_defined and not self.lambda_defined: 309 print("Please define lambda before") 310 311 elif self.bregma_defined and self.lambda_defined: 312 self.align_signal.emit(True) 313 print(self.align_signal) 314 315 self.align_template_pushed =False 316 317 else: 318 print("Centre of the tempalte alignment cancelled, please push the button again"),→ 319 self.align_template_pushed =False 320 321 322 def pushButton_bregma_pressed(self): 323 324 if self.bregma_pushed == False: 325 print("Click on bregma") 326 self.align_template_pushed =False 327 self.bregma_pushed =True 328 self.lambda_pushed =False 329 self.move_pushed =False 330 self.center_trajectory_pushed =False 331 332 else: 333 print("Bregma selection cancelled, please push the button again") 334 self.bregma_pushed =False 335 self.video_label.circles_to_draw[1]=None 336 81
337 338 339 def pushButton_lambda_pressed(self): 340 341 if self.lambda_pushed == False: 342 print("Click on lambda") 343 self.align_template_pushed =False 344 self.bregma_pushed =False 345 self.lambda_pushed =True 346 self.move_pushed =False 347 self.center_trajectory_pushed =False 348 349 else: 350 print("Lambda selection cancelled, please push the button again") 351 self.lambda_pushed =False 352 self.video_label.circles_to_draw[0]=None 353 354 355 def pushButton_move_pressed(self): 356 357 if self.move_pushed == False: 358 print("Please click on a point on the screen to move the drill to that location"),→ 359 self.align_template_pushed =False 360 self.bregma_pushed =False 361 self.lambda_pushed =False 362 self.move_pushed =True 363 self.center_trajectory_pushed =False 364 365 def pushButton_center_trajectory_pressed(self): 366 if self.center_trajectory_pushed == False: 367 print("Please define the center of the trajectory") 368 self.align_template_pushed =False 369 self.bregma_pushed =False 370 self.lambda_pushed =False 371 self.move_pushed =False 372 self.center_trajectory_pushed =True 373 374 else: 82
375 print("Center of the trajectory cancelled, please push the button again"),→ 376 self.center_trajectory_pushed =False 377 self.points_trajectory =[] 378 379 def pushButton_start_trajectory_pressed(self): 380 381 self.total_decrease = 0 382 383 if not self.start_trajectory_pushed and self.trajectory_ready: 384 385 self.start_trajectory =True 386 self.align_template_pushed =False 387 self.bregma_pushed =False 388 self.lambda_pushed =False 389 self.move_pushed =False 390 self.center_trajectory_pushed =False 391 print("Starting trajectory") 392 393 self.approach_point =controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, window.center_trajectory[0], window.center_trajectory[1]) ,→ ,→ 394 self.approach_point =np.append(self.approach_point, window.center_trajectory[2]),→ 395 controller.move_to(self.approach_point[0], self.approach_point[1]) 396 print(self.approach_point[0], self.approach_point[1]) 397 controller.send_command(f"Z-27 F400") 398 controller.send_command("M03 S8000") 399 # self.first_iteration = True 400 401 self.first_point =controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, self.points_trajectory_copy[0][0], self.points_trajectory_copy[0][1]) ,→ ,→ 402 self.rx=self.approach_point[0]-self.points_trajectory_copy[0][0] 403 self.ry =self.approach_point[1]-self.points_trajectory_copy[0][1] 404 self.radius_trajectory_gcode =sqrt(self.rx**2 + self.ry**2) 405 406 for cicles in range(int(self.cicles)): 407 408 for x, y, z in self.points_trajectory_copy: 83
409 410 # if self.first_iteration: 411 412 # gcode_coords = controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, x, y),→ 413 # controller.send_command(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} Z{z:.2f} F100"),→ 414 # # controller.send_command(f"G02 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} I{self.i_offset} J{self.j_offset} F100") ,→ ,→ 415 # self.first_iteration = False 416 # # self.gcode_coords_before=gcode_coords.copy() 417 # # print(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} Z{z:.2f} F100"),→ 418 # else: 419 gcode_coords =controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, x, y),→ 420 # print(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} Z{-27 - (cicles)*self.step_trajectory.value()} F300") ,→ ,→ 421 controller.send_command(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f}Z{z:.2f}F100"),→ 422 # controller.send_command(f"G02 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} R{self.radius_trajectory_gcode} F100") ,→ ,→ 423 # self.gcode_coords_before = gcode_coords.copy() 424 # print(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} Z{z:.2f} F100"),→ 425 426 self.first_point =controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, self.points_trajectory_copy[0][0], self.points_trajectory_copy[0][1]) ,→ ,→ 427 controller.send_command(f"G01 X{self.first_point[0]} Y{self.first_point[1]} Z{self.points_trajectory_copy[0][2]:.2f}F100") ,→ ,→ 428 # print("firts point", f"G01 X{self.first_point[0]} Y{self.first_point[1]} Z{self.points_trajectory_copy[0][2]:.2f} F150") ,→ ,→ 429 430 # print(f"Z {-27 - (cicles)*self.step_trajectory.value()} F300") 84
431 # controller.send_command(f"Z {-32.5 - (cicles)*self.step_trajectory.value()} F150"),→ 432 433 for iin range(len(self.points_trajectory_copy)): 434 print(self.points_trajectory_copy[i][2]) 435 print(" ") 436 print(" ") 437 print(" ") 438 self.points_trajectory_copy[i][2]= self.points_trajectory_copy[i][2]- self.step_trajectory.value() ,→ ,→ 439 print(self.points_trajectory_copy[i][2]) 440 441 self.total_decrease =self.total_decrease- self.step_trajectory.value(),→ 442 443 print("next") 444 print("next") 445 print("next") 446 print("next") 447 print("next") 448 449 # # controller.send_command(f"G01 Z{-32.5 - self.height_trajectory.value()} F150"),→ 450 451 for iin range(len(self.points_trajectory_copy)): 452 print(self.points_trajectory_copy[i][2]) 453 self.points_trajectory_copy[i][2]= self.points_trajectory_copy[i][2]- self.step_trajectory.value() ,→ ,→ 454 print(" ") 455 print(" ") 456 print(" ") 457 print(self.points_trajectory_copy[i][2]) 458 459 self.total_decrease =self.total_decrease- self.step_trajectory.value(),→ 460 461 for x, y, z in self.points_trajectory_copy: 85
462 gcode_coords =controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, x, y),→ 463 controller.send_command(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f}Z{z:.2f}F100")#DESCOMENTAR,→ 464 print(z) 465 466 # gcode_coords = controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, x, y),→ 467 # # print(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} Z{-27 - self.height_trajectory.value()} F300"),→ 468 # controller.send_command(f"G01 X{gcode_coords[0]:.2f} Y{gcode_coords[1]:.2f} Z{-27 - self.height_trajectory.value()} F150") ,→ ,→ 469 470 471 472 print("cicles",self.cicles) 473 print("height decrease",self.total_decrease) 474 475 controller.send_command(f"Z {-21}F300") 476 controller.send_command("M05") 477 controller.move_to(0.538,120.6-39.895) 478 self.center_trajectory_pushed =False 479 480 elif not self.start_trajectory_pushed and not self.trajectory_ready: 481 print("Please, select a trajectory before (You can do this by choosing the radius in the box, then clicking on button *Centre Trajectory* and then clicking on the desired centre)") ,→ ,→ 482 483 elif self.start_trajectory_pushed: 484 print("Please wait, trajectory in process") 485 486 487 488 def reset_marker(self): 489 self.video_label.show_marker =False 490 self.video_label.centers.clear() 491 self.video_label.contours.clear() 492 self.video_label.circles_to_draw =[None,None] 493 self.video_label.update() 86
494 self.bregma_defined =False 495 self.lambda_defined =False 496 self.lambda_signal.emit(None,None) 497 self.bregma_signal.emit(None,None) 498 self.align_signal.emit(False) 499 self.camera_handler.reset_template() 500 501 502 def reset_trajectory(self): 503 504 window.video_label.update_trajectory_points([]) 505 self.update() 506 self.trajectory_ready =False 507 508 509 def on_image_clicked(self, x_pixel, y_pixel): 510 # Registers the clicks on the image and shows them in the terminal 511 print(f"Clicked on: x={x_pixel}, y={y_pixel}") 512 513 if self.calibration_completed and self.bregma_pushed and not self.lambda_pushed and not self.move_pushed and not self.center_trajectory_pushed: ,→ ,→ 514 # Store circle coordinates in the circles list 515 self.video_label.circles_to_draw[1]=(x_pixel, y_pixel, 2) 516 #print(f"Bregma: ({x_pixel}, {y_pixel})") 517 self.bregma_signal.emit(x_pixel, y_pixel) 518 self.update() 519 self.bregma_pushed =False 520 self.bregma_defined =True 521 522 elif self.calibration_completed and not self.bregma_pushed and self.lambda_pushed and not self.move_pushed and not self.center_trajectory_pushed: ,→ ,→ 523 # Store circle coordinates in the circles list 524 self.video_label.circles_to_draw[0]=(x_pixel, y_pixel, 2) 525 self.lambda_signal.emit(x_pixel, y_pixel) 526 self.update() # 527 self.lambda_pushed =False 528 self.lambda_defined =True 529 87
530 531 elif self.calibration_completed and not self.bregma_pushed and not self.lambda_pushed and self.move_pushed and not self.center_trajectory_pushed: ,→ ,→ 532 print("moving") 533 self.prediction =controller.convert_pixels_to_gcode(model, scaler_X, scaler_y, x_pixel, y_pixel),→ 534 controller.hole(self.prediction[0], self.prediction[1], -32.6, 1.5),→ 535 controller.send_command(f"Z-27 F400") 536 controller.move_to(0.538,120.6-39.895) 537 #controller.move_to(0.538, 120.6) 538 self.move_pushed =False 539 540 elif self.calibration_completed and not self.bregma_pushed and not self.lambda_pushed and not self.move_pushed and self.center_trajectory_pushed: ,→ ,→ 541 self.center_trajectory =[x_pixel, y_pixel, 35.2]#32.819] 542 print("starting sequence") 543 self.diameter_trajectory =self.findChild(QtWidgets.QDoubleSpinBox, "doubleSpinBox_trajectory_diameter"),→ 544 self.height_trajectory =self.findChild(QtWidgets.QDoubleSpinBox, "doubleSpinBox_height"),→ 545 self.step_trajectory =self.findChild(QtWidgets.QDoubleSpinBox, "doubleSpinBox_step"),→ 546 self.points_trajectory, self.cicles, self.last_cicle = controller.trajectory(window.center_trajectory, [3,2,-8], self.diameter_trajectory.value()*21.40181, self.height_trajectory.value(), self.step_trajectory.value()) ,→ ,→ ,→ 547 # print(type(window.center_trajectory), window.center_trajectory) 548 self.points_trajectory_copy =deepcopy(self.points_trajectory) 549 self.points_trajectory_copy[:,2]=self.points_trajectory_copy[:,2]/⌋ 21.40181-self.center_trajectory[2],→ 550 551 ## Visualizing the trajectory in 3D 552 fig =plt.figure() 553 ax =fig.add_subplot(111, projection='3d') 554 ax.scatter(self.points_trajectory_copy[:,0], self.points_trajectory_copy[:,1]/21.40181, self.points_trajectory_copy[:,2]/21.40181, color='b') ,→ ,→ 88
146 147 painter.drawEllipse(QtCore.QPoint(x, y), radius, radius) 148 149 painter.end() 150 151 152 153 class CameraHandler: 154 def __init__(self, label, slider_width, slider_height, move_x, move_y,ui_instance):,→ 155 self.video_label =label 156 self.slider_width =slider_width 157 self.slider_height =slider_height 158 self.move_x =move_x 159 self.move_y =move_y 160 self.show_template =False # Not showing the template fromm the start 161 self.retrieved_lambda =[None,None] 162 self.retrieved_bregma =[None,None] 163 self.retrieved_align =False 164 self.template_aligned =False 165 self.aligned_template_pixmap =None 166 self.previous_x = 0 167 self.previous_y = 0 168 169 170 171 ui_instance.lambda_signal.connect(self.update_lambda) 172 ui_instance.bregma_signal.connect(self.update_bregma) 173 ui_instance.align_signal.connect(self.update_align) 174 175 176 pll.par["devices/dlls/uc480"]="C:\\Program Files\\Thorlabs\\Scientific Imaging\\ThorCam",→ 177 self.cam =uc480.UC480Camera(cam_id=1) 178 frame =self.cam.snap() 179 180 if frame is not None: 181 height, width, _ =frame.shape 182 self.video_label.setFixedSize(width, height) 183 self.video_label.setScaledContents(True) 95
184 self.timer =QTimer() 185 self.timer.timeout.connect(self.update_frame) 186 self.timer.start(30) 187 188 self.slider_width.valueChanged.connect(self.update_template_size) 189 self.slider_height.valueChanged.connect(self.update_template_size) 190 191 self.template_width =self.slider_width.value() 192 self.template_height =self.slider_height.value() 193 194 self.move_x.valueChanged.connect(self.update_template_position) 195 self.move_y.valueChanged.connect(self.update_template_position) 196 197 self.top_left_x =self.move_x.value() 198 self.top_left_y =self.move_y.value() 199 200 201 def update_template_size(self): 202 self.template_width =self.slider_width.value() 203 self.template_height =self.slider_height.value() 204 self.resize_template(self.template_width, self.template_height) 205 206 def update_template_position(self): 207 # Updates coordinates based on slider values 208 self.top_left_x =self.move_x.value() 209 self.top_left_y =self.move_y.value() 210 211 # Calculates the movement from current position 212 delta_x =self.top_left_x -self.previous_x 213 delta_y =self.top_left_y -self.previous_y 214 215 # Stores the new possition 216 self.previous_x =self.top_left_x 217 self.previous_y =self.top_left_y 218 219 # Moves the template 220 self.move_template(delta_x, delta_y) 221 222 # self.top_left_x = self.move_x.value() 223 # self.top_left_y = self.move_y.value() 96
224 # self.move_template() 225 226 def update_lambda(self, x, y): 227 # Updates lambda irl 228 self.retrieved_lambda =[x, y] 229 print(f"Lambda: ({self.retrieved_lambda})") 230 231 def update_bregma(self, x, y): 232 # Updates bregma irl 233 self.retrieved_bregma =[x, y] 234 print(f"Bregma: ({self.retrieved_bregma})") 235 236 def update_align(self, status): 237 238 if status: 239 print("Align status is True. Aligning template...") 240 aligned_pixmap =self.align_template( 241 'C:\\Users\\nico1\\Desktop\\brain_template_with_borders_fixed.png', 242 [self.retrieved_lambda, self.retrieved_bregma], 243 [[469,490], [668,490]] 244 ) 245 246 if aligned_pixmap: 247 self.template_aligned =True 248 self.aligned_template_pixmap =aligned_pixmap # Stores the template to show it in every frame,→ 249 print("Template aligned and ready for display.") 250 else: 251 print("Failed to align template.") 252 else: 253 print("Align status is False. Template alignment not triggered.") 254 255 def align_template(self, template_path, image_points, template_points): 256 # Loading the template 257 template =cv2.imread(template_path, cv2.IMREAD_UNCHANGED) 258 if template is None: 259 print("Error: The template could not be loaded.") 260 return None 261 print(f"Original size of the template: {template.shape[1]}x{template.shape[0]}"),→ 97
262 263 # Reference points 264 (x1_img, y1_img), (x2_img, y2_img) =image_points 265 (x1_tpl, y1_tpl), (x2_tpl, y2_tpl) =template_points 266 267 # Scale 268 dist_img =np.sqrt((x2_img -x1_img) **2+(y2_img -y1_img) ** 2) 269 dist_tpl =np.sqrt((x2_tpl -x1_tpl) **2+(y2_tpl -y1_tpl) ** 2) 270 scale =dist_img /dist_tpl 271 print(f"Scale calculated: {scale:.2f}") 272 273 # Resize 274 h,w=template.shape[:2] 275 new_w, new_h =int(w *scale), int(h *scale) 276 resized_template =cv2.resize(template, (new_w, new_h), interpolation=cv2.INTER_LINEAR),→ 277 print(f"Resized size: {new_w}x{new_h}") 278 279 # Rotation 280 angle_img =math.atan2(y2_img -y1_img, x2_img -x1_img) 281 angle_tpl =math.atan2(y2_tpl -y1_tpl, x2_tpl -x1_tpl) 282 rotation_angle =math.degrees(angle_tpl -angle_img) 283 print(f"Rotation angle: {rotation_angle:.2f}°") 284 rotation_matrix =cv2.getRotationMatrix2D((new_w // 2, new_h // 2), rotation_angle, 1.0),→ 285 rotated_template =cv2.warpAffine(resized_template, rotation_matrix, (new_w, new_h), borderMode=cv2.BORDER_CONSTANT, borderValue=(0,0, 0,0)) ,→ ,→ 286 print(f"Size after rotation: {rotated_template.shape[1]}x{rotated_template.shape[0]}"),→ 287 288 # Movemnet 289 x_offset =x1_img -(x1_tpl *scale) 290 y_offset =y1_img -(y1_tpl *scale) 291 print(f"Offset: x={x_offset}, y={y_offset}") 292 293 # Dinamic output dimensions 294 output_width =max(rotated_template.shape[1], self.video_label.width()) 295 output_height =max(rotated_template.shape[0], self.video_label.height()) 296 output_image =np.zeros((output_height, output_width, 4), dtype=np.uint8) 98
297 print(f"Dinamic dimensions of the output image: {output_width}x{output_height}"),→ 298 299 # Positioning of the template 300 y1 =max(0,int(y_offset)) 301 y2 =min(int(y_offset) +rotated_template.shape[0], output_image.shape[0]) 302 x1 =max(0,int(x_offset)) 303 x2 =min(int(x_offset) +rotated_template.shape[1], output_image.shape[1]) 304 print(f"Adjusted positioning coordinates: x1={x1}, x2={x2}, y1={y1}, y2={y2}"),→ 305 306 # Applying aligned template 307 output_image[y1:y2, x1:x2] =rotated_template[0:y2 -y1, 0:x2 -x1] 308 309 # Converting to QPixmap 310 height, width, _ =output_image.shape 311 bytes_per_line =4*width 312 qimg =QImage(output_image.data, width, height, bytes_per_line, QImage.Format_ARGB32),→ 313 pixmap =QPixmap.fromImage(qimg) 314 print(f"Final dynamic size of QPixmap: {pixmap.width()}x{pixmap.height()}"),→ 315 316 self.aligned_template_pixmap =pixmap 317 self.video_label.setPixmap(pixmap) 318 self.video_label.update() 319 return pixmap 320 321 322 323 def resize_template(self, delta_width, delta_height): 324 325 if not self.template_aligned: 326 print("Error: There is not aligned template to resize.") 327 return 328 329 # Veryfing the pixmap is not empty 330 if self.aligned_template_pixmap.isNull(): 331 print("Error: QPixmap is empty.") 332 return 99
333 334 # QPixmap to QImage 335 qimg =self.aligned_template_pixmap.toImage() 336 337 # Image format check 338 if qimg.format() != QImage.Format_ARGB32: 339 print("The format of the iage is not ARGB32. Converting...") 340 qimg =qimg.convertToFormat(QImage.Format_ARGB32) 341 342 # Getv image data as np.array 343 width =qimg.width() 344 height =qimg.height() 345 channels = 4 # ARGB32 346 ptr =qimg.bits() 347 ptr.setsize(qimg.byteCount()) 348 img =np.array(ptr).reshape(height, width, channels) 349 350 # New size 351 new_width =max(1, width +delta_width) # avoid negative values 352 new_height =max(1, height +delta_height) # avoid negative values 353 354 # Resize the template 355 resized_template =cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_LINEAR),→ 356 357 # Convert again to pixmap 358 resized_qimg =QImage( 359 resized_template.data, 360 new_width, 361 new_height, 362 channels *new_width, 363 QImage.Format_ARGB32 364 ) 365 self.aligned_template_pixmap =QPixmap.fromImage(resized_qimg) 366 367 # Refresh the visualization 368 self.video_label.setPixmap(self.aligned_template_pixmap) 369 print(f"Resized template: {new_width}x{new_height}.") 370 371 100
372 373 # def move_template(self, delta_x, delta_y): 374 375 376 # return 377 378 379 def move_template(self, delta_x, delta_y): 380 if not self.template_aligned: 381 print("Error: No aligned template to move.") 382 return 383 384 if self.aligned_template_pixmap.isNull(): 385 print("Error: QPixmap is empty.") 386 return 387 388 # Convert QPixmap to QImage 389 qimg =self.aligned_template_pixmap.toImage() 390 391 if qimg.format() != QImage.Format_ARGB32: 392 qimg =qimg.convertToFormat(QImage.Format_ARGB32) 393 394 # Get image data as numpy array 395 width =qimg.width() 396 height =qimg.height() 397 channels = 4 # ARGB32 398 ptr =qimg.bits() 399 ptr.setsize(qimg.byteCount()) 400 img =np.array(ptr).reshape(height, width, channels) 401 402 # Create an empty canvas for the new position 403 output_width =max(self.video_label.width(), width +abs(delta_x)) 404 output_height =max(self.video_label.height(), height +abs(delta_y)) 405 output_image =np.zeros((output_height, output_width, channels), dtype=np.uint8),→ 406 407 # Calculate the new position 408 x_offset =max(0, delta_x) 409 y_offset =max(0, delta_y) 410 101
411 # Place the image in the new position 412 y1 =y_offset 413 y2 =y_offset +height 414 x1 =x_offset 415 x2 =x_offset +width 416 417 output_image[y1:y2, x1:x2] =img 418 419 # Convert back to QPixmap 420 moved_qimg =QImage( 421 output_image.data, 422 output_width, 423 output_height, 424 channels *output_width, 425 QImage.Format_ARGB32 426 ) 427 self.aligned_template_pixmap =QPixmap.fromImage(moved_qimg) 428 429 # Update the display 430 self.video_label.setPixmap(self.aligned_template_pixmap) 431 print(f"Template moved by ({delta_x},{delta_y}).") 432 433 434 def reset_template(self): 435 print("Resetting template alignment...") 436 self.template_aligned =False 437 self.aligned_template_pixmap =None 438 self.video_label.clear() 439 self.update_frame() 440 self.first_paint_event =True 441 442 def update_frame(self): 443 frame =self.cam.snap() 444 if frame is not None: 445 start_x, start_y = 63,265 446 width, height =697-start_x, 669 - start_y 447 roi =frame[start_y:start_y+height, start_x:start_x+width] 448 rgb_frame =cv2.cvtColor(roi, cv2.COLOR_BGR2RGB) 449 450 height, width, channel =rgb_frame.shape 102
451 bytes_per_line =channel *width 452 qimg =QImage(rgb_frame.data, width, height, bytes_per_line, QImage.Format_RGB888),→ 453 pixmap =QPixmap.fromImage(qimg) 454 455 painter =QPainter(pixmap) 456 457 if self.template_aligned and self.aligned_template_pixmap is not None: 458 scaled_template =self.aligned_template_pixmap.scaled( 459 self.video_label.width(), 460 self.video_label.height(), 461 Qt.KeepAspectRatio, 462 Qt.SmoothTransformation 463 ) 464 painter.setOpacity(0.5) 465 painter.drawPixmap(0,0, scaled_template) 466 467 painter.end() 468 self.video_label.setPixmap(pixmap) 469 self.video_label.setFixedSize(width, height) 470 471 def stop_camera(self): 472 self.cam.close() 473 self.timer.stop() 474 103
grbl_Controller.py 1import serial 2import time 3import scipy 4import numpy as np 5from PyQt5.QtCore import pyqtSignal, QObject 6from tensorflow.keras.models import Sequential 7from tensorflow.keras.layers import Dense 8from sklearn.preprocessing import MinMaxScaler 9from PyQt5.QtCore import QTimer 10 11 12 class GRBLController(QObject): 13 14 def __init__(self, port, baudrate=115200, timeout=1): 15 super(GRBLController, self).__init__() # Llamada al constructor de QObject,→ 16 self.port =port 17 self.baudrate =baudrate 18 self.timeout =timeout 19 self.serial_connection =None 20 21 def connect(self): 22 """Establish connection to GRBL controller""" 23 try: 24 self.serial_connection =serial.Serial(self.port, self.baudrate, timeout=self.timeout),→ 25 time.sleep(2)# Wait for GRBL to initialize 26 self.serial_connection.flushInput() # Flush input buffer 27 print("Connected to GRBL") 28 except Exception as e: 29 print(f"Failed to connect to GRBL: {e}") 30 31 def disconnect(self): 32 """Close serial connection""" 33 if self.serial_connection: 34 self.serial_connection.close() 35 print("Disconnected from GRBL") 36 37 def send_command(self, command): 104
251 def convert_pixels_to_gcode(self,model, scaler_X, scaler_y, x_pixel, y_pixel):,→ 252 # Scaling input coordinates 253 punto_pixel_scaled =scaler_X.transform([[x_pixel, y_pixel]]) 254 255 # Making prediction 256 prediccion_scaled =model.predict(punto_pixel_scaled) 257 258 # Descalating the prediction to gcode coordinates 259 prediccion =scaler_y.inverse_transform(prediccion_scaled) 260 print(f"prediction: [{prediccion[0][0]:.3f},{prediccion[0][1]:.3f}]") 261 return prediccion[0]# Retrieving the coordinate in GCode 262 263 def unlock(self): 264 """Unlock GRBL by sending the $X command""" 265 return self.send_command("$X") 266 267 def home(self): 268 """Home the machine by sending the G28 command""" 269 return self.send_command("$H") 270 271 272 273 # Usage Example: 274 # controller = GRBLController(port='/dev/ttyUSB0') 275 # controller.connect() 276 # response = controller.move_to(x=10, y=20, z=5) 277 # print("GRBL Response:", response) 278 # controller.disconnect() 111