Extract RGB values from image
There are broadly three steps to find the dominant colors in an image:
- Extract RGB values into three lists.
- Perform k-means clustering on scaled RGB values.
- Display the colors of cluster centers.
To extract RGB values, we use the imread()
function of the image
class of matplotlib
. Empty lists, r
, g
and b
have been initialized.
For the purpose of finding dominant colors, we will be using the following image.
This is a part of the course
“Cluster Analysis in Python”
Exercise instructions
- Import
image
class ofmatplotlib
. - Read the image using the
imread()
function and print the dimensions of the resultant matrix. - Store the values for the three colors from all pixels in lists
r
,g
andb
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Import image class of matplotlib
____ as img
# Read batman image and print dimensions
batman_image = ____('batman.jpg')
print(____)
# Store RGB values of all pixels in lists r, g and b
for ____:
for temp_r, temp_g, temp_b in ____:
r.append(temp_r)
g.append(temp_g)
b.append(temp_b)
This exercise is part of the course
Cluster Analysis in Python
In this course, you will be introduced to unsupervised learning through techniques such as hierarchical and k-means clustering using the SciPy library.
Now that you are familiar with two of the most popular clustering techniques, this chapter helps you apply this knowledge to real-world problems. The chapter first discusses the process of finding dominant colors in an image, before moving on to the problem discussed in the introduction - clustering of news articles. The chapter concludes with a discussion on clustering with multiple variables, which makes it difficult to visualize all the data.
Exercise 1: Dominant colors in imagesExercise 2: Extract RGB values from imageExercise 3: How many dominant colors?Exercise 4: Display dominant colorsExercise 5: Document clusteringExercise 6: TF-IDF of movie plotsExercise 7: Top terms in movie clustersExercise 8: Clustering with multiple featuresExercise 9: Clustering with many featuresExercise 10: Basic checks on clustersExercise 11: FIFA 18: what makes a complete player?Exercise 12: Farewell!What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.