Average Color of an Image
Bash, 46 bytes
ImageMagick scales image to one pixel which contains average of the colors in the image then outputs it as text.
convert $1 -scale 1x1\! txt:-|egrep -o '#\w+'
Pyth - 23 22 19 18 16 bytes
Transposes to get all channels, then sums, divides, and hexifies each. Finishes by concatenating and prepending a #
.
+\#sm.H/sdldCs'z
Takes an image file name (any type) from stdin and outputs to stdout. VERY SLOW.
+ String concat
\# "#"
s String concat all channels
m Map
.H Hex string
/ ld Divided by length of channel
sd Sum of channel
C Transpose to separate into channels
s Concatenate all rows
'z Read image with filename input
Sample run
>>>pyth avg.pyth
V5VAR.jpg
#8b7d41
MATLAB - 68 bytes
The image is read in with imread
combined with uigetfile
to open up a GUI to choose the image you want to load in. The assumption with this code is that all images are RGB, and to calculate the average colour, we sum over each channel individually then divide by as many elements as there are in one channel, which is the total number of pixels in the RGB image (numel
(I)
) divided by 3. Because the average can possibly generate floating point values, a call to fix
is required to round the number down towards zero. sprintf
combined with the hexadecimal formatting string (%x
) is used to print out each integer value in the average into its hex equivalent. However, the 02
is there to ensure that an extra 0 is padded to the left should the average value for any channel be less than 16*.
I=imread(uigetfile);
['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))]
Sample Runs
The nice thing about imread
is that you can read in images directly from URLs. As a reproducible example, let's assume you have downloaded the images on your computer and have run the above code... but for demonstration, I'll read the images directly from Code Golf:
First Image
>> I=imread('http://i.stack.imgur.com/dkShg.jpg');
>> ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))]
ans =
#53715f
Second Image
>> I=imread('http://i.stack.imgur.com/V5VAR.jpg');
>> ['#' sprintf('%02x',fix(sum(sum(I))*3/numel(I)))]
ans =
#8b7d41
*Note: This was a collaborative effort made by StackOverflow users on the MATLAB and Octave chat room.