With this program, the user must provide an image and choose two pixels on the image to average the color of. This can also easily be expanded to more than 2 pixels in order to fully capture a more representative color of the whole image. Some applications such as Spotify use this technology to make the app interface match an image such as an album cover, but I mainly designed this code for use with colored LEDs.
For example: consider the following image as our sample…
Now I will choose two pixels whose colors I want to average. As previously mentioned, using more pixels will give a more accurate average but I want to keep the example simple and short.
Here we have the two colors I selected: Color 1 and Color 2. Color 1 is located within the circle, which is located about 480 pixels into the image horizontally and 70 pixels pixels vertically from the top. Color 2 is located 900 pixels into the image horizontally and 400 down from the top. These ‘coordinates’ are important because they tell the program where to look in the image in order to extract the RGB values.
The image is represented by an array that is way too large to show, but this code says to look for an R, G, and B value at coordinates 480, 70 and 900,400. Note how all of the values are subtracted by 1 because 0 represents the first entity in a sequence in Python. The first brackets represent how many pixels to look down from the top and the second brackets represents how many pixels to look in horizontally. As you can see, the final brackets contain 0, 1, or 2. Since RGB values are represented as a tuple like (152, 148, 166)- the R value corresponds to 0, G to 1, and B to 2. Running the code leaves us with these results:
The averaged result is simply calculated by adding all R values and dividing by how many different color samples you use (in this case 2). You then repeat this for the G and B values, giving a final RGB value for Color 3. Color 1 is (139, 202, 255), and Color 2 is (152, 148, 77). And of course, the final result for our averaged Color 3 is (145, 175, 166)