用Python实现光线追踪效果:逼真的光影动画




图片描述



个人简介:某不知名博主,致力于全栈领域的优质博客分享 | 用最优质的内容带来最舒适的阅读体验!文末获取免费IT学习资料!



🍅 文末获取更多信息 🍅 👇🏻 精彩专栏推荐订阅收藏 👇🏻



专栏系列直达链接相关介绍
书籍分享点我跳转书籍作为获取知识的重要途径,对于IT从业者来说更是不可或缺的资源。不定期更新IT图书,并在评论区抽取随机粉丝,书籍免费包邮到家
AI前沿点我跳转探讨人工智能技术领域的最新发展和创新,涵盖机器学习、深度学习、自然语言处理、计算机视觉等领域的研究进展和趋势分析。通过深入解读前沿技术、案例研究和行业动向,为读者带来关于人工智能未来发展方向和应用前景的洞察和启发。
Elasticsearch点我跳转详解 Elasticsearch 搜索和数据分析引擎
科技前沿点我跳转本档是关于科技和互联网的专栏,旨在为读者提供有趣、有用、有深度的科技资讯和思考。从多个角度探讨科技与人类生活的关系,包括但不限于科技趋势、产品评测、技术解读、行业观察、创业故事等内容。希望通过本栏,与读者分享科技的魅力和思考,让科技成为我们生活的一部分,而不仅仅是一个陌生的词汇。
Java之光点我跳转本栏将带领读者深入探索Java编程世界的种种奥秘。无论你是初学者还是资深开发者,这里都将为你提供丰富的Java知识和实用的编程技巧。
Linux学习日志点我跳转本专栏致力于探索Linux操作系统的各个方面,包括基础知识、系统管理、网络配置、安全性等。通过深入浅出的文章和实践指南,帮助读者更好地理解和应用Linux,提高系统管理和开发技能。无论你是初学者还是有经验的Linux用户,都能在本专栏中找到有用的信息和解决方案。
MySQL之旅点我跳转专栏将带领读者进入MySQL数据库的世界,探索其强大的功能和应用。我们将深入探讨MySQL的基本概念、SQL语言的应用、数据库设计与优化、数据备份与恢复等方面的知识,并结合实际案例进行讲解和实践操作。
精通Python百日计划点我跳转我们将引领你踏上一段为期100天的编程之旅,逐步深入了解和掌握Python编程语言。无论你是编程新手还是有一定基础的开发者,这个专栏都会为你提供系统而全面的学习路径,帮助你在短短100天内成为Python高手。




在这里插入图片描述

引言

光线追踪是一种生成高质量图像的技术,通过模拟光线与物体之间的交互来生成逼真的光影效果。在这篇博客中,我们将使用Python来实现一个简单的光线追踪算法,生成一个具有光影效果的三维场景。本文将带你一步步实现这一效果,并展示如何使用Python编程实现光线追踪。

准备工作

前置条件

在开始之前,你需要确保你的系统已经安装了以下库:

  • Numpy:用于高效的数值计算
  • Pillow:用于图像处理

如果你还没有安装这些库,可以使用以下命令进行安装:

pip install numpy pillow

代码实现与解析

导入必要的库

我们首先需要导入Numpy和Pillow库:

import numpy as np
from PIL import Image

定义光线追踪函数

我们定义一个函数来处理光线追踪的主要逻辑:

def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0:
       return v
    return v / norm

def intersect_sphere(origin, direction, sphere):
    oc = origin - sphere['center']
    a = np.dot(direction, direction)
    b = 2.0 * np.dot(oc, direction)
    c = np.dot(oc, oc) - sphere['radius']**2
    discriminant = b**2 - 4*a*c
    if discriminant < 0:
        return False, None
    else:
        t = (-b - np.sqrt(discriminant)) / (2.0 * a)
        return True, t

def ray_trace(origin, direction, spheres):
    closest_t = float('inf')
    hit_sphere = None
    for sphere in spheres:
        hit, t = intersect_sphere(origin, direction, sphere)
        if hit and t < closest_t:
            closest_t = t
            hit_sphere = sphere
    if hit_sphere is None:
        return np.array([0, 0, 0])
    hit_point = origin + closest_t * direction
    normal = normalize(hit_point - hit_sphere['center'])
    light_dir = normalize(np.array([1, 1, -1]))
    intensity = max(np.dot(normal, light_dir), 0)
    color = intensity * hit_sphere['color']
    return color

设置场景和渲染图像

我们定义场景中的球体及其属性,然后进行光线追踪并渲染图像:

width, height = 800, 600
camera = np.array([0, 0, 1])
viewport = np.array([2, 1.5, 1])
image = Image.new("RGB", (width, height))
pixels = image.load()

spheres = [
    {'center': np.array([0, 0, -5]), 'radius': 1, 'color': np.array([255, 0, 0])},
    {'center': np.array([-2, 1, -6]), 'radius': 1, 'color': np.array([0, 255, 0])},
    {'center': np.array([2, 1, -6]), 'radius': 1, 'color': np.array([0, 0, 255])}
]

for y in range(height):
    for x in range(width):
        px = (x / width) * viewport[0] - viewport[0] / 2
        py = -(y / height) * viewport[1] + viewport[1] / 2
        direction = normalize(np.array([px, py, -viewport[2]]) - camera)
        color = ray_trace(camera, direction, spheres)
        pixels[x, y] = tuple(color.astype(int))

image.show()

完整代码

import numpy as np
from PIL import Image

def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0:
       return v
    return v / norm

def intersect_sphere(origin, direction, sphere):
    oc = origin - sphere['center']
    a = np.dot(direction, direction)
    b = 2.0 * np.dot(oc, direction)
    c = np.dot(oc, oc) - sphere['radius']**2
    discriminant = b**2 - 4*a*c
    if discriminant < 0:
        return False, None
    else:
        t = (-b - np.sqrt(discriminant)) / (2.0 * a)
        return True, t

def ray_trace(origin, direction, spheres):
    closest_t = float('inf')
    hit_sphere = None
    for sphere in spheres:
        hit, t = intersect_sphere(origin, direction, sphere)
        if hit and t < closest_t:
            closest_t = t
            hit_sphere = sphere
    if hit_sphere is None:
        return np.array([0, 0, 0])
    hit_point = origin + closest_t * direction
    normal = normalize(hit_point - hit_sphere['center'])
    light_dir = normalize(np.array([1, 1, -1]))
    intensity = max(np.dot(normal, light_dir), 0)
    color = intensity * hit_sphere['color']
    return color

width, height = 800, 600
camera = np.array([0, 0, 1])
viewport = np.array([2, 1.5, 1])
image = Image.new("RGB", (width, height))
pixels = image.load()

spheres = [
    {'center': np.array([0, 0, -5]), 'radius': 1, 'color': np.array([255, 0, 0])},
    {'center': np.array([-2, 1, -6]), 'radius': 1, 'color': np.array([0, 255, 0])},
    {'center': np.array([2, 1, -6]), 'radius': 1, 'color': np.array([0, 0, 255])}
]

for y in range(height):
    for x in range(width):
        px = (x / width) * viewport[0] - viewport[0] / 2
        py = -(y / height) * viewport[1] + viewport[1] / 2
        direction = normalize(np.array([px, py, -viewport[2]]) - camera)
        color = ray_trace(camera, direction, spheres)
        pixels[x, y] = tuple(color.astype(int))

image.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

屿小夏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值