Fundamentals 12 min read

Create a Peppa Pig Cartoon in Python: Turtle Art, Image Editing & Dynamic QR Codes

This tutorial shows why learning Python is valuable and walks you through four fun projects—drawing Peppa Pig with the turtle library, changing image backgrounds using OpenCV, splitting images into a 3×3 grid with Pillow, and creating dynamic QR codes with MyQR—complete with code examples and visual results.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Create a Peppa Pig Cartoon in Python: Turtle Art, Image Editing & Dynamic QR Codes

Why Learn Python?

Python is widely used in many jobs and can be applied to create entertaining projects, making it an excellent language to learn.

1. Draw Peppa Pig with Python

The turtle library provides simple graphics capabilities for drawing shapes and characters like Peppa Pig.

from turtle import *
# Draw nose
def nose(x,y):
    penup()
    goto(x,y)
    pendown()
    setheading(-30)
    begin_fill()
    a=0.4
    for i in range(120):
        if 0<=i<30 or 60<=i<90:
            a=a+0.08
            left(3)
            forward(a)
        else:
            a=a-0.08
            left(3)
            forward(a)
    end_fill()
    penup()
    setheading(90)
    forward(25)
    setheading(0)
    forward(10)
    pendown()
    pencolor(255,155,192)
    setheading(10)
    begin_fill()
    circle(5)
    color(160,82,45)
    end_fill()
    # ... (additional functions for head, ears, eyes, etc.)

def setting():
    pensize(4)
    hideturtle()
    colormode(255)
    color((255,155,192),"pink")
    setup(840,500)
    speed(10)

def main():
    setting()
    nose(-100,100)
    head(-69,167)
    ears(0,160)
    eyes(0,140)
    cheek(80,10)
    mouth(-20,30)
    body(-32,-8)
    hands(-56,-45)
    foot(2,-177)
    tail(148,-155)
    done()

if __name__ == '__main__':
    main()

Result:

2. Change Background Color with Python

By using OpenCV, each pixel can be examined and replaced to change the background color of an image.

import cv2
import numpy as np
# Read image
img = cv2.imread('zhu.jpg')
# Resize
img = cv2.resize(img, None, fx=0.5, fy=0.5)
rows, cols, channels = img.shape
cv2.imshow('img', img)
# Convert to HSV
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
cv2.imshow('hsv', hsv)
# Threshold for blue background
lower_blue = np.array([90,70,70])
upper_blue = np.array([110,255,255])
mask = cv2.inRange(hsv, lower_blue, upper_blue)
# Erode and dilate
erode = cv2.erode(mask, None, iterations=1)
cv2.imshow('erode', erode)

dilate = cv2.dilate(erode, None, iterations=1)
cv2.imshow('dilate', dilate)
# Replace white pixels with red
for i in range(rows):
    for j in range(cols):
        if erode[i,j] == 255:
            img[i,j] = (0,0,255)  # BGR
cv2.imshow('res', img)
cv2.waitKey(0)

Result:

3. Split Image into a 3×3 Grid

The Pillow library can pad an image to a square, then crop it into nine equal parts.

from PIL import Image
import sys

def fill_image(image):
    width, height = image.size
    new_len = width if width > height else height
    new_image = Image.new(image.mode, (new_len, new_len), color='white')
    if width > height:
        new_image.paste(image, (0, int((new_len - height) / 2)))
    else:
        new_image.paste(image, (int((new_len - width) / 2), 0))
    return new_image

def cut_image(image):
    width, height = image.size
    item_w = int(width / 3)
    item_h = int(height / 3)
    boxes = []
    for i in range(3):
        for j in range(3):
            box = (j*item_w, i*item_h, (j+1)*item_w, (i+1)*item_h)
            boxes.append(box)
    return [image.crop(b) for b in boxes]

def save_images(img_list):
    idx = 1
    for img in img_list:
        img.save(str(idx) + '.jpg')
        idx += 1

file_path = "zhuzhu.jpg"
img = Image.open(file_path)
img = fill_image(img)
imgs = cut_image(img)
save_images(imgs)

Result:

4. Generate a Dynamic QR Code

Using the MyQR library, a QR code can be generated with a static or animated background image.

from MyQR import myqr
import matplotlib.pyplot as plt
save_name = 'dynamic.gif'
myqr.run(
    words='https://blog.csdn.net/weixin_41261833',
    version=10,
    level='H',
    colorized=True,
    contrast=1.5,
    brightness=1.0,
    save_name=save_name,
    picture=r"G:\1Pycharm_Project\csdn分享系列\小猪佩奇的几个操作\动态.gif"
)
# Display the QR code
img = Image.open(save_name)
plt.figure('Image')
plt.imshow(img)
plt.axis('off')
plt.show()

Result:

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonTutorialOpenCVturtle graphics
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.