
Automating Swatches
Mollie EdyShare
“Oliver,” none of you are saying, “Mollie sure offers a lot of colours of yarn with her products. How does she organise them all on her website?”
And the answer is that she doesn’t. I do. And it’s… it’s a little tedious. So I’ve tried to automate as much of the process as I can. Since Python is my bread and butter for coding, I’ve written a few scripts to do the job for me. So on today’s edition of Stitch & Post, I’d like to nerd out about how I use Python to get those lovely swatches.
First up, Mollie lets me know what wool yarn planning on using for a particular type of knit. She generally likes to stick to one or two styles per item (for example, James C Brett Aurora DK yarn and Stylecraft Special DK for hats, and never any kind of chunky yarn for names!), but all the colours she can source. Currently, she mostly gets them through Wool Warehouse, but it doesn’t really matter for me as long as there’s basically a catalogue with names and pictures of the yarn. So once I’m pointed to the right place, I’ve got a script to download the yarn pictures in all colours and assign them the correct names.
Now we’ve got the images, but that’s only half the job, because I still need to get them onto Mollie’s website to use as swatches. Importantly, I want to make sure they make square swatches, and they’re in a nice pleasing aesthetic order. It’s a multi-stage process, which took quite a while to crop and sort everything before I realised that I could just get a computer to do it.
The cropping’s easy. Just get the code to load the image and chop off sides as necessary until everything’s square. The sorting’s more difficult. I could easily get it to sort everything alphabetically, but that would invariably be a mishmash of colours. What I want is more of a gradient. That was easy enough when I manually sorted everything, my brain can easily sort red to orange to yellow to green to blue to purple to red. But how do I tell a computer to do that?
Basically, colour wheels. Computers can represent all colours as an HSV, which is basically a number representing where in this circle you are. You’ll have probably seen the HSV for colour pickers before, even if they didn’t register. But my point is, it’s literally a number assigned to a colour.
To make sure I get the main colour of each yarn, I blurred them before getting the HSV, which should account for any light parts or shaded parts. Then each yarn had an HSV, and I could sort them.
The method isn’t without flaws. For some reason, my code’s determined that white is a type of green, but this is just a hobby for me and it speeds things up. Haven’t yet worked out how to automate uploading them to the website, but maybe check in next week and I’ll have that sorted too.