October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
ThatPainter
algorithmic art

An Algorithm for Art: How Thread Portraits Turn Photos Into Line by Line Paintings

Do these 3 things before closing this tab:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minute

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ThatPainter is reader-supported. When you buy through links on our site, we may earn an affiliate commission. Learn More

A thread portrait is a photograph rebuilt from straight lines. Instead of applying paint or shading every pixel, the maker stretches dark thread between nails around a circular wooden panel. Enough overlapping chords create areas that appear dark, while sparse regions remain light.

Jenny Ma’s project, covered by Hackaday in 2021, uses a Python algorithm to decide which nail-to-nail line should be added next. The software produces the instructions; the artwork is still assembled by hand.

What is a thread portrait?

Thread portraits—also called string art, pin-and-thread art, filography, or algorithmic string art—represent an image with straight thread segments stretched between pins or nails. The finished surface has no continuous painted tones. Its apparent shading comes from line density, overlap, thread thickness, and the way the eye blends nearby marks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A single strand contributes a narrow dark line. Hundreds or thousands of strands crossing the same region create perceived darkness. This is different from:

#1 Best Overall
Ayervici Personalized Cross Stitch Kits Custom Photo Embroidery Kit Set Make Your Own Photo DIY Painting Full Embroidery Cross Stitch (12"*16"/30 * 40CM)
  • What a big fun to record beautiful moments with cotton thread. You can customize your own photos, family photos, dog photos, idol photos or a totem, etc
  • The fabric is clearly printed with small squares, which are colored and marked with symbols. Each symbol corresponds to the color of a cross-stitch thread
  • The colorful patterns and grid lines printed on the cross-stitch fabric are very easy to wash off after you finish embroidering,Not intended for users under 12/14 years old
  • The Package contains all the needed (very high-quality) supplies to start embroidering immediately: 1pc personalized printed stamped fabric, 3-4 needles, and 1 set of cotton cross stitch threads and instructions in multi-languages including English
  • Note:11CT uses 3 strands to stitch. Please do not wet the pre-covered pattern before finishing, otherwise the printed part will disappear
  • Physical darkness: the amount of thread actually covering the backing.
  • Perceived darkness: the tone a viewer sees after overlapping lines blend optically.
  • Algorithmic darkness: the remaining target value the program is trying to represent.

The method is algorithmic image processing, not evidence of a neural network or image-understanding system. The program measures image values along possible lines; it does not recognize a face in the human sense.

The project in brief

For Ma’s project, a portrait was mapped onto a circular arrangement of virtual nails. The physical artwork used an approximately 80-centimetre (31.5-inch) wooden circle. Although 300 nails were initially planned, the final layout used 298 when the intended count did not fit. Ma described roughly 300 nails as a practical sweet spot for this particular build, not as a universal optimum.

Once the nails were installed, the generated sequence told the maker which nail to connect to next. The computer therefore handled the repetitive design problem, while the physical construction remained a manual craft process.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How the image-making algorithm works

  1. Prepare the portrait. The image is cropped or fitted into a circle and converted to grayscale.
  2. Create virtual nails. Evenly spaced points are placed around the circumference.
  3. Choose a starting nail. The featured project starts from a random nail, so two runs may differ unless a random seed is controlled.
  4. Evaluate candidate chords. From the current nail, the program considers a line to every other nail.
  5. Score each line. It checks the image values beneath each candidate and identifies the line that passes through the greatest remaining darkness.
  6. Select the best candidate. The destination nail is appended to the output sequence.
  7. Subtract the line. The selected line’s contribution is removed from a working, or residual, image.
  8. Repeat. The current nail becomes the selected destination, and the process continues until a line limit or another stopping condition is reached.

The subtraction step is crucial. Without it, the same dark facial feature would remain the best answer and the program could repeatedly choose nearly the same chord. Removing each selected contribution makes later choices search for darkness that has not yet been represented.

This is a greedy optimization process: each choice is the best-looking option at that moment, rather than part of a guaranteed globally optimal solution. Early lines influence every later line.

Why straight lines can suggest a face

The program has a limited vocabulary: the possible chords connecting the perimeter nails. It cannot draw an arbitrary curve or independently set every pixel. Yet a portrait contains broad tonal structures that straight lines can approximate.

Dark hair may accumulate many overlapping chords. The eye sockets, nostrils, jawline, and shadows under the nose can emerge from changing line density. Light cheeks or a pale background receive fewer strands. At a suitable viewing distance, the individual geometry becomes less important than the overall distribution of darkness.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Sale
Zhenqing Johannes Vermeer's Girl with a Pearl Earring Cross Stitch Kit – 14CT 30x35cm Pre-Printed Full Coverage Embroidery, No Hoop Needed, Beginner-Friendly Art Craft (70346)
  • Vermeer’s Timeless Portrait: Pre-printed design faithfully reproduces the delicate facial expression, vibrant turban, luminous pearl earring, and soft shadow details of the original painting.
  • Beginner-Friendly & No Hoop Needed: Specially treated 14CT cotton fabric holds tension perfectly—start stitching right away with no extra tools or complex setup.
  • Full-Coverage Art Quality: 14CT fabric offers finer detail for a professional finish. Size 30x35cm is ideal for framing and home decor.
  • Complete Embroidery Kit: Includes color-accurate threads, needle, pre-printed fabric, and clear English instructions—everything you need in one box.
  • Elegant Display Ready: Once finished, this piece becomes a sophisticated artwork perfect for living rooms, studies, or galleries—a beautiful tribute to classical art.

The best result is not necessarily the one with the lowest pixel-by-pixel error. A mathematically plausible image can look muddy, tangled, or visually harsh when converted to real thread. A useful objective balances image similarity with recognizable facial structure, attractive line flow, manageable labor, and a physical line density that the material can support.

The geometry of the circular nail layout

A circular layout makes the design easier to describe and keeps the possible endpoints evenly distributed. For a circle centered at (c_x,c_y), with radius r and N nails, a standard evenly spaced model is:

x_i = c_x + r cos(2πi/N)
y_i = c_y + r sin(2πi/N)

This formula is the natural geometric interpretation of the project’s evenly spaced virtual nails; it is not a complete specification of Ma’s implementation.

In a reproduction, the image and the physical board must use the same center, radius, coordinate orientation, and indexing convention. A mismatch between clockwise and counterclockwise numbering, or between zero-based and one-based indexes, can make a correct digital sequence produce the wrong physical picture.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The circular frame also imposes a compositional constraint. A square or rectangular photograph must be cropped or distorted to fit the circle, and important features near the edge may disappear behind the mask.

A conceptual Python workflow

The core process can be expressed without claiming exact details from the original code:

load portrait
crop or resize to a square
convert to grayscale
apply a circular mask
place N virtual nails around the circle
choose a starting nail
create a residual image

repeat until the stopping rule is met:
    score the chord from the current nail to each candidate nail
    reject invalid or self-referential candidates
    choose the highest-scoring chord
    append its destination nail
    subtract its simulated contribution from the residual image
    move to the destination nail

export the ordered nail sequence

A resulting sequence might look like:

17 → 142 → 63 → 211 → 98 → ...

The builder wraps thread from nail 17 to 142, then from 142 to 63, and continues in order.

Rank #3
Meecaa Cross Stitch Kits 14 Count Stamped, Self-Portrait Cypress Tree Embroidery Kit with Accessories Pre Printed (Van Gogh Self-Portrait)
  • Fabric Size:40×47CM. This kit includes full range of necessary tools and accessories. NO physical frame included! 14CT Pre-printed cotton fabric, high-definition pattern, pre-sorted embroidery thread, 2× needles, 1× English instructions. We provide one third more threads than enough
  • Meecaa DIY cross stitch kit is stamped with nontoxic & washable dye. Accurately pre-printed pattern, easy to follow instructions as well as Arabic numbers, symbols and corresponding numbers make the cross-stitching work very easy and fun
  • 100% ecological cotton floss that is more brilliant in color and softer, finer, strong and sturdy, elegant style, beautiful appearance, makes your cross-stitch art more vivid and durable without fading
  • We use 14CT standard threads. One thread is composed of 6 strands, so you need to divide the 6 strands into three 2-strand lines before you work. After finishing, put the canvas in warm water for 20 minutes to wash off the pre-printed pattern
  • Cross stitch can help you to make your ordinary wall become vivifying. It is also a best choice of gifts, such as Christmas gifts, birthday gifts and so on. Suitable for teenagers, adults, beginners and advanced stitchers. If you run out of the threads, please feel free to contact us

A practical scoring routine would grayscale the target, sample pixels along each chord, calculate a darkness score, and account for darkness already removed from the residual image. The source description confirms this broad procedure, but not the original formula, rasterization resolution, thread-width simulation, or stopping threshold. Those should not be presented as exact features of Ma’s code without checking the original project materials.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Preparing a portrait for string art

Source-image preparation often matters as much as nail count. Begin with a square crop that places the face comfortably inside the future circle. Then:

  • Convert the image to grayscale.
  • Increase contrast enough to separate facial planes from the background.
  • Remove, simplify, or darken a busy background.
  • Use brightness or gamma adjustment to preserve important midtones.
  • Apply a mild blur to suppress tiny photographic details and noise.
  • Mask pixels outside the circle.
  • Invert the image only if the scoring convention requires dark regions to be represented by high values rather than low values.

Strong lighting, clear eyes and mouth, distinct hair boundaries, and a relatively simple background are generally helpful. Low-contrast photographs, multiple faces, patterned clothing, and pale subjects against pale backgrounds are harder to translate into a sparse vocabulary of chords.

Excessive sharpening can make the algorithm chase noise. Conversely, too little contrast can leave the program with no clear preference between candidate lines.

From digital sequence to physical artwork

  1. Build a rigid circular backing. The featured piece used an approximately 80 cm wooden canvas. A larger board needs more support and increases thread length.
  2. Generate a full-scale nail template. Mark the circle center, cardinal directions, and every nail position.
  3. Install and number the nails. Use durable labels and document the direction around the circle.
  4. Run the algorithm for the exact layout. If the physical count changes from 300 to 298, regenerate the sequence; the old coordinates no longer describe the same set of possible chords.
  5. Wrap the thread in order. Keep the strand taut but do not pull hard enough to bend nails, warp the board, or break the thread.
  6. Check progress in stages. Compare the physical piece with a digital simulation rather than waiting until the final line to discover a numbering error.

Before committing to a long sequence, test a short list of known nail pairs. This catches the most destructive setup errors: an off-by-one index, a reversed direction, a different first nail, or a flipped coordinate system.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choosing nails, canvas, thread, and line count

Nail count

More nails provide more endpoints, angles, and possible chords. They also increase marking, drilling, computation, numbering, congestion, and the chance of tangles. Fewer nails are easier to build but offer a coarser geometric vocabulary.

The project’s 298 nails are a useful reference for a large portrait, while Ma’s approximately 300-nail conclusion is specific to her canvas, materials, and visual judgment. It should not be treated as an engineering limit or guaranteed best choice.

Rank #4
EZDNKPI Tiger Face Portrait DIY 11CT Stamped Cross Stitch Kits for Beginners Easy Needlepoint Embroidery Counted Cross Stitch Art Craft for Wall Decoration 12x16inch
  • 【Size and Package】12x16 inch, 5pc cross stitch needles, enough thread already sorted, 1pc English instructions, 1pc cross stitch patterns instructions, and 1pc 11CT pre-printed stamped cross stitch fabric cloth
  • 【Stamped Cross Stitch Kits for Adults】Cross stitch kits gives a pre-set canvas and detailed description, complete tools, suitable for adults, beginners, you only need to follow the pre-set path, you can take the lead to reach the destination and complete the intellectual challenge
  • 【Crafted with High-quality Materials】Cotton thread used in the cross-stitch Kit is soft, bright-colored and durable-making your cross stitch silky, vivid and long-lasting. Definitely top-grade! Especially the fabric, weaved in three-ply, has enough thickness so that it can be easily play stitches on
  • 【Fulfilling Creative Journey】With our dimensions cross stitch kits, which provide a rewarding way to relieve stress and achieve a sense of accomplishment. Whether you are using them as unique crafts or decorative pieces, our counted cross stitching kits for adults will enhance your living space beautifully
  • 【After-Sales Service】If you have any issues with the adult cross-stitch kit you received, please contact us immediately, and we will resolve all issues for you.

Canvas diameter

A larger canvas can spread the same nail count over more space and improve viewing distance, but it requires a stronger backing and more thread. A small canvas is easier to handle; dense areas can become muddy if the thread is thick or the line count is high.

Thread

Choose thread with low stretch, consistent diameter, adequate strength, and a matte, dark finish for monochrome portraits. Smooth thread is easier to tension and less likely to snag. Fuzzy thread may create lines wider than the digital preview, while glossy thread can introduce highlights that alter perceived tone.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Tension

Loose thread sags and blurs the intended geometry. Excessive tension can pull out nails, warp a thin board, break the strand, or create overloaded bundles around frequently used nails. Consistency is more important than maximum tightness.

Line count

Additional lines generally increase darkness and detail until the image saturates. The available source does not establish a verified final segment count for the featured build, so there is no reliable universal number to copy. Stop when the digital preview stops gaining useful structure—or when additional physical density makes the portrait muddy.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failure modes

The face is unrecognizable

Simplify the source, recenter the crop, improve contrast, darken or remove the background, and blur fine detail slightly. Then try a different line budget, nail count, or starting nail. A portrait that is weak in grayscale will rarely become clearer through extra thread alone.

The output becomes almost black

Check that the residual image is actually updated after each selected line. Too many lines, an overly thick thread, or a scoring function that ignores existing darkness can all cause saturation. Reduce the line budget, strengthen residual subtraction, penalize already-dark regions, or model the real thread width.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The output is too faint

Increase the line budget or target contrast, use a darker or slightly heavier thread, brighten the backing, and check for loose spans. Remember that the physical result may be lighter or darker than a one-pixel digital simulation.

Best Value
RIOLIS 1912 Snowy Meow Counted Cross Stitch Kit 9.5 x 11.75 in
  • Snowy Meow — Watching the First Snowfall — A long-haired cat sits perfectly still while snowflakes drift through the air around it. The winter world seems to have paused for a moment, and the cat appears content to simply watch.
  • Everything Needed for a Cozy Winter Project — Includes Zweigart 10 ct white AIDA fabric, wool/acrylic threads in 11 colors, a needle, detailed instructions, and a color chart. The finished artwork measures 9½" × 11¾".
  • The Portrait Appears Fur by Fur — Soft shades of gray gradually shape the cat's face, tail, and flowing coat. With each completed section, more of its calm expression and character begin to emerge.
  • Silver Grays, Winter Whites & Frosty Blue Accents — A restrained palette keeps the focus on texture and atmosphere. Delicate snowflakes and cool highlights bring a gentle winter feeling to the design.
  • The Quietest Part of a Winter Day — No chasing, no jumping, no mischief. Just a cat, a few drifting snowflakes, and a moment of complete stillness. The finished piece captures the kind of calm that usually lasts only a minute before life starts moving again.

The physical result does not match the preview

Verify nail count, circle center, radius, starting nail, index origin, and clockwise or counterclockwise direction. Confirm that the physical nails are evenly spaced and that the preview uses the same coordinate orientation. Print a nail map and compare the first few connections manually.

Thread breaks or nails pull out

Reduce tension and inspect the backing. A thicker, more rigid board, consistently pre-drilled holes, and nails suited to the material can improve reliability. Also watch for nail positions that receive many wraps; the algorithm may need a penalty to avoid overloading individual endpoints.

What the method cannot do

The algorithm cannot freely draw curves, guarantee a globally optimal portrait, or preserve every small feature in the source. It is constrained by the available chords and by the physical behavior of thread.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Digital resolution and physical resolution are not the same. Nail count determines possible endpoints, but the final image also depends on canvas diameter, thread diameter, number of wraps, nail accuracy, tension, lighting, and viewing distance. A higher nail count alone does not guarantee a sharper portrait.

Likewise, the work is neither fully autonomous nor simply “AI art.” Software generates an ordered construction plan, but a person chooses and prepares the image, builds the board, installs and numbers the nails, selects materials, and winds the thread.

Useful extensions

  • Record a random seed or use a deterministic start for reproducible output.
  • Render lines with an estimated physical width instead of single-pixel strokes.
  • Compare several starting nails and retain the most recognizable or visually pleasing result.
  • Use edge-aware scoring so major facial boundaries receive more attention.
  • Prune implausible candidates to reduce computation.
  • Experiment with multiple thread colors, while recognizing that color introduces another calibration problem.
  • Adapt the geometry to oval, polygonal, or custom-shaped frames.
  • Generate a preview that includes expected thread overlap and lighting.
  • Use CNC tools or automated string-art machinery when repeatability or production volume matters.

Automation belongs to a different category from Ma’s handmade construction: it can reduce repetitive winding and improve positioning consistency, but adds machine cost, setup, maintenance, and software complexity. For a one-off portrait, the manual process is the point as much as the result.

A practical debugging checklist

  • Can you view the circular crop by itself?
  • Do the virtual nails align with a full-scale physical template?
  • Are the nails indexed from zero or one?
  • Does digital nail 0 correspond to the intended physical starting mark?
  • Does clockwise in software mean clockwise on the board?
  • Does a test chord appear in the expected place?
  • Does the residual image get visibly lighter where lines have been selected?
  • Does the preview simulate approximately the thread thickness you will use?
  • Have you saved the nail count, starting nail, orientation, and random seed with the output sequence?

Those intermediate images—the crop, nail map, first few chords, residual after successive batches, and final simulation—are more useful than a final result alone. They reveal whether a failure began in image preparation, geometry, scoring, or physical assembly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The appeal of thread portraits is precisely this handoff between computation and craft. A simple greedy rule turns a photograph into a sequence of constrained choices; hundreds of those choices become a tangible surface whose portrait appears only when the lines are seen together.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.