In: Computer Science
Using cImage in Python, how to create an image of a
sunset (at least 400 by 400 pixels), black at the top, becoming
redder/yellower lower down. Also, randomly place in the sky a given
number of white stars of random size of either one pixel or 4
(adjacent) pixels
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.
#code with no comments, for easy copying
import image
import random
def create_sunset(num_stars=10):
picture=image.EmptyImage(400,400)
divisions=255/picture.getHeight()
for i in range(picture.getHeight()):
pix=image.Pixel(int(divisions*i),int(divisions*i*0.7),0)
for j in range(picture.getWidth()):
picture.setPixel(j,i,pix)
pix=image.Pixel(255,255,255)
for i in range(num_stars):
row=random.randrange(0,picture.getHeight()//3)
col=random.randrange(0,picture.getWidth())
picture.setPixel(col,row,pix)
return picture
win = image.ImageWin("Image", 400, 400)
img = create_sunset(20)
img.draw(win)
win.mainloop()
#same code with comments, for learning
import image
import random
# method to create a 400x400 sunset image, and add num_stars number of stars
def create_sunset(num_stars=10):
# creating a 400x400 image
picture = image.EmptyImage(400, 400)
# dividing 255 by height to get a value to interpolate between colors
divisions = 255 / picture.getHeight()
# looping through each row
for i in range(picture.getHeight()):
# based on the row, creating a pixel. it will be darker in top, and reddish/yellow in bottom
# change 0.7 to 0.6 or 0.8 depending on you much reddish yellow you want.
pix = image.Pixel(int(divisions * i), int(divisions * i * 0.7), 0)
# looping through each column in current row, filling with this pixel
for j in range(picture.getWidth()):
picture.setPixel(j, i, pix)
# creating a pixel for white color
pix = image.Pixel(255, 255, 255)
# looping for num_stars number of times
for i in range(num_stars):
# generating a random set of row and col indices
# making sure that row is somewhere at the top (sky)
row = random.randrange(0, picture.getHeight() // 3)
col = random.randrange(0, picture.getWidth())
# filling that position with white
picture.setPixel(col, row, pix)
# returning picture
return picture
# creating a window, creating and displaying a sunset image, with 20 stars
win = image.ImageWin("Image", 400, 400)
img = create_sunset(20)
img.draw(win)
win.mainloop()
#output