Dimir EDH Box with Nacre Inlay

It's been a while since I've put up an update, but I haven't been up to nothing. I found out that I have access to a beefy laser cutter through my work, and have been throwing various projects at it over the last few weeks. One of the first things I wanted to try was precision inlay and making a rudimentary deck box. My first target was my Lazaav EDH deck, and it provided a good opportunity to get my feet wet with both laser cutting, inlay, and wood staining. The material itself comes from an 1/4" thick oak project board. I had pondered putting on a few layers of shellac or other finish to smooth it out, but decided that I'd already learned what I'd wanted to, and kinda preferred the woodgrain look.

Showing off the inlay colors

Showing off the inlay colors

The lid fits, but not perfectly

The lid fits, but not perfectly

The ebony stain looks almost exactly like I wanted it to

The ebony stain looks almost exactly like I wanted it to

I didn't both to finish the interior on this one, a final version would definitely have a lining.

I didn't both to finish the interior on this one, a final version would definitely have a lining.

The pattern for the box itself was generated using MakerCase, but I think for later projects I'm going to opt for actually making the joints myself to ensure they fit. There seemed to be some inconsistencies with the laser kerf (similar to the saw-depth for conventional cuts) that prevented perfect mating, and I haven't dialed in the compensation for that.

Over all this served as a proof-of-method and tools for doing nacre inlay on later projects, and bonus points: it still works as a box.

Recognizing Cards - Finding the Match

In the previous two posts in this series (1, 2) I talked about capturing a reliable image of the art on a magic card from a webcam, and how we can hash those images for an effective and mostly efficient comparison. Now we're left with a hash for the card we'd like to match, and an enormous table of hashes for all the possible matches (something like 18,000 cards). The first question is how to compare the hashes in a meaningful way, but thankfully this is made easy by the nature and documentation for phash. The Hamming distance, or number of dissimilar characters in the string, is the metric of choice. This method is demonstrated step-wise below, first for the correct target, then for a random non-target image.

When compared to the actual match, the Hamming distance is 9. Mismatched character are highlighted in red.

When compared to the actual match, the Hamming distance is 9. Mismatched characters are highlighted in red. While the cutoff value might take some fine tuning, for our purposes (and my camera), 9 is a relatively strong match.


Compared to an incorrect image, the Hamming distance is 15. The single matched character is effectively within the noise.

Hamming distance is a reliable metric for this hashing approach, and is relatively easy to compute if the hashes are all already calculated. That being said, we don't really want to do 18,000 x 16 charter-character comparisons in order to determine which card we're looking at. Instead we can use a binary search tree. There is a lot already written on binary trees, but the short version is this: by splitting space up one can iteritively narrow down the possibilities, rather than look at each candidate individually. It does require that you take the time to build the tree, but individual searches become substantially faster.

But wait, the Hamming distance doesn't provide coordinates in some searchable space, it provides a measure describing how two data are related (or not), but this can be thought of as a 16 dimensional metric space. The approach I've gone with is a vantage-point, or VP tree, chosen primarily since Paul Harrison was kind enough to post his Python implementation. The idea behind VP trees is to pick a point in your space, e.g. the hash "1111aaaabbbbcccc", and then break your member-set into two parts: those "nearer" than some cut-off Hamming distance, and those further out. By repeating this process a tree of relations can be built up, with adjacent 'branches' having smaller hamming distances than 'far' branches. This means that a hash you're trying to match can rapidly traverse the tree and only run direct comparison with one or two actual set members. The paper by Kumar et.al has an excellent explanation of how this compares with other binary-tree approaches, and while they were doing image-patch analysis, the content is still incredible relevant and well presented. Figure 2 in that paper, not reproduced here, is perfect for visualizing the structure of VP trees!

I'm still in the process of cleaning up code, but plan to shortly follow up with a video demonstration of the code in action, as well a few snippets of particular interest.

Recognizing Cards - Effective Comparisons with Hashing

In the previous post we got as far as isolating and pre-processing the art from a card placed in front of the camera; now we come to the problem of effectively comparing it with all the possible matches. Given the possible "attacks" against the image we're trying to match, e.g. rotation, color balance, and blur, it's important to choose a comparison method that will be insensitive to the ones we can't control without losing the ability to clearly identify the correct match among thousands of impostors. A bit of googling led me to phash, a perceptual hashing algorithm that seemed ideal for my application. A good explanation of how the algorithm works can be found here, and illustrates how small attacks on the image can be neglected. I've illustrated the algorithm steps below using one of the cards from my testing group, Snowfall.

Illustration of the phash algorithm from left to right. DCT is the discrete cosine transform. Click for full-size.

The basic identification scheme is simple: calculate the hash for each possible card, then calculate the hash for the art we're identifying. These hashes are converted to ASCII strings and stored. For each hash in the collection, calculate the hamming distance (essentially how many characters in the hash string are dissimilar), and that number describes how different they are. The process of searching through a collection of hashes to find the best match in a reasonable amount of time will be the subject of the next post in this series (hint: it involves VP trees.) Obtaining hashes for all the possible card-arts is an exercise in web scrapping and loops, and isn't something I need to dive into here.

One of my first concerns upon seeing the algorithm spelled out was the discarding of color. The fantasy art we're dealing with is, in general, more colorful than most test image sets, so we might be discarding more information for less of a performance gain than usual. To that end, I decided to try a very simple approach, referred to as phash_color below: get a phash from each of the color channels and simply append them end-to-end. While it takes proportionally longer to calculate, I felt it should provide better discrimination. This expanded algorithm is illustrated below. While it is true that the results (far right column) appear highly similar across color channels, distinct improvements to identification were found across the entire corpus of images compared to the simpler (and faster) approach.

The color-aware extension of the phash algorithm. The rows correspond to individual color channels.

The color-aware extension of the phash algorithm. The rows correspond to individual color channels. Click for full-size.

I decided to make a systematic test of it, and chose four cards from my old box and grabbed images, shown below. Some small attempt was made to vary the color content and level of detail across the test images.

The four captured arts for testing the hashing algorithms.

The four captured arts for testing the hashing algorithms. The art itself is the property of Wizards of the Coast.

For several combinations of hash and pre-processing I found what I'm calling the SNR, after 'signal-to-noise ratio'. This SNR is essentially how well the hash matches the image it should, divided by the quality of the next best match. The ideal hash size was found to be 16 by a good deal of trial and error. A gallery of showing the matching strength for the four combinations (original phash, the color version, with equalized histograms, and without pre-processing) are shown below, but the general take-away is that histogram equalization makes matching easier, and including color provides additional protection against false positives.

This slideshow requires JavaScript.

If there is interest I can post the code for the color-aware phash function, but it really is as simple as breaking the image into three greyscale layers and using phash function provided by the imagehash package. Up next: VP trees and quickly determining which card it is we're looking at!

Recognizing Cards - Image Capture

Back in October I posted a short blurb on my first attempts on recognizing Magic cards through webcam imagery. A handful of factors have brought me back around to it, not the least of which is a still un-sorted collection. Also, it happened to be a good excuse to dig into image processing and search trees, things I’ve heard a lot about but never really dug into. Probably the biggest push to get back on this project was a snippet of python I found for live display of the pre-and-post processed webcam frames in real time, here. There is real novelty in seeing your code in action in a very immediate way, and it also eliminated all of the frustration I was having with convincing the camera to stay in focus between captures. At present, the program appears to behave well and recognize cards reliably!

I plan to break my thoughts on this project into a few smaller posts focusing on the specific tasks and problems that came up along the way, so I can devote enough space to the topics I found most interesting.

  • Image Pre-Processing
  • Recognizing Blurry Images: Hashing and Performance
  • Finding Matches: Fancy Binary Trees

I should note here: a lot of the ideas used in this project were taken from code others posted online. Any time I directly used (or was heavily inspired by) a chunk of code, I’ll link out to the original source as well as include a listing at the bottom of each post in this series.


The goal here was to take the camera imagery and produce an image that was most likely to be recognized as "similar" by our hashing algorithm. First and foremost, we need to deal with the fact that our camera (1) is not perfect, the white-balance, saturation, and focus of our acquired image may all be different than the image we're comparing with, and (2) the camera captures a lot more than the card alone. Let's focus on the latter problem first, isolating the card from the background.

The method I described in the previous post works sometimes, but not particularly well. It required exactly ideal lighting and a perfectly flat background. The algorithm I ended up settling on is:

  1. Convert a copy of the frame to grey-scale
  2. Store the absolute difference between that frame, and the background (more on that later)
  3. Threshold that difference-image to a binary image
  4. Find the contours present using cv2.findContours()
  5. Only look at the contours with a bounded area greater than 10k pixels (based on my camera)
  6. Find a bounding box for each of these contours and compute the aspect ratio.
  7. Throw out contours with a bounding box aspect ratio less than 0.65 or greater than 1.0
  8. If we've got exactly one contour left in the set, that's our card!

The next problem to tackle is that of perspective and rotation, which thankfully we can tackle simultaneously. In the previous steps we were able to find the contour of the card and the bounding rectangle for that contour, and we can use these.

  • Find the approximate bounding polygon for our contour using cv2.approxPolyDp().
  • If the result has more than four corners, we need to trim out the spurious corners by finding the ones closest to any other corner. These might result from a hand holding the card, for example.
  • Using the width of the bounding box, known aspect ratio of a real card, and the corners of the trapezoid bounding the card, we can construct the perspective transformation matrix.
  • Apply the perspective transform.
Camera input image. Card contour is shown in red, bounding rectangle is shown in green.

Camera input image. Card contour is shown in red, bounding rectangle is shown in green. The text labels are the result of the look-up process I'll explain in the coming posts.

The isolated and perspective-corrected card image.

The isolated and perspective-corrected card image.

Lastly, to isolate the art we simply rely on the consistency of the printed cards. By measuring the cards it was fairly easy to pick out the fractional width and height bounds for the art, and simply crop to those fractions. Now we're left with the first problem: the imperfect camera.  Due to the way we're hashing images, which will be discussed in the next post in this series, we're not terribly worried about image sharpness as the method does not preserve high frequencies. Contrast however, is a big concern. After much experimentation I settled on a very simple histogram equalization. Essentially modifying the image such that the brightest color is white and darkest color is black, without disrupting how the bits in the middle correspond. An example of this is given below.

Sample image showing (cw) the camera capture, the target image, the result of histogram equalizing the input, and the result of equalizing the target.

Sample image showing the camera capture, the target image, the result of histogram equalizing the input, and the result of equalizing the target.

So now we're at the point where we can capture convincing versions of the card art reliably from the webcam. In the next post I'll go over how I chose the hashing algorithm to compare each captured image against all the potential candidates, so we can tell which card we've actually got!

Fungiculture: Oyster Mushrooms

It has been a while since I’ve been able to post an actual update, having gotten a job, moved, and settled in during the interim. Having met with some small success growing a few basil plants indoors, I decided to branch out into mycoculture, or mushroom growing, as the requirements are a bit stricter, supplying a bit of an engineering challenge in getting it right. While it’s totally true that, given my choice of oyster mushrooms (pleurotus ostreatus) for my first attempt, I could have just as well used a plastic bag and a spray bottle, however that would not have scratched my data-gathering/total automation itch. Now let us get to the admittedly over-kill list of parts I ended up using.

During this first week-long time lapse we kept the aquarium light on continuously to provide consistent illumination for the camera, and realized that consistent (and blue) light strongly inhibits mushroom growth, which turns out to be a well-established fact  so for a week we saw very little happen aside from a moderate whitening of the surface of the mycelium-log. After a week of watching, we folded and decided to shut it down for the evening and go to bed. Of course, finally given a break from the light, mushrooms immediately appeared over night, so we excitedly resumed the time-lapse capture the following morning, resulting in the second video.

First week, under constant illumination (not much change)

Second week, without night illumination

By the end of that week we had a full flush of mushrooms to harvest, as shown in the photos below. I probably waited about a half-day too long, given that the cap-edges were just slightly beginning to droop. After cutting them from the base with a kitchen knife, the heights and cap-widths were measured for later comparison, and the rinsed mushrooms were stir-fried with green onion and garlic! They were pretty tasty! Given that I don’t usually eat mushrooms I was surprised by how much I liked them, but the inevitable bias towards something I made myself can only help. I also managed to log the conditions over the first 12 days (missing the last bit of the fruiting stage before harvesting); those data are shown below. The placement of the two sensors probably makes up for the fact that the controller was reporting ~70% RH while the logger reported values around ~60%, but there are some relatively easy calibration tests that can be done.

Mushrooms_humidity Mushrooms_temperature
Plots of the temperature and humidity as a function of time over the first 12 days.Without further delay, I should show off the fruits (kinda) of my labor, the mushrooms!

This slideshow requires JavaScript.

Rather than use this as a one-off experiment, I’ve already got the tank back under humidity control and monitoring, the first beginnings of a new flush of mushrooms are just now showing themselves. Moving forward I might try to simplify the setup, as I’ve read that environmental monitoring and power control are super-easy with cheap single-board computers (e.g. raspberry pi). It’s only coincidence that I’ve been playing with those lately for other project, just 4 years behind the curve!

Publication: Designing spectrum-splitting dichroic filters to optimize current-matched photovoltaics

After an incredibly long wait, and with an incredibly long title, the paper covering my work on thin film filters for solar energy collection is finally in print! You can find the it here as part of OSA's Applied Optics Journal.

If there's interest in a plain-English explanation of what we did and why, I'd definitely take the time to write one up! Just drop a comment below.

Wrapping up

It's been a while since I've updated here, and rather than ambiguously stating that "life's been crazy" I can concretely sum it up as "was busy graduating". Writing the dissertation, handing off projects that are still active, and generally cleaning up the path behind me have taken a sizable chunk of time. None of this is to say that I was particularly itching to dive into new projects after passing my defense. I'm moving out to the bay area finally, joining a handful of friends already out there. Hopefully this new chapter will present just as many (if not more) opportunities for projects worth writing about. For the time being I'll be focusing on the logistics of uprooting myself from Tucson, and minimizing the transplantation shock of a new city and job.

Recognizing Cards - First Attempts

Sorting images has been a problem on my mind for years, but I never had a really good reason to sink time into it. Just recently, I finally found a reason. It occurred to me that it would be useful to have my webcam recognize magic cards by their art, and add them to a database for collection tracking. I've since learned that this wasn't as new an idea as I'd thought, and several complete software packages for this specific application have become available in the last 6 months. Nevertheless, it was an interesting excursion into image processing, admittedly not my home turf. It worked much better than planned too.

To my mind, the problem had three main tasks that I'd not undertaken before, in order of drastically increasing difficulty:

  1. Grabbing camera input from Python
  2. Isolating the card from the background
  3. Usefully comparing images

The first part was mostly just an exercise in googling it and adapting the code to my webcam. Short version, use OpenCV2's VideoCapture method, and be sure to chuck out a few frames while the camera is auto-focusing and tuning the white balance. The second bit proved to be slightly more interesting. Given a photo of a card on a plain white background, canny edge detection can reliably pull out the edge (though I haven't tried this with white-boarded cards yet). The card-background contour is easily picked it; it has the largest area. Once we've cropped the image down to that, we can isolate the art by knowing the ratios used to layout the cards. This process is shown below.

Original image

Original image



Isolated card

Isolated card

Isolated art

Isolated art

The third and most difficult step, effectively comparing the images, will have to wait until I've got more time to write. Soon!

Music Video Exchange

The CD-exchange group I've been meeting with for several weeks now decided to have a session entirely dedicated to sharing music videos. Given the ease of distribution, we settled on videos available freely online. I've compile the lists into one long YouTube playlist, which only misses out on a single track (Royksopp's "Remind Me", which is on Vimeo). Clocking in at just about two hours, the entire list makes for an interesting and discussion-sparking evening. While Beach House's "Wishes" was the stand-out video, I thoroughly enjoyed all the selections. Feel free to share your thoughts in the comments, or link to your favorite music videos.


Most Likely to Rock - A Metal Overview

Some context is necessary here. Several of my friends have formed a sort of bi-weekly disc exchange program in the spirit of old painfully 90s mix-tapes. Each week we're either exchanging CDs or meeting to discuss the selections we've listened to. It's been fun so far, providing an excuse to discover new music. In addition it's required us to engage in focused listening and critically evaluate what we're hearing before the discussion. Typically they're curated around a broad theme like "travel", but this previous round turned into a genre-focused overview, with each member tackling a genre that they had more familiarity with. I'd gotten it into my head that I knew a decent amount about metal music, so I went with that idea. Various factors collided to delay the next meeting, meaning I had something like six weeks rather than two to compose my disc. This is good, because I discovered that I actually knew very little about metal going into this.

I ended up spending an solid chunk of time just determining when and how various sub-genres of metal evolved, as well as what distinguished them from their siblings. Sites like Map of Metal and Every Noise at Once provided an amazing starting point as well as a shot of motivation for the task. While this did result in a playlist, the more interesting (read: time intensive) products were the liner notes. For each track I wrote up a short paragraph or two about the genre, threw in the album cover, lyrics, and a list of other artists that fall into the same camp. It's worth noting that chronology was used as the organizing principle behind the playlist, so don't expect smooth transitions nor consistent tempos. The tracks were selected with three goals: provide exemplary tracks for the genres, be accessible for an audience who had never been interested in metal before, and above all fit within the 80 minute limit of a CD-R. I dropped a lot of amazing tracks to stay under the limit, and they were painful omissions, but the various metalheads I consulted with eventually agreed that it was a reasonable introduction.

Enough words, here's the goods.

Album Cover

Playlist (Google Docs)
Liner Notes (PDF)