发布于 2021-06-03 07:04:50
注意到:这绝不是一个好的解决方案,我写这个答案是为了让你有一个答案,不管是好是坏。
我的方法是创建一个图像,并将每个像素作为一个点在图形上,方法是将像素的x坐标插入一个函数中,该函数返回一个与像素的y坐标相对应的数字。如果函数的结果等于y坐标,则像素的颜色会发生变化。我添加了一些选项来自定义图形的外观。下面是函数(它只是一个原型的意思,而不是其潜在的效率,如果您喜欢这种方法,我可以改进代码):
from numbers import Number
def draw_graph(image, math_func, *,
error=10,
x_scale=1, y_scale=1,
x_offset=None, y_offset=None,
color=(0, 255, 0)):
if x_offset is None:
x_offset = image.width // 2
if y_offset is None:
y_offset = image.height // 2
pxls = image.load()
for x in range(image.width):
for y in range(image.height):
output = math_func((x - x_offset) / x_scale)
if isinstance(output, Number):
if output - error <= (image.height - y - y_offset) / y_scale <= output + error:
pxls[x, y] = color
elif isinstance(output, tuple):
for out in output:
if out - error <= (image.height - y - y_offset) / y_scale <= out + error:
pxls[x, y] = colorimage是一个枕头图像对象,math_func是一个接受整数(x)并返回数字或元组(多个值)的函数,错误是函数的输出必须与像素的y坐标有多近才能被着色,其余的参数是不言自明的。如果match_func返回None,则函数将忽略它。
下面是函数的示例用法(图像应该在程序结束时显示出来):
from PIL import Image
from numbers import Number
from math import sqrt
def third_power(x):
return 0.01 * x**3
def one_over_x(x):
return 1 / x if x != 0 else None
def idk(x):
return sqrt(x*x - 3) if x*x > 3 else None
def draw_graph(image, math_func, *,
error=10,
x_scale=1, y_scale=1,
x_offset=None, y_offset=None,
color=(0, 255, 0)):
if x_offset is None:
x_offset = image.width // 2
if y_offset is None:
y_offset = image.height // 2
pxls = image.load()
for x in range(image.width):
for y in range(image.height):
output = math_func((x - x_offset) / x_scale)
if isinstance(output, Number):
if output - error <= (image.height - y - y_offset) / y_scale <= output + error:
pxls[x, y] = color
elif isinstance(output, tuple):
for out in output:
if out - error <= (image.height - y - y_offset) / y_scale <= out + error:
pxls[x, y] = color
img1 = Image.new("RGB", (200, 200), "black")
draw_graph(img1, third_power, error=5, x_scale=3)
draw_graph(img1, one_over_x, error=3, x_scale=100, color=(255, 0, 0))
draw_graph(img1, idk, error=1, x_scale=3, y_scale=10, color=(0, 0, 255))
img1.show()
img2 = Image.new("RGB", (2000, 2000), "black")
draw_graph(img2, lambda x: x*x, x_scale=10, y_scale=2)
img2.show()如果我在这个答复上出了错,请评论一下,现在是凌晨3点。我无法抗拒好的挑战。我希望你觉得这个答案有用或有创意。
https://stackoverflow.com/questions/67753303
复制相似问题