Question

Python

How do I manipulate this code to give me an image that fades from black to red going from left to right, where left would be black and fade to red going right.

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()
Was it helpful?

Solution

In your loop, you're always writing 255, 0, 0. That's a triplet of red, green, blue. The write of 255 above the loop specifies that the maximum value is 255. The width of your image is 256 pixels. There are 256 values in the range [0, 255]. Thus, it is fairly simple to deduce that the red component should be the X value. You could modify your code to look like this:

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

OTHER TIPS

Since you want the fade to go black to red from left to right, each row of the image will be identical and only needs to be created once and used over and over. Each data row of the PPM image file will look something like the following where each trio of values correspond to an RGB triplets:

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

Here is a modified version of your code which does this:

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()

Here's the actual result (converted to .png format for this site):

black to red image created by modified code

You're nearly there, but you need to put your red calculation into the loop that goes over every pixel. You're constantly writing (255,0,0) but you want to be writing (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()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top