python画立方体--魔方
作者:hqx 发布时间:2022-04-22 10:20:43
标签:python,画,立方体,魔方
直接进入主题
立方体每列颜色不同:
# Import libraries
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
# Create axis
axes = [5,5,5]
# Create Data
data = np.ones(axes, dtype=np.bool)
# Controll Tranperency
alpha = 0.9
# Control colour
colors = np.empty(axes + [4], dtype=np.float32)
colors[0] = [1, 0, 0, alpha] # red
colors[1] = [0, 1, 0, alpha] # green
colors[2] = [0, 0, 1, alpha] # blue
colors[3] = [1, 1, 0, alpha] # yellow
colors[4] = [1, 1, 1, alpha] # grey
# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Voxels is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
立方体各面颜色不同:
import matplotlib.pyplot as plt
import numpy as np
def generate_rubik_cube(nx, ny, nz):
"""
根据输入生成指定尺寸的魔方
:param nx:
:param ny:
:param nz:
:return:
"""
# 准备一些坐标
n_voxels = np.ones((nx + 2, ny + 2, nz + 2), dtype=bool)
# 生成间隙
size = np.array(n_voxels.shape) * 2
filled_2 = np.zeros(size - 1, dtype=n_voxels.dtype)
filled_2[::2, ::2, ::2] = n_voxels
# 缩小间隙
# 构建voxels顶点控制网格
# x, y, z均为6x6x8的矩阵,为voxels的网格,3x3x4个小方块,共有6x6x8个顶点。
# 这里//2是精髓,把索引范围从[0 1 2 3 4 5]转换为[0 0 1 1 2 2],这样就可以单独设立每个方块的顶点范围
x, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2 # 3x6x6x8,其中x,y,z均为6x6x8
x[1::2, :, :] += 0.95
y[:, 1::2, :] += 0.95
z[:, :, 1::2] += 0.95
# 修改最外面的面
x[0, :, :] += 0.94
y[:, 0, :] += 0.94
z[:, :, 0] += 0.94
x[-1, :, :] -= 0.94
y[:, -1, :] -= 0.94
z[:, :, -1] -= 0.94
# 去除边角料
filled_2[0, 0, :] = 0
filled_2[0, -1, :] = 0
filled_2[-1, 0, :] = 0
filled_2[-1, -1, :] = 0
filled_2[:, 0, 0] = 0
filled_2[:, 0, -1] = 0
filled_2[:, -1, 0] = 0
filled_2[:, -1, -1] = 0
filled_2[0, :, 0] = 0
filled_2[0, :, -1] = 0
filled_2[-1, :, 0] = 0
filled_2[-1, :, -1] = 0
# 给魔方六个面赋予不同的颜色
colors = np.array(['#ffd400', "#fffffb", "#f47920", "#d71345", "#145b7d", "#45b97c"])
facecolors = np.full(filled_2.shape, '#77787b') # 设一个灰色的基调
# facecolors = np.zeros(filled_2.shape, dtype='U7')
facecolors[:, :, -1] = colors[0] # 上黄
facecolors[:, :, 0] = colors[1] # 下白
facecolors[:, 0, :] = colors[2] # 左橙
facecolors[:, -1, :] = colors[3] # 右红
facecolors[0, :, :] = colors[4] # 前蓝
facecolors[-1, :, :] = colors[5] # 后绿
ax = plt.figure().add_subplot(projection='3d')
ax.voxels(x, y, z, filled_2, facecolors=facecolors)
plt.show()
if __name__ == '__main__':
generate_rubik_cube(4, 4, 4)
彩色透视立方体:
from __future__ import division
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from matplotlib.pyplot import figure, show
def quad(plane='xy', origin=None, width=1, height=1, depth=0):
u, v = (0, 0) if origin is None else origin
plane = plane.lower()
if plane == 'xy':
vertices = ((u, v, depth),
(u + width, v, depth),
(u + width, v + height, depth),
(u, v + height, depth))
elif plane == 'xz':
vertices = ((u, depth, v),
(u + width, depth, v),
(u + width, depth, v + height),
(u, depth, v + height))
elif plane == 'yz':
vertices = ((depth, u, v),
(depth, u + width, v),
(depth, u + width, v + height),
(depth, u, v + height))
else:
raise ValueError('"{0}" is not a supported plane!'.format(plane))
return np.array(vertices)
def grid(plane='xy',
origin=None,
width=1,
height=1,
depth=0,
width_segments=1,
height_segments=1):
u, v = (0, 0) if origin is None else origin
w_x, h_y = width / width_segments, height / height_segments
quads = []
for i in range(width_segments):
for j in range(height_segments):
quads.append(
quad(plane, (i * w_x + u, j * h_y + v), w_x, h_y, depth))
return np.array(quads)
def cube(plane=None,
origin=None,
width=1,
height=1,
depth=1,
width_segments=1,
height_segments=1,
depth_segments=1):
plane = (('+x', '-x', '+y', '-y', '+z', '-z')
if plane is None else
[p.lower() for p in plane])
u, v, w = (0, 0, 0) if origin is None else origin
w_s, h_s, d_s = width_segments, height_segments, depth_segments
grids = []
if '-z' in plane:
grids.extend(grid('xy', (u, w), width, depth, v, w_s, d_s))
if '+z' in plane:
grids.extend(grid('xy', (u, w), width, depth, v + height, w_s, d_s))
if '-y' in plane:
grids.extend(grid('xz', (u, v), width, height, w, w_s, h_s))
if '+y' in plane:
grids.extend(grid('xz', (u, v), width, height, w + depth, w_s, h_s))
if '-x' in plane:
grids.extend(grid('yz', (w, v), depth, height, u, d_s, h_s))
if '+x' in plane:
grids.extend(grid('yz', (w, v), depth, height, u + width, d_s, h_s))
return np.array(grids)
canvas = figure()
axes = Axes3D(canvas)
quads = cube(width_segments=4, height_segments=4, depth_segments=4)
# You can replace the following line by whatever suits you. Here, we compute
# each quad colour by averaging its vertices positions.
RGB = np.average(quads, axis=-2)
# Setting +xz and -xz plane faces to black.
RGB[RGB[..., 1] == 0] = 0
RGB[RGB[..., 1] == 1] = 0
# Adding an alpha value to the colour array.
RGBA = np.hstack((RGB, np.full((RGB.shape[0], 1), .85)))
collection = Poly3DCollection(quads)
collection.set_color(RGBA)
axes.add_collection3d(collection)
show()
来源:https://blog.csdn.net/weixin_44853840/article/details/123794474


猜你喜欢
- 如何生成指定区间中的随机数要求生成区间[a, b]中的随机数。若要求为浮点数,则Python中只能近似达到这一要求,因为随机函数的取值区间一
- 之前跟一些小伙伴有个讨论:大概就是很多跟数据打交道的朋友都面对过很复杂的excel公式,有时嵌套层数特别多,肉眼观看很容易蒙圈。有了这样的需
- 以下的文章主要是介绍SQL Server数据转换服务的4妙用之执行一些自动化的操作。在SQL Server数据库的实际操作管理中,数据库管理
- php cookie中不能使用点号(句号),实际上不是很严格,应该说可以使用点号的cookie名,但会被转换,你命名一个cookie:$_C
- 概述据说fastapi是目前最快的异步框架,遂决定将其和django异步进行并发比较。先说结果fastapi的异步可以使整体运行速度非常均衡
- 本篇介绍Python中的引用。首先想一想如图示例。在python中,值是靠引用来传递来的。用id()来判断两个变量是否为同一个值的引用。如图
- 本文实例讲述了python开发之文件操作用法。分享给大家供大家参考,具体如下:先来看看官方API:os-Miscellaneous oper
- 首先要下载:Graphviz - Graph Visualization Software安装完成后将安装目录的bin 路径加到系统路径中,
- 本文实例讲述了C#创建数据库及导入sql脚本的方法。分享给大家供大家参考,具体如下:C#创建数据库:/// <summary>/
- 如果直接使用base64_encode和base64_decode方法的话,生成的字符串可能不适用URL地址。下面的方法可以解决该问题:UR
- PHP 跳转,即重定向浏览器到指定的 URL,是一个很常见的功能。这种功能也有一些细节性的要求,比如等待多少秒以后跳转,用不用JavaScr
- 前言因为工作中不怎么使用python,所以对python的了解不够,只是在使用的时候才去学,在之前的几个例子中几乎没使用什么python的特
- Jupyter Notebook本身是默认使用一种Anaconda中root目录下的Python环境的,如果想使用其它的虚拟环境,还需要通过
- 在任何编辑器中,获取光标位置都是非常重要的,很多人可能认为较难,其实只要处理好浏览器的兼容,还是比较容易实现的。下面我们一起来看看如何获取到
- 本文介绍了node.js用fs.rename强制重命名或移动文件夹的方法,首先介绍了rename的用法,具体如下:【重命名文件夹】// re
- 题目:有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?程序分析:可填在百位、十位、个位的数字都是1、2、3、
- 作用collate_fn:即用于collate的function,用于整理数据的函数。说到整理数据,你当然要会用数据,即会用数据制作工具to
- drop方法有一个可选参数inplace,表明可对原数组作出修改并返回一个新数组。不管参数默认为False还是设置为True,原数组的内存值
- 数据去重可以使用duplicated()和drop_duplicates()两个方法。DataFrame.duplicated(subset
- 本文实例为大家分享了css+html+js实现五角星评分的具体代码,供大家参考,具体内容如下效果图:css:<style>&nb