【问题标题】:Black to Red fade on ppm using python [duplicate]使用python在ppm上从黑色到红色褪色[重复]
【发布时间】:2013-02-24 22:58:22
【问题描述】:

Python

我如何操作此代码以给我一个从左到右从黑色渐变为红色的图像,其中左侧为黑色,右侧为红色。

def main():
    f = open("testImage.ppm","w")
    f.write("P3 \n")
    width=256
    height=256
    f.write("%d %d \n"%(width,height))
    f.write("255 \n")
    for i in range(width*height):
        x=i%256
        y=i/256
        f.write("255, 0, 0 \n")
    f.close()

main()

【问题讨论】:

    标签: python ppm


    【解决方案1】:

    在你的循环中,你总是写255, 0, 0。那是红色,绿色,蓝色的三重奏。循环上方255 的写入指定最大值为255。图像的宽度为256 像素。 [0, 255] 范围内有 256 个值。因此,很容易推断出红色分量应该是 X 值。您可以将代码修改为如下所示:

    f.write("%d, 0, 0 \n" % x)
    

    【讨论】:

    • 效果很好,谢谢
    • 说红色分量应该是 X 值仅在特定情况下才正确,因为图像恰好是 256 像素宽。一般来说,对于其他宽度的任意大小的图像,这是不真实的,颜色会有所不同。
    【解决方案2】:

    由于您希望淡入淡出从左到右从黑色变为红色,因此图像的每一行都是相同的,只需要创建一次并反复使用。 PPM 图像文件的每个数据行将如下所示,其中每个三元组值对应一个 RGB 三元组:

    0 0 0 1 0 0 2 0 0 3 0 0 4 0 0 5 . . . 251 0 0 252 0 0 253 0 0 254 0 0 255 0 0
    

    这是您的代码的修改版本:

    def main():
        with open("testImage.ppm", "wb") as f:
            f.write("P3\n")
            width = 256
            height = 256
            f.write("%d %d\n"%(width,height))
            f.write("255\n")
            delta_red = 256./width
            row = ' '.join('{} {} {}'.format(int(i*delta_red), 0, 0)
                                             for i in xrange(width)) + '\n'
            for _ in xrange(height):
                f.write(row)
    
    main()
    

    这是实际结果(转换为本网站的 .png 格式):

    【讨论】:

    • 谢谢,效果很好
    • @user2105564:请注意,在计算每个像素的红色量时会考虑图像的width。其他答案没有这样做,因此尽管它们可能适用于您在示例中使用的 256 像素宽的图像,但它们并不能解决更普遍的问题。
    【解决方案3】:

    您快到了,但您需要将红色计算放入遍历每个像素的循环中。你一直在写 (255,0,0) 但你想写 (x,0,0)。

    def main():
        f = open("testImage.ppm","w")
        f.write("P3 \n")
        width=256
        height=256
        f.write("%d %d \n"%(width,height))
        f.write("255 \n")
        for i in range(width*height):
            x=i%256
            y=i/256
            f.write("%s, 0, 0 \n" % x)  #SEE THIS LINE
        f.close()
    
    main()
    

    【讨论】:

    • 效果很好,谢谢。
    猜你喜欢
    • 2019-12-14
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 2021-10-26
    • 2018-09-15
    • 1970-01-01
    • 2014-11-03
    • 2016-07-17
    相关资源
    最近更新 更多