<html><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,…
- User
#canvas { border: 1px solid #000; }
.controls { margin-top: 20px; display: flex; flex-direction: column; gap: 10px; }
input, button { padding: 5px; font-size: 16px; }
button { cursor: pointer; background-color: #4CAF50; color: white; border: none; padding: 10px 20px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; transition-duration: 0.4s; }
button:hover { background-color: #45a049; }
把它移植到Python+Numpy,要求尽可能高效运行,效率越高越好,但功能不变,并且允许指定图像尺寸
- Assistant
好的,下面是使用 Python 和 NumPy 实现的高效代码,功能与您的 JavaScript 代码相同,并允许指定图像尺寸、方格宽度、高度以及第二图层的透明度。该代码充分利用了 NumPy 的向量化计算,尽可能提高运行效率。
import numpy as np from PIL import Image def render_image(width=500, height=500, square_width=50, square_height=50, layer_opacity=0.5): # 创建像素坐标网格 y, x = np.ogrid[0:height, 0:width] # 归一化坐标 x_norm = x / width y_norm = y / height # 第一图层:全局渐变 global_gradient = (x_norm + (1 - y_norm)) * 0.5 # 第二图层:方格渐变 x_mod = (x % square_width) / square_width y_mod = (y % square_height) / square_height square_gradient = (x_mod + (1 - y_mod)) * 0.5 # 叠加两个图层 final_color = global_gradient * (1 - layer_opacity * (1 - square_gradient)) # 将结果映射到 0-255 并转换为 8 位无符号整数 image_array = np.uint8(final_color * 255) # 创建灰度图像 image = Image.fromarray(image_array, mode='L') return image if __name__ == '__main__': # 用户可在此处指定参数 width = 500 # 图像宽度 height = 500 # 图像高度 square_width = 50 # 方格宽度 square_height = 50 # 方格高度 layer_opacity = 0.5 # 第二图层透明度(0 到 1) # 渲染图像 img = render_image(width, height, square_width, square_height, layer_opacity) # 保存图像 img.save('laji.png') # 显示图像(可选) img.show()