Python 不仅是功能强大的编程语言,它同样可以用来创造 富有创意和美感 的视觉艺术!今天,我们分享 几种 Python 代码绘制爱心 的独特方式,涵盖 数学公式、字符艺术(ASCII)、turtle 绘图,让你感受 Python 代码的浪漫魅力!💘


1. 经典数学方程绘制爱心 ❤️

📌 方式:基于参数方程绘制爱心曲线

使用 Matplotlib + NumPy,基于数学公式绘制光滑的爱心曲线:

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(0, 2 * np.pi, 1000)
x = 16 * np.sin(t) ** 3
y = 13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)

plt.plot(x, y, 'r', linewidth=3)
plt.fill(x, y, 'red', alpha=0.5)  # 填充爱心
plt.axis("equal")
plt.title("Python 绘制爱心曲线", fontsize=14)
plt.show()

🌟 代码解析:

参数方程 (x, y) 生成爱心形状

Matplotlib 进行绘制,并填充红色

axis(“equal”) 保持图形比例

效果:红色爱心曲线,美观优雅!


2. ASCII 代码生成爱心 💖

📌 方式:利用字符艺术 (ASCII Art)

如果你想用 纯文本 生成爱心,Python 也可以轻松实现!

message = "I Love Python!"
for y in range(12, -12, -1):
    line = ""
    for x in range(-30, 30):
        formula = ((x * 0.04) ** 2 + (y * 0.1) ** 2 - 1) ** 3 - (x * 0.04) ** 2 * (y * 0.1) ** 3
        line += message[(x - y) % len(message)] if formula <= 0 else " "
    print(line)

🌟 代码解析:

• 通过数学公式创建 字符形状的爱心

• 使用 I Love Python! 进行填充,形成动态效果

适用于终端展示浪漫 ASCII 爱心 💝


3. Python Turtle 绘制动态爱心 🐢

📌 方式:用 Turtle 库绘制动画爱心

Turtle 是 Python 自带的绘图库,可以用它来绘制一个 动态爱心

import turtle

screen = turtle.Screen()
screen.bgcolor("black")

t = turtle.Turtle()
t.speed(0)
t.pensize(2)
t.color("red")

def draw_heart():
    t.penup()
    t.goto(0, -200)
    t.pendown()
    t.begin_fill()
    t.color("red")
    t.left(140)
    t.forward(180)
    for i in range(200):
        t.right(1)
        t.forward(2)
    t.left(120)
    for i in range(200):
        t.right(1)
        t.forward(2)
    t.forward(180)
    t.end_fill()

draw_heart()
t.hideturtle()
turtle.done()

🌟 代码解析:

Turtle 绘制爱心轮廓

红色填充,在黑色背景下视觉效果突出

适用于 GUI 界面、互动小程序


4. 使用 OpenCV 绘制炫酷渐变爱心 💜

import cv2
import numpy as np

image = np.zeros((500, 500, 3), dtype=np.uint8)

for i in range(50):
    t = np.linspace(0, 2 * np.pi, 1000)
    x = 16 * np.sin(t) ** 3 + 250
    y = -(13 * np.cos(t) - 5 * np.cos(2 * t) - 2 * np.cos(3 * t) - np.cos(4 * t)) * 10 + 300
    color = (i * 5, 0, 255 - i * 5)
    for j in range(len(x) - 1):
        cv2.line(image, (int(x[j]), int(y[j])), (int(x[j + 1]), int(y[j + 1])), color, 2)

cv2.imshow("Love Heart", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

🌟 代码解析:

利用 OpenCV 绘制多层次的爱心

使用循环产生渐变效果

适用于计算机视觉 & GUI 界面应用


✨ 结论:Python 爱心代码的魅力!

💡 Python 让编程更有趣,甚至可以创造浪漫!

Matplotlib:参数方程绘制爱心

ASCII Art:纯文本爱心字符画

Turtle:动态爱心绘图

OpenCV:渐变色视觉爱心

💬 你最喜欢哪种 Python 爱心代码?欢迎留言交流! ❤️

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐