Electronics · python · raspberry pi

[FIXED!!!] Turn on a lamp with a gesture – Image Processing! Machine learning!


Source: http://makezine.com/projects/raspberry-pi-potter-wand/

Make has a write-up on wand-control with a simple reflective wand…

…it *was* broken.  Fixed it.

Back in January when I first read the article I was so excited to try it, I ordered a bunch of parts, downloaded the Git, and then figured out it didn’t work.

Not to worry though.  A fellow named John Horton contacted me, and inspired me to try again.  This time, I decided to try to understand the code, and get it up to snuff.  If you want to skip ahead.  The code is here:


To be clear… I’m not a python dev… those that are will definitely cringe… Sorry.

Here is the original writeup…


The original concept is fantastic… it just didn’t work for me.

So I tried to get it going from the ground up, and rearchitected the source so its multi-threaded, and uses machine learning to match gestures.  Even the image feed is fast! 😉

First, prepare the PI3 by installing OpenCV

First – start with a fresh disk.  I use piBakery:


These are the exact steps I used to get a fresh full-desktop PI3 up and running:


They were mostly gleaned from here (with one minor fix):


Like many of you, I tried piles of instructions without success.  I was surprised when this set worked with out a hitch.

Next, get the code…

I’ve made the code available here:

git clone https://github.com/mamacker/pi_to_potter

It has a version that is very close to the original, just sped up and tweaked.  That one is called rpotter.py.


The other one I created is called trained.py, in that one I used machine learning!!!  Which was extremely entertaining.

To run it, cd into pi_to_potter:

python trained.py

Note – it takes a while to start up, because it runs through all of the images in the Pictures directory to train itself to recognize those gestures.

Make sure your environment is mostly free of reflective surfaces.  Those reflections behind you will ruin the wand detection.  You want one dot… the wand. 🙂

Once the code is running, put something reflective in your camera’s field of view.  Make sure its just a point, otherwise your gesture will be difficult to see.  Once something is seen.  Two windows will come up:

Screen Shot of Trained in Action

The “Original” will flicker between the real image, and any detected, thresholded, light reflection.  Original, should be where you see motion.

The “Raspberry Potter” window, will show you any tracks created by Optical Flow.

Finally, watch the command-line logs.  That’s where you’ll see the name of the recognized image.  When you are ready to do something based on a recognition, update the Spells function.  You can refer to some other articles on how to control outlets for fun:

Raspberry PI Controlling Power through GPIO (no wifi needed)

Raspberry PI for controlling TP-Link POWER

Raspberry PI for Controlling Wemo Power

Universal Studio’s Wands are really bad reflectors… Or there is other magic…

Universal Studio’s wands are really bad reflectors.  They must have some serious emitters at the park, because getting light back from them is terribly difficult.  So I ordered a bunch of other materials to try out.

This tape worked:51K10mxgGuL._SL1000_

White Reflective Tape

This is the tape on the end of cost-effective-for-kids wands I found:

Screen Shot 2017-12-09 at 7.04.10 PM

I found the wands on Etsy:


There are other reflectors… but I have yet to try them.  I’ll updated once I give them a go:61aa7ewie4l-_sl1200_

Retroreflective Tape

The camera I used – the Pi Noir




How this technique works…

This technique uses image processing to track the wands position through a series of pictures taken on the camera.  It first has to find the wand within the view, once its identified the wand light, it uses a function in the OpenCV package to track its movement:

calcOpticalFlowPyrLK:  Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with pyramids.

This provides points from the image set which can be matched against the gesture “shapes”.  Where the shape check in the original simply takes two line segments, identifies them as move up, left, down or right.  The combination of any two creates a recognizable request.

It’s really quite brilliant in its simplicity.

The original code for the image recognition is found here:


And it’s wonderfully tiny.  The updated version is found in my repo here:


Now you can train it!!!

The “triangle” training set

So, while I was in there I was able to add the ability to train for gestures.  Once you have the whole system up and running.  Add the –train flag.  That will start storing new images in the /Pictures directory.  These will be the attempts at gestures people do in front of your camera.  You get a starter set I recorded when you get the repo.

python trained.py --train

Practice the gestures until you get a good set of them in the Pictures folder, at least 5, and they need to be distinct enough from the others to not conflict.  Once you have a good collection, create a folder for them with a simple name.  Something like “star”, or “book”, or “funny”.  Then that command will be auto-learned at the next restart.

The last step is to add an “if” statement that uses it in the “Spell” function:

Screen Shot 2017-12-09 at 7.15.28 PM.png

Add your new name in that list… and make it do something!  Once you’re done, restart the code, and watch for your recognition to show in the logs.

I’ll let you know…

I’ll try again as soon as my reflective bits come in.

If you have a little more funds and less time – the build where the smarts are in the wand can be found here:

Raspberry Pi – Control by Magic Wand!


27 thoughts on “[FIXED!!!] Turn on a lamp with a gesture – Image Processing! Machine learning!

  1. Hi,
    Thanks for the new code, it is working great. I had modified it to use a HAT with relays. Anyways I am having trouble running the code at start-up. I did not use PiBakery as I already had the initial drive built using the image from Sean.
    I used both the init.d method and systemd method to get it going at start-up, both failed to load. Below is the log from the systemd method, do you have any idea on why this is not working or the specific steps to get it going from start-up?
    Dec 20 20:39:51 PotterWandGizmo systemd[1]: Starting My Potter Service…
    Dec 20 20:39:51 PotterWandGizmo systemd[1]: Started My Potter Service.
    Dec 20 20:39:59 PotterWandGizmo python[795]: (Original:795): Gtk-WARNING **: cannot open display:
    Dec 20 20:39:59 PotterWandGizmo python[795]: Initializing point tracking
    Dec 20 20:39:59 PotterWandGizmo python[795]: About to start.
    Dec 20 20:39:59 PotterWandGizmo python[795]: START incendio_pin ON and set switch off if video is running
    Dec 20 20:39:59 PotterWandGizmo python[795]: Starting wand tracking…
    Dec 20 20:39:59 PotterWandGizmo python[795]: Running find…
    Dec 20 20:39:59 PotterWandGizmo systemd[1]: potter.service: main process exited, code=exited, status=1/FAILURE
    Dec 20 20:39:59 PotterWandGizmo systemd[1]: Unit potter.service entered failed state.


    1. Hi Tim,
      I’ve never tried to run it from systemd, or initd, but it may be because of the line: “Gtk-WARNING”.
      That’s probably because its trying to open a window from a non-desktop root account, before the desktop is loaded.

      My bet… though again, I haven’t tried it is to use the LXDE to start the app. As mentioned here:

      Specifically this part of that article:
      @/usr/bin/python /home/pi/example.py

      Would look like this:
      @/usr/bin/python /home/pi/pi_to_potter/trained.py

      Put that in your:

      I wrote another article that talks a little about this here:

      Good luck! If you still have trouble, I’ll give it a whirl myself, until I get it going on boot.


      1. I found something odd. The script rpotter.py works fine in the autostart but the trained.py does not start. Both are working fine outside of the autostart.


  2. Ah, that’s probably because I didn’t make sure the paths were absolute.

    This line:
    mypath = “./Pictures/”

    Should be the full path to the Pictures directory. Something like:
    mypath = “/home/pi/pi_to_potter/Pictures”

    Let me know if that doesn’t do it.


    1. I bow to you again. It fixed it. The only issue I have right is that the “spell()” routine gets called twice on each detection, this was in the original code as well.

      I fixed it by adding a check to see if it happened twice quickly so I am fine.


  3. I’m a Linux newbie, so sorry if this is a dumb question. I’m going through your steps all goes well until I run make, I’m getting linking errors. Undefined references in the image codec.so file.
    Any thoughts on how to fix, I’m lost?


    1. It sounds like one of your dependencies wasn’t properly installed. Have you tried running the package install steps a second time? They all have to succeed before you attempt the make command.


  4. I removed the build directory, re-ran the various library install steps and it works now. Not sure what was the problem exactly but it compiled!!
    Can’t get the trained.py file to run as you describe. Getting errors on that step. I think you address this in a comment above, but I don’t follow what I need to change to fix it. Do I need to edit the trained.py file somehow?


    1. Whoops!!! Sorry about that. You can either, install the dependency:
      sudo pip install pytesseract
      Remove the import line in that file. That was an OCR library I was attempting, but tossed when I added the training. Fixed it in the github repo.

      Sorry again, and let me know if you have any other trouble!


  5. Brilliant work! I’ve finally gotten all the way to tracking, and the IR is picking up the signal well, BUT the lights not he particle internet button aren’t reacting at all. any counsel is much appreciated!


    1. Hi John! Thanks!

      This code doesn’t attempt to turn on pins for the particle. That’s been stripped out to reduce complexity.

      If you’d like to put that back in, you need to bring back the calls to pigpio seen in the original here:

      So you’ll need to (on the pi command line):
      sudo pip install pigpio

      Add pigpio to the python file like this:
      import pigpio

      pi = pigpio.pi()

      Add the various pins you’d like to actuate:
      #pin for Trinket (Colovario)
      trinket_pin = 12

      And specifically update the function “Spell” which has the calls to set pins like this:

      If you have trouble getting this done, let me know. I don’t have a Particle or the various other bits he used, but I can probably make it function without it, and create a file that has the “pins” work going.


  6. Hilarious. I bought three different internet buttons, convinced i’d bricked them in the wiring process (this is outside my level of expertise, I’m afraid). If you’re able to insert those spells into your functioning code (I could never get the original code to track properly), I’ll gladly send you a particle internet button. They’re pretty cool. lmk.


    1. Heh. Thanks for the offer – but don’t worry about sending me anything! I’ve added the pin control. There is a new file called trainedwpins.py. Do a “git pull” to get the latest.

      You use it all the same way, but now you just have to make sure you first run the pgpio service. Like this:
      sudo pigpiod

      Then run the code like this:
      python trainedwpins.py

      I was able to test it with an LED. Kinda fun actually. 😉

      The spells that actuate the pins are:
      CENTER: One line from top to bottom, will turn on the trinket_pin.
      CIRCLE or SQUARE: Will turn on the incendio pin, and turn off switch and nox.
      LEFT: Will turn on the switch pin.
      TRIANGLE: Tuns on the NOX pin.

      Let me know if you have trouble!


  7. Thanks! That was very kind of you. I’ve downloaded the file but am getting the pytesseract error when try to run trainedwpins.py

    any suggestions?


  8. So close! I’m jammed up here:

    Starting wand tracking…
    OpenCV Error: Assertion failed (prevPyr[level * lvlStep1].size() == nextPyr[level * lvlStep2].size()) in calcOpticalFlowPyrLK, file /home/pi/opencv-3.1.0/modules/video/src/lkpyramid.cpp, line 1248
    OpenCV Error: Assertion failed (ssize.area() > 0) in resize, file /home/pi/opencv-3.1.0/modules/imgproc/src/imgwarp.cpp, line 3229
    CAST: mistakes

    Any ideas?


    1. I don’t think that one matters actually. That’s just because the image hit the edge when detecting wand.

      Have you tried using your wand in the view?

      I’ll double check it though…


  9. Yup. That message shouldn’t matter. Its likely because you are getting a reflection near the edge of the screen. That reflection makes it so the image can’t be resized, and the detection fails.

    If you reduce the reflections from your background and bring your shiny thing(the wand) into view. You should see the spells start to get detected.

    If it still doesn’t work – I can add more logging. Let me know!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s