Macro Pi – Focus Stacking using Raspberry Pi

Here’s another in the series of articles of photographic uses for the Raspberry Pi SBC (Single Board Computer). This time, it’s re-purposing an old flatbed scanner as a macro rail for focus stacking images in macro photography.

The Plan

There’s a common issue with shooting macro photography, and that’s the limitation in depth of field (or depth of focus). It can be as little as 0.5mm, depending on the camera settings and magnification you’re trying to achieve. A solution to this is to take several images, each one moving closer to the subject by a tiny amount. Each image will have a different part of the subject in focus. You can then combine all the sharp parts of the images together using some free software called CombineZM, and end up with a completely sharp image from front to back of the subject. The difficulty with this is moving the camera accurately at such small distances. Once solution is to turn the zoom ring on your lens slightly, but that’s still hit-and-miss on highly magnified images (1:1 and smaller). Commercial solutions can cost as much as $600, including controller.

So, I came up with the idea of re-purposing an old flat-bed scanner that I had in the attic gathering dust. It’s so old, that the most recent drivers available for it are for Windows XP. So it hasn’t been used in a couple of years. Being a scanner capable of 2400 dpi, it was definitely accurate enough, but would it be able to move a 3KG camera and lens? If I could get at the stepper motor to drive the scan element, maybe I could attach a camera to it and move it in very fine increments, ideal for macro photography.

Once I took the cover and the glass off, I was left with a nice flat platform on which to place my camera, and a 4-wire connection to the stepper motor to drive the platform forward and back. The stepper motor drive can be seen in the above image in the bottom right.

Mounting the camera is simply a case of placing it on the platform. The drive is slow enough that it does not dislodge the camera while it moves. The camera shown is a Canon EOS 5D Mark II, but it should work with Nikon, Sony, etc. Any camera with a shutter release mechanism.

The Circuits

This project was made much easier by using an off-the-shelf stepper motor drive unit (see pic). It’s a dual H-Bridge motor drive unit. I had it off eBay for €9. It has the capability to drive 2 DC motors, OR 1 stepper motor with 2 coils. In this project, we’re driving one stepper motor with two coils.

So, connecting in the 4-wire stepper motor interface into the MOTORA and MOTORB connections, and adding in a PSU in the form of  3 x AA  batteries to drive the motor, I then connected 4 GPIO outputs of the Raspberry Pi directly onto the 4 inputs to the stepper motor driver board. I wired the EnableA and EnableB pins to the +5V, as I want both coils in the motor to be enabled, and saved myself a few GPIO pins in the process.

The sequence I’m using to drive forward is 1000, 0100, 0010, 0001 (repeating), and backwards, is 0001, 0010, 0100, 1000 (repeating). You can see in the sequence that it’s enabling one of the coils on the motor at a time, causing it to rotate.

With a small bit of code, I was then able to drive the platform in the scanner forward and backwards ad various speeds, depending on how fast I ran the sequence to the motor (see below for the code)

The next step was to drive the shutter of the camera between each move of the platform. This was done using the following circuit.

So, now I can move the camera towards the subject in increments as little as 0.02 mm, taking an image each increment. That’s incredible resolution for something this easy to build!

The Code

Here’e a snippet of python code to move the motor a number of steps, and trigger the shutter.  Run this script for each frame in your stack. I guess you could stick a loop around it if you know how many frames you want to take, but I wanted to keep it simple for this article.

import sys
import wiringpi
from time import sleep

# Parameters:
#     direction (0 or 1)
#     number of steps (int)
#     delay between steps (float)

gpio = wiringpi.GPIO(wiringpi.GPIO.WPI_MODE_GPIO)  

motor_pin_a = 0
motor_pin_b = 1
motor_pin_c = 4
motor_pin_d = 14
shutterpin = 17

gpio.pinMode(motor_pin_a,gpio.OUTPUT)
gpio.pinMode(motor_pin_b,gpio.OUTPUT)
gpio.pinMode(motor_pin_c,gpio.OUTPUT)
gpio.pinMode(motor_pin_d,gpio.OUTPUT)
gpio.pinMode(shutterpin,gpio.OUTPUT)  

wiringpi.pinMode(shutterpin,1)
wiringpi.pinMode(motor_pin_a,1)
wiringpi.pinMode(motor_pin_b,1)
wiringpi.pinMode(motor_pin_c,1)
wiringpi.pinMode(motor_pin_d,1)

if sys.argv[1] == '1':
	start=0
	finish=int(sys.argv[2],base=10)
	increment=1
else:
	start=int(sys.argv[2],base=10)
	finish=0
	increment=-1

stepdelay=float(sys.argv[3])
a = [ '1000', '0100', '0010', '0001']

for j in range(start,finish,increment):
	i = j%4
	if a[i][0:1] == '1':
		gpio.digitalWrite(motor_pin_a,gpio.HIGH)
	else:
		gpio.digitalWrite(motor_pin_a,gpio.LOW)
	if a[i][1:2] == '1':
		gpio.digitalWrite(motor_pin_b,gpio.HIGH)
	else:
		gpio.digitalWrite(motor_pin_b,gpio.LOW)
	if a[i][2:3] == '1':
		gpio.digitalWrite(motor_pin_c,gpio.HIGH)
	else:
		gpio.digitalWrite(motor_pin_c,gpio.LOW)
	if a[i][3:4] == '1':
		gpio.digitalWrite(motor_pin_d,gpio.HIGH)
	else:
		gpio.digitalWrite(motor_pin_d,gpio.LOW)
	sleep(stepdelay)

# sleep 100ms to let things settle.
sleep(0.1)

# Trigger the camera shutter.
gpio.digitalWrite(shutterpin,gpio.HIGH)
sleep(0.1)
gpio.digitalWrite(shutterpin,gpio.LOW)

The Results

Here’s a video of the rig in operation, including a video of 42 stacked images played at 6 frames per second. This shows how the point of focus changes as the camera moves towards the subject

Here’s a few sample images taken using the flatbed scanner rig (MacroPi) :)

 

Next Steps

For a more robust solution, I’ve ordered the following part. Functionally it is the same as the flatbed scanner, but should allow me to more easily mount on a tripod for portable motorized focus stacking.

It was everything I was looking for all in one unit. A motor, rails, leadscrew, linear motion platform, all in one unit, all pre-assembled for about €83. I’d already got a 4-wire stepper motor working with the Raspberry Pi a few weeks ago, so the software was ready to go, it just needed me to build a macro rail. This thing would save me a load of time, and I’d end up with an industrial quality solution.

Some of the specs:

Motion length – 11.4 cm / 4.5″ ~
Leadscrew length – 14 cm / 5.5″ ~
Rail step (pitch) – 16 TPI
1.8° Step Motor – Made by SANYO DENKI
Type: 103H548-0498
Step: 1.8/step

The motor has 200 steps per rev, so with 16 turns per inch, (6.3 turns per centimetre), that gives me a movement of  126 steps per mm. Plenty accurate for what I need.

 

Raspberry Pi is a trademark of the Raspberry Pi Foundation

About the Author:

By day I’m a senior embedded Linux software engineer working with Emutex Ltd, an Embedded Software Solutions company in Limerick Ireland. In my spare time, I take pictures, and play with gadgets and technology.

Twitter: https://twitter.com/climberhunt @climberhunt
Facebook: https://www.facebook.com/davidhuntphotography


This entry was posted in Computer Stuff, Photography, Tutorial and tagged .

47 Comments

  1. Greg Gillies January 17, 2013 at 3:28 pm #

    Nice project. I can see myself using this as a starting point to build a motorised “barn-door” mount for long exposure astrophotography. I guess it could also be adapted to become an automatic dolly for time lapse with motion or panoramic shots. The possibilities are endless! Just a thought on the focus stacking though – could you not just do it using libgphoto and a USB connection to the camera?

    • daveh January 17, 2013 at 5:56 pm #

      Yes, USB is an option, and only one line of code change, also saves you building the circuit for the shutter port. Cool!

  2. Colin January 17, 2013 at 5:26 pm #

    Where can I buy the hardware in your last picture?

    • daveh January 17, 2013 at 6:02 pm #

      Interesting, I’ve had 4 emails in the last hour about that! :)
      http://www.ebay.ie/itm/280743516102#ht_2635wt_1165
      6 left Get ‘em quick, they won’t last long! :)
      Dave.

      • Brad January 19, 2013 at 6:47 am #

        1 less now. I just bit the bullet and ordered one. Looks good and going to enjoy tinkering away to get this working!

        • daveh January 22, 2013 at 1:26 pm #

          Only 1 left! :)

      • rick January 29, 2013 at 12:40 am #

        Hi Dave,

        Thanks for your tutorials! I just purchased one myself and am in the process of buying the parts to go with it. Do you know if yours is a unipolar or bipolar stepper motor?

        Thanks and look forward to the updates.

        Rick

        • daveh January 29, 2013 at 9:40 am #

          Rick, I believe it’s a bipolar motor.
          Dave.

        • Rick February 9, 2013 at 11:55 pm #

          Hi David,

          Just wondering if you have incorporated you new stepper/rail system yet? I just received mine but still unsure of what I am doing… From the wires at the motor it looks like a unipolar; but the connector is only four wires, which would lead me to believe that it is a bipolar.?.?. Also what voltage are you driving the motor at? My stepper drive is at 5v but some of the data sheets call the 103h548 motors at 3.6v. Anyways, look forward to building one soon and following your progress!

          Thanks,
          Rick

          • daveh February 10, 2013 at 12:30 pm #

            Rick, I haven’t taken it ay further, but I did connect it up to the driver and it worked fine. I was using 3 x AA NiMh batteries, so that would have been about 3.6 volts. Dave.

  3. Steve Ramsey January 17, 2013 at 6:21 pm #

    Hi David, another great idea!

    I assume it would be easy to add in a couple of lines of code so that you could add another step by an input on the pi, or even put in the number of steps you want at the beginning? i think I could do it in basic, but I am new to python.

  4. Brian January 17, 2013 at 11:25 pm #

    I would recommend a Opto-isolator over a transistor to use with the camera shutter. Would be sad to fry the expensive 5D D:

    I tested it with an arduino, the delay isn’t that big of an issue (my sony DSLR has quiet some delay over the external shutter release port… tried some stuff with wirelles flashes and wirelles shooting at the same time)

  5. Bob Cochran January 19, 2013 at 1:29 am #

    How did you make the camera shutter release? It looks like you bought a shutter release cable and cut apart one end for connection to the NPN transistor? Is the resistor intended to drop the voltage going to the camera?

    • daveh January 19, 2013 at 9:15 am #

      Bob, Yes, I had an old shutter release in which the switch was broken. I never throw anything out! ;)

  6. Dustin Grzesik January 19, 2013 at 5:19 am #

    That’s an excellent project and great set of instructions. Have you used ImageJ? It’s open-source image analysis software (funded by the NIH) and it’s scriptable.

    • daveh January 19, 2013 at 9:16 am #

      Dustin, I’ll take a look. Thanks! Dave.

  7. Bob Cochran January 19, 2013 at 6:27 pm #

    Is there a way to waterproof this for damp or outdoor conditions? Thanks, Bob

    • daveh January 19, 2013 at 8:51 pm #

      Bob, I’d only intend on using this indoors. No wind to move subjects around between shots! :)
      However, with the Linear Motion rail, it should be relatively damp-proof. I’d be more worried about the Raspberry Pi, to be honest…
      Dave.

  8. Bob Cochran January 20, 2013 at 5:07 am #

    I have zero experience with stepper motors, so this should be a good first project. I found my retired flatbed scanner and removed the glass top. The motor is a Neocene 2T3543 PM-type stepper marked as being 4 Ohms. It is 12v and has 4 wires. I guess I will need to supply it with 12v. From watching your video repeatedly, it looks like your camera is sitting on the scanner platform unsecured. Or did you modify the platform to secure the camera?

    • daveh January 20, 2013 at 10:33 am #

      Bob, 3v – 4.5 v should be fine. And yes, the camera is just sitting on the platform. The speed is slow enough so as not to dislodge the camera.

  9. Oleg Mazurov January 20, 2013 at 6:16 pm #

    That’s how I made focus stacking assistant. The thing is small and portable, I use it all the time to shoot pictures for the site.

    http://www.circuitsathome.com/camera-control/focus-stacking-assistant-for-eos-cameras

  10. Joe January 21, 2013 at 2:04 pm #

    Try Zerene Stacker. It’s a lot more versatile, and a lot simpler.
    http://zerenesystems.com/cms/stacker

    • daveh January 21, 2013 at 2:18 pm #

      It’s probably worth mentioning that Zerene Stacker is a commercial application, prices range from $39 for the student edition to $289 for the full version.

  11. Bob Cochran January 21, 2013 at 3:53 pm #

    I’ve ordered the stepper motor controller (about 3-5 weeks from China) and I’ll look around for a shutter release cable. I’m going to play with ImageJ since I’m on the Mac. Perhaps I can use this beginning experience to work more with insect photograohy. I will think of how to accomplish the same thing for photographing insects. It is difficult to set up a tripod with the camera pointed at a spider or mantis and then focus the lens such that the lens doesn’t drop slightly or the creature doesn’t scoot off and hide in fear. Part of my problem is the tripod I’m using has trouble locking a heavy camera exactly into position when it is on an extension rail. The weight of the extension rail and he angle it is pointed at makes the tripod tip over easily. A better tripod plus he linear motion rail might help with that because it can move the camera lens closer to the insect…hopefully without frightening it.

  12. Gerald January 21, 2013 at 11:01 pm #

    Why not use the Magic Lantern in your camera and let this kind of project for Nikon users.

    • Greg G January 21, 2013 at 11:25 pm #

      Magic Lantern would work in most circumstances, but not if you are using extension tubes or reversing rings where you have no automatic control over the focus. Besides, it’s more fun connecting your camera to an old scanner! ;-)

  13. nahiko January 22, 2013 at 7:15 pm #

    Does anyone know what Lytro is?
    I think they do the same than this.

  14. Peter Faasse January 22, 2013 at 10:03 pm #

    FYI: quite a few of those stepper motors support ‘half steps’.

    fi: You mention as the forward stepping control sequence:

    1000, 0100, 0010, 0001

    You might want to see what happens with:

    1000, 1100, 0100, 0110,
    0010, 0011, 0001, 1001

    Not that you seem to need it ‘here’, but with the same electronics, you can get the double ‘resolution’.

  15. Bob Cochran January 23, 2013 at 3:06 am #

    Possibly a silly idea: there is already an ST L6219 stepper motor driver on my scanner’s circuit board. It’s an SO24 surface mount package. Would it be practical to drive the stepper motor by soldering wires to the L6219 pins and connecting them to the Raspberry? Of course, it is very difficult to say without the schematic diagram and the manufacturer, if still in business, may be unlikely to give it to me. It is probably better to wait for my dedicated board to arrive from China.

    • daveh January 23, 2013 at 9:58 am #

      Bob, probably a fine idea if the scanner is broken, but if it still works, you can always put it back together when you’re done with your macro shots. :)
      Dave.

  16. Joe H January 25, 2013 at 10:58 pm #

    Dave,

    Really enjoyed reading about your projects and in fact cited them on my blog here: http://www.hackthings.com/raspberry-pi-nearly-a-million-units-sold-but-is-yours-idle/

    Very impressive work all around.

    thanks,
    Joe

  17. Martin January 26, 2013 at 8:45 pm #

    wouldn’t it be easier just to attach a stepper motor to the manual focus dial? turn a bit, take picture, turn a bit, take picture and so on.. My thought is this way the camera does not get closer. Moving camera closer would make the subject a bit bigger each time the focus is adjusted to a deeper field.. Just my thought, I could be wrong though..
    Cool project

    • daveh January 26, 2013 at 9:44 pm #

      Good idea. However, the engineering to build a jig to attach to the lens could be quite complicated. Might be worth it for the zoom, though! :)

  18. Bob Cochran January 28, 2013 at 3:37 am #

    Faced with another 2-3 weeks wait for the motor driver I ordered to arrive here from China, I ordered a “Big Easy” motor driver from Sparkfun Electronics which I should have by the end of this week. I have all the remaining parts needed except a breadboard. I could try to use the L6219 motor driver that is on my scanner’s circuit board, too. That may activate the scanning hardware itself, though. Better try to run the motor all by itself.

  19. Bob Cochran February 3, 2013 at 3:02 pm #

    Dave, in your code you assign 0 to motor_pin_a. Pin 0 is actually a WiringPi pin name and it maps to BCM pin 17, also known as GPIO17, which in turn in is pin 11 on the Raspberry Pi Model B header P1. So your motor control wires are in P1 header pins 11, 12, 16, and 23 respectively and the camera shutter pin 17 is mapped to BCM pin 28 which in turn maps to the auxiliary header pin 3. Is this correct? Did you have any special reason for these pin choices? Putting the camera shutter pin on the auxiilary header is especially interesting. Thanks, Bob

    • daveh February 3, 2013 at 7:55 pm #

      Bob, I’m using the WPI_MODE_GPIO, and all the pins I’m using are within the first 8 pins of the GPIO header beside 3.3 and 5V supplies. Pin 3 – GPIO 0, Pin 5 = GPIO 1, Pin 7 is GPIO 4 and Pin 8 is GPIO 14. I’m doing that because I’m using an 8-way header connector I recycled from an old USB panel mount for a PC.

  20. Bob Cochran February 6, 2013 at 4:22 am #

    Hi Dave, thanks for letting me know. I’m still a little confused here. Is your “wiringpi” from this source –> https://projects.drogon.net/raspberry-pi/wiringpi/ ?

    The motor driver I ordered from China arrived today, so I have the choice of using either that (it is the “HEX” brand and looks almost the same as yours, with the same L298 chip) or the Big Easy Driver from Brian Schmalz and Sparkfun Electronics. I’m going to use the Big Easy first, because the physical form factor is a lot smaller than the HEX L298, and it looks like the programming required is simpler too. I just need a few more parts: 3.5mm screw terminals, which should arrive Thursday or Friday. I’ll let you know what happens.

  21. Steve Ramsey February 19, 2013 at 4:44 pm #

    Dave I am in the process of getting all the bits to do this, and think I get most of it. The bit that is confusing me is the enable A and enable B pins. Do you mean they are both wired to the 5v pin on the GPIO interface, or to the 5 V pin on the stepper motor driver? Also, does the battery pack connect in via the 3 terminals between motor A and motor B?
    thanks

    • daveh February 19, 2013 at 5:38 pm #

      Steve, I connected both Enable pins to the +5 on the 8-pin header. And yes, the 3.6v from the battery goes to 2 of the 3 terminals between A and B.
      Rgds,
      Dave.

      • Gareth Jones March 1, 2013 at 12:18 pm #

        I’m trying to do the same thing – though as the basis for a timelapse slider.
        I’ve got the stepper out of the scanner, and also got the same board as yourself.
        I think I have the 8 pin wiring correct, but the wiring to the stepper motor is eluding me.
        I have 6 wires, and i’ve identified the two sets of three wires so: two are the coil ends and one is the centre tap. It’s how these are wired to the motor end of the board. I’m assuming that the two coil wires go to the two terminals of motor A connection? Then where does the centre tap go? Does it go to GND, or to Vms? Or is it disconnected – a bit more googling leads me to believe this is the case.

        • daveh March 1, 2013 at 2:35 pm #

          Gareth, You should have 4 wires out of the stepper motor back to the controller, two on MotorA and two on MotorB. Only 4 wires to the stepper. Then Separately, take your battery into the +Vcc and Gnd (3.6v approx).

          • Gareth Jones March 2, 2013 at 10:07 am #

            Thanks – yes, that’s what I’ve got now – I finally worked it out. The centre taps have to go to ground as well.
            The other thing I ‘discovered’, having spent some time working out which wire went to which coil, was the sequence in which I needed to energise the coil wires was the same as the order they were in the connector.

  22. Ken Stoneman February 23, 2013 at 10:29 am #

    Where can I obtain the threepin plug neded to connece to my EOS canon Camera please

  23. VICENTE SALAZAR G February 27, 2013 at 1:32 pm #

    NO HAY FORMA QUE FUERA TRADUCIDO A EPAÑOL GRACIAS

    • daveh February 27, 2013 at 2:20 pm #

      Hola Vicente.
      Te recomendaría que tradujeras el texto usando Google Translator (translate.google.com).
      Gracias.
      Dave.

  24. Chris March 20, 2013 at 11:22 am #

    Hey David,
    great Work & thanks for sharing this!
    I think I will try to combine this article with your timelaps dolly. With an step-motor it should be fine to drive the slider back to his starting point – after it did his job. The normal DC-Motor isn’t so accurate or?

    Is it right that i could use the H-Bridge motor drive unit also with 12V from an external Powersupply?

    And: Is it possible to share more Pics or the Layout from the wiring diagram? I’m not the best electrician :).

    That would be awsome!

22 Trackbacks

  1. [...] you want to build your own focus-stacking rail, Dave has full build instructions, including circuit diagrams, code and tips on where to get parts at his website; even if you’re not a seasoned electronics hacker, you should be able to follow [...]

  2. [...] each one moving closer to the subject, to be later focus stacked in CombineZM. Build info here: http://davidhunt.ie/?p=2826 Like this:LikeBe the first to like [...]

  3. By Noticias breves de la semana (3) | 18minutos on January 19, 2013 at 3:23 am

    [...] Macro Pi, focus stacking utilizando una Raspberry Pi. [...]

  4. [...] ที่มา http://davidhunt.ie/?p=2826 [...]

  5. [...] depth of field – the small region where things are actually in focus. [David] came up with a neat homebrew solution for making sure everything in his macro photos is in focus using a discarded flatbed scanner and a [...]

  6. [...] depth of field – the small region where things are actually in focus. [David] came up with a neat homebrew solution for making sure everything in his macro photos is in focus using a discarded flatbed scanner and a [...]

  7. [...] little region exactly in which the situation is in fact withinside concentrate. [Donald] developed the well put together homebrew solution for making certain my way through their macro pictures is at emphasis utilizing a dumped flat bed [...]

  8. By Photo Life :: BLOG on January 22, 2013 at 3:31 pm

    [...] you heard of the Raspberry Pi? Photographer Dave Hunt has a cool project where he uses the Raspberry Pi and an old flat-bed scanner to do focus [...]

  9. [...] que ha hecho Dave Hunt es aprovechar sus conocimientos y esta pequeña maravilla informática para construir un preciso [...]

  10. [...] idea of turning an old flatbed scanner into a macro rail for shooting focus-stacking photos. Hunt writes that the main question was whether the scan element could support a hefty DSLR and lens: I came up [...]

  11. [...] stunning, “focus stacked” macro photos Dave Hunt figured out a way to accomplish “focus stacking” macro images using a Raspberry Pi and [...]

  12. [...] – and software, and hardware. The latter is a simple but very useful gadget assembled by David Hunt . How does it work? Straight. Using the mechanism of the old scanner, Hunt has created a moving [...]

  13. [...] Macro Pi – סורק הופך לרובוט הערמת פוקוס (מקור: David Hunt) [...]

  14. By Camera Pi – DSLR Camera with Embedded Computer on January 25, 2013 at 5:37 pm

    [...] Macro Pi – Focus Stacking using Raspberry Pi [...]

  15. [...] Continue to Dave Hunt’s write up of the project, including wiring diagrams [...]

  16. By PhotoPi | Björn Salgert on March 4, 2013 at 9:02 pm

    [...] Macro Pi - Macrofotos mit mehr schärfe erstellen [...]

  17. [...] « Macro Pi – Focus Stacking using Raspberry Pi RAID Pi – Raspberry Pi as a RAID file server [...]

  18. [...] Macro Pi – Focus Stacking using Raspberry Pi [...]

  19. By Cool Raspberry Pi | Circle and Square on May 16, 2013 at 10:22 pm

    [...] Time-lapse photography • Bird photography • Water drop photography • Macro photography [...]

  20. [...] the video and if you are feeling the itch to try it yourselves head on to  Hunt’s website and read about the entire DIY building process. Do keep in mind that there is at least one [...]

  21. […] David Hunt had an old flatbed scanner sitting around, and he figured he could kill two birds with one stone by using it to create a setup that solves the focus problem with macro photography. […]