Rubix Solver
I have never been able to solve a Rubix Cube. I know there are algorithms for it, but I just can’t crack the nut. Friends and colleagues through the years have gone through the shuffle and solve, but much like juggling it is an act I am destined to watch. I could wallow in self pity or I could set about sicking technology on a people problem. It’s a pickle!
After a bit of googling it appears the first step to a machine solving D-Wade presents The Cube would be to identify the colors present. After an exhaustive few rounds of GPT-Googling interlaced with trial and error I landed on the following:
1 | function detectColors(img) |
The detectColors function is designed to detect and classify colors from specific points on an image of a Rubik’s Cube by analyzing pixel RGB values. It uses hardcoded predefined grid and color ranges to identify and return the detected colors. I create a canvas element, get the context for 2D drawing and draw the image (in our case the Rubix). My grid array is a set of hardcoded points normalized to align to spots roughly 10, 40, 70% through the image. This [3x3] set of (x,y) coordinates corresponds to where the colors should be.
Alongside the general grid for detection colorRanges is an object that defines RGB value ranges for the six Rubix colors: white, yellow, blue, green, red, and orange. Each color is associated with an array containing two RGB triplets representing the minimum and maximum values for that color. An empty array colors is initialized to store the detected colors.
The function loops through each coordinate and calculates the corresponding pixel’s (x,y) position on the canvas. context.getImageData(x, y, 1, 1).data retrieves the RGBA values of the pixel at the specified position. The detected color is determined by discarding that alpha quicker than ‘Rona and comparing the pixel’s RGB values against the defined value from colorRanges. Object.keys(colorRanges).find is used to find the color whose range includes the pixel’s RGB values. Which seems a bit hacky, but dang if it doesn’t work fairly well.
There are still instances where unknown pops up when detecting colors, so spending more time to shore it up before production will be required, but for now I’m satisfied. Demo in the future at some point will be part 2: