Draw Hanuman ji Using Python Turtle With Free Source Code

Draw Hanuman ji Using Python Turtle With Free Source Code

Introduction:

Hello friends, welcome to today’s blog post! In this article, we will learn how to take an SVG file and render it as a sketch using Python’s Turtle graphics module. This project will help you understand how to parse SVG paths. It is quite simple and fun! You need to know some basics of Python libraries like Turtle, which is used for drawing, svgpathtools for reading SVG paths, and tqdm for showing a progress bar during loading.

How to Run the Code:

Follow these simple steps:

1. Ensure Python is Installed:

Verify that Python (preferably version 3.6 or above) is installed on your system by typing the following in your command prompt or terminal:

python –version

2. Copy the Code:

Copy the complete source code (provided in the Source Code section below) into a file named, for example, hanumanji.py.

3. Navigate to Your Code Directory:

Open a terminal or command prompt and use the cd command to change to the directory where you saved the file.

cd path/to/directory

4. Run the Script:

Execute the script by typing:

python hanumanji.py

Code Explanation:

Step 1: Installing Required Libraries:

First of all, we have to install all the packages which we are using inside the code. For install the package simply you have to open the terminal and write.

pip install svgpathtools tqdm

After installing, import the required modules in your Python file:

import turtle as tu
import cv2
from svgpathtools import svg2paths2
from svg.path import parse_path
from tqdm import tqdm

Step 2: Creating the sketch_from_svg Class:

A class in Python helps organize code by bundling data and functions together. Here, we create a class called sketch_from_svg which will:

  • Load the SVG file,
  • Process SVG paths to extract drawing instructions,
  • Draw those paths using Python’s Turtle graphics.
Class sketch_from_svg:
def __init__(self,path,scale=30,x_offset=350,y_offset=350):
#Initializes the SVG path file location, scale for resizing, and offsets for positioning the drawing.
     self.path = path
        self.x_offset = x_offset
        self.y_offset = y_offset
        self.scale = scale

Step 3: Converting Hex Colors to RGB:

SVG colors are usually in hexadecimal format like #ff5733. However, Turtle expects colors in RGB format with float values between 0 and 1. For example:

  • Hex #ff0000 (pure red) becomes (1.0, 0.0, 0.0) in Turtle.

To convert the hex colors from the SVG into this Turtle-friendly format, we define a method inside our class called hex_to_rgb.

Step 4: Loading SVG Paths:

In this step, we create a method called load_svg() to read the SVG file and prepare it for drawing.

  • It uses svg2paths2() to load all paths and their colors from the SVG file.
  • It gets the SVG’s width and height to help with scaling.
  • Each path is parsed using parse_path() to get its shape.
  • The fill color is converted from hex to RGB using our earlier method.
  • Then, it takes several small points along the path to form a set of coordinates.
  • These coordinates are scaled and shifted to fit well on the Turtle screen.
  • Finally, it returns all the paths with their colors, ready for drawing.

Step 5: Drawing with Turtle:

Now that we have all the points and colors, we use the Turtle library to draw the shapes:

  • First, we create a Turtle pen and set its speed to the fastest.
  • For each shape (path), we move the pen to the starting point without drawing.
  • Then, we go through all the points and draw lines between them.
  • We also set the fill color and use begin_fill() and end_fill() to fill the shape with color.
  • After drawing everything, turtle.done() keeps the window open.

Step 6: Running the Code:

At the end, create an object of the class with your SVG file and call the draw() method:

pen = sketch_from_svg('your_svg_file.svg', scale=70)
pen.draw()

Python.py:

import turtle as tu
import cv2
from svgpathtools import svg2paths2
from svg.path import parse_path
from tqdm import tqdm

class sketch_from_svg:

    def __init__(self, path, scale=30, x_offset=350, y_offset=350):
        self.path = path
        self.x_offset = x_offset
        self.y_offset = y_offset
        self.scale = scale

    def hex_to_rgb(self, string):
        strlen = len(string)
        if string.startswith('#'):
            if strlen == 7:
                r = string[1:3]
                g = string[3:5]
                b = string[5:7]
            elif strlen == 4:
                r = string[1:2] * 2
                g = string[2:3] * 2
                b = string[3:4] * 2
        elif strlen == 3:
            r = string[0:1] * 2
            g = string[1:2] * 2
            b = string[2:3] * 2
        else:
            r = string[0:2]
            g = string[2:4]
            b = string[4:6]

        return int(r, 16) / 255, int(g, 16) / 255, int(b, 16) / 255

    def load_svg(self):
        print('loading data')
        paths, attributes, svg_att = svg2paths2(self.path)
        h = svg_att["height"]
        w = svg_att['width']
        self.height = int(h[:h.find('.')])
        self.width = int(w[:w.find('.')])

        res = []
        for i in tqdm(attributes):
            path = parse_path(i['d'])
            co = i['fill']
            col = self.hex_to_rgb(co)
            n = len(list(path)) + 2
            pts = [((int((p.real / self.width) * self.scale)) - self.x_offset,
                    (int((p.imag / self.height) * self.scale)) - self.y_offset)
                   for p in (path.point(i / n) for i in range(0, n + 1))]
            res.append((pts, col))
        print('svg data loaded')
        return res

    def move_to(self, x, y):
        self.pen.up()
        self.pen.goto(x, y)
        self.pen.down()

    def draw(self, retain=True):
        coordinates = self.load_svg()
        self.pen = tu.Turtle()
        self.pen.speed(0)
        for path_col in coordinates:
            f = 1
            self.pen.color('black')
            path = path_col[0]
            col = path_col[1]
            self.pen.color(col)
            self.pen.begin_fill()
            for coord in path:
                x, y = coord
                y *= -1
                if f:
                    self.move_to(x, y)
                    f = 0
                else:
                    self.pen.goto(x, y)
            self.pen.end_fill()

        if retain:
            tu.done()

pen = sketch_from_svg('hanumanji.svg', scale=70)
pen.draw()

Output:

When you run the code, a Turtle Graphics window opens, and the program sketches an SVG image using paths and color fills.

  • The Turtle reads the SVG file, extracts paths, and moves across the canvas to trace shapes.
  • The image’s colors are preserved as the Turtle fills shapes with the correct shades.
  • Once all paths are drawn, the output resembles a hand-drawn digital sketch of the original SVG image.

Note:

  • Replace ‘hanumanji.svg’ with your SVG file path.
  • You can adjust scale, x_offset, and y_offset to resize or reposition your drawing.