【问题标题】:Python 3 change turtle pen brightnessPython 3 改变乌龟笔的亮度
【发布时间】:2021-11-09 16:32:44
【问题描述】:

我正在尝试生成随机噪声,并将其绘制在屏幕上,但我需要乌龟的笔才能改变亮度

【问题讨论】:

  • 请澄清您的具体问题或提供其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。

标签: python turtle-graphics noise python-turtle


【解决方案1】:

您最好的选择可能是在白色(或您使用的任何背景)和您想要显示的“最亮”之间改变颜色。例如,如果您希望明亮的颜色为绿色,则您的 RGB 颜色代码将为 (0,255,0)。白色的 RGB 颜色代码是 (255,255,255)。因此,要改变“亮度”,您可以同时将红色和蓝色通道更改为 0(尽可能亮)和 255(尽可能暗)。

如果您想要说 100 级亮度,您可以使用 numpy (https://numpy.org/doc/stable/reference/generated/numpy.linspace.html) 中的 linspace 函数来获取等间距的值数组。

import numpy as np
color_range = np.linspace(255, 0, 100)
# color_range will be a np array of length 100 where color_range[0] = 255.0 
# and color_range[99] = 0.0

# now we can create a list of colors from least bright to most bright
colors = [(int(i),255,int(i)) for i in color_range] 
# colors[0] will be (255, 255, 255) which is white
# colors[99] will be (0, 255, 0) which is green

【讨论】:

    【解决方案2】:

    您可以使用colorsys 库在支持亮度的颜色模型(我们将在下面使用 HSV)和海龟使用的 RGB 颜色之间进行转换。这是一个渐变示例:

    from colorsys import hsv_to_rgb
    from turtle import Screen, Turtle
    
    WIDTH, HEIGHT = 100, 100
    CURSOR_SIZE = 20
    
    screen = Screen()
    screen.setup(WIDTH, HEIGHT)
    screen.setworldcoordinates(0, HEIGHT, WIDTH, 0)
    screen.tracer(False)
    
    turtle = Turtle()
    turtle.hideturtle()
    turtle.shape('square')
    turtle.shapesize(1 / CURSOR_SIZE)
    turtle.penup()
    
    for y in range(HEIGHT):
        turtle.goto(0, y)
    
        for x in range(WIDTH):
            value = x * y / (WIDTH * HEIGHT)
            rgb = hsv_to_rgb(0.0, 1.0, value)
            turtle.color(rgb)
            turtle.stamp()
            turtle.forward(1)
    
    screen.update()
    screen.exitonclick()
    

    输出

    所有颜色都是不同亮度的红色。要产生噪声,我们可以从 random 库中导入 random() 函数,并将 value 赋值更改为:

    value = random()
    

    (放大)输出

    【讨论】:

    • 当我尝试实现你的代码时,它给了我这个错误: NotImplementedError: colorsys is not yet implemented in Skulpt on line 1 in main.py
    • @JacobMorrison,由于 Skulpt 不包含库 colorsys.py,您可以转到 its source code 并将 hsv_to_rgb() 函数的定义复制到您自己的代码中,因为它完全是自包含。并删除import
    猜你喜欢
    • 2015-01-30
    • 2013-12-17
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2016-06-20
    • 2012-03-03
    • 2016-11-01
    • 1970-01-01
    相关资源
    最近更新 更多