pythonopencvubuntucamerapyusb

Controlling Stepper motors and Camera simultaneously


what is the best way to control a stepper motor and camera simultaneously?

Suppose the camera is placed on a linear stage (stepper motor) and I want to move the stage in 1 mm steps and capture a frame at the end of each step. Both devices (Camera and the stage) are connected to my computer (Ubuntu 18.04.3 LTS) via 2 different USB 2.0 ports.

My script for the camera looks something like:

def camera():
    ...
    ...
    ...
    while(True):
        cv2.imshow('live', frame)
        ueye.is_ExitCamera(hCam2)
        cv2.destroyAllWindows()

if __name__ == "__main__":
    camera()

and outputs live broadcast from the camera.

For the motor something like:

i = 0
while i < 6:           # Move 6 times
    stepper.Move(0.5)  # Moves forward by 0.5 mm
    time.sleep(1)      # Sleeps for a second
    i += 1

time.sleep(2)
print("\nProcess End\n")
close()                # closes port 

and moves and sleeps as desired.

Both scripts run sucessfully when executed seperately. However, how do I combine these scripts so that I can take a picture at the end of each step? For the example adressed above for moving 6 times, I want to get 6 images at the end, captured at the end of each step. Should one use multithreading, multiprocessing?... Both devices are connected to my computer via 2 seperate USB 2.0 ports. I'm not a beginner in programming, but not an expert either so any suggestions will be kindly appreciated.


Solution

  • It there a reason that you can't call some function that captures an image on each step?

    # import modules for camera and stepper control
    
    def step_and_capture(steps=6):
      images = []
      for x in range(steps):
        stepper.Move(0.5)
        image = cam_capture_method() # returns a photo or it could write to somewhere
        time.sleep(1)
      # save the images to folder?
    
    if __name__ == "__main__":
        step_and_capture()