import numpy as np from PIL import Image import time
def save_image(data, out_path): data = data.astype(np.uint8) image = Image.fromarray(data, mode='L') image.save(out_path)
def sdf_sphere(x, y, cx, cy, r): """计算点 (x, y) 到中心为 (cx, cy) 且半径为 r 的圆的符号距离""" dx = x - cx dy = y - cy return np.sqrt(dx * dx + dy * dy) - r
def func1(input_image): """For循环遍历每一个元素""" width = input_image.shape[0] height = input_image.shape[1] print(f'width: {width}, height: {height}') for i in range(width): for j in range(height): u = i / width v = j / height if sdf_sphere(u, v, 0.5, 0.5, 0.2) < 0.1: input_image[i, j] = 255 return input_image
def func2(input_image): """使用np向量操作""" width = input_image.shape[0] height = input_image.shape[1] u, v = np.meshgrid(np.linspace(0, 1, width), np.linspace(0, 1, height), indexing='ij') distances = sdf_sphere(u, v, 0.5, 0.5, 0.2) input_image[distances < 0.1] = 255 return input_image
if __name__ == "__main__": image1 = np.zeros((512, 512), dtype=np.float32) image2 = np.zeros((512, 512), dtype=np.float32) start_time = time.time() out1 = func1(image1) end_time = time.time() print(end_time - start_time) start_time = time.time() out2 = func2(image2) end_time = time.time() print(end_time - start_time) save_image(out1, 'assets/temp/image.png') save_image(out2, 'assets/temp/image2.png')
|