Welcome to the CSC Q&A, on our server named in honor of Ada Lovelace. Write great code! Get help and give help!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+7 votes

I am having trouble understanding how to randomly select coordinates of the image and their color numbers and write them to the art file. I suppose I have to use the .getPixels() and color_rgb() but I don’t know how to set the loop up.

asked in CSC201 Spring 2021 by (1 point)

2 Answers

+4 votes

Essentially what you want to do is create a loop that will, in this order, select a random x and y point, get the RGB color values from the corresponding pixel in the .gif file, and then write all that data to the .art file in the format

Edit: As you mentioned, the .getPixel() function will return the RGB values, but they will return them as a list.

answered by (1 point)
+4 votes

Try to break each problem into smaller steps, potentially working backwards from your goal.

Goal: You want to find random coordinates. So, first you need to find a random x-coordinate, and a random y-coordinate.

To find a random x-coordinate, you need to know what range of values is allowed, before you can use the random module to generate a random number in that range. The range should be between 0 and the image width (or height) minus 1. So, how do you find the image width/height?

First, you need an Image object, which contains the data of the image loaded from the .gif file. Once you have that image object, try printing out the width or height. Run your code to test it.

Then try assigning the image width to a variable, and writing that value to the .art file. Test it.

Then make a new variable to represent your random x-coordinate, and set it to a random value in the right range. PRINT out the value to test it. Run it several times to make sure all random values are in the right range.

Do the same thing for a random y-value.

Once you have ONE random x and ONE random y value, you can use the image object's .getPixel(...) (not getPixels plural!) to get the color information from that x and y location.

PRINT out the results, so you can see what kind of data getPixel() returns.

Use that data to find the red, green, and blue values of the pixel, and print those out separately.

Then, try writing x, y, red, green, and blue all to the output text file. Test it.

Once you can do this for ONE random x and y location, THEN you an wrap a loop around it to try doing it many times.

This kind of iterative "code a bit, test a bit, code a bit, test a bit" cycle helps make it possible to solve large/hard problems...

answered by (508 points)
...