Professional Documents
Culture Documents
Teju Docu
Teju Docu
on
IMPLEMENTATION OF COLOR DETECTION THROUGH KNN AND
KMEANS USING OPENCV
Submitted by
Mrs. C PRIYANKA
TO
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE AND ENGINEERING
2021-2022
Department of Computer Science and Engineering
BONAFIDE CERTIFICATE
This is to certify that this is the bonafide certificate of an industrial oriented mini
(17W91A05H5) of B. Tech in the partial fulfilment of the requirements for the degree
Computer Science & Engineering and this has not been submitted for the award of any
I hereby declare that the Mini Project report entitled “Implementation Of Color
Detection through KNN and KMEANS using OPENCV” submitted to Malla
Reddy Institute of Engineering and Technology (Autonomous), affiliated to
Jawaharlal Nehru Technological University Hyderabad (JNTUH), for the award of the
degree of Bachelor of Technology in Computer Science & Engineering is a result of
original industrial oriented mini project done by me.
It is further declared that the seminar report or any part thereof has not been
previously submitted to any University or Institute for the award of degree or diploma
First and foremost, I am grateful to the Principal Dr. M. ASHOK, for providing
me with all the resources in the college to make my project a success. I thank him
for his valuable suggestions at the time of seminars which encouraged me to give
my best in the project.
I would also like to thank all the supporting staff of the Dept. of CSE and all other
departments who have been helpful directly or indirectly in making the project a
success.
ABSTRACT i
LIST OF FIGURES ii
LIST OF SCREENS iii
1 INTRODUCTION 1
1.1 Scope
1.2 Existing System
1.3 Proposed System
2 LITERATURE SURVEY 3
3 SYSTEM ANALYSIS 4
4 SYSTEM DESIGN 6
4.2 Modules
5 SYSTEM IMPLMENTATION 13
6 OUTPUT SCREENS 30
8 REFRENCES 39
ABSTRACT
Colour Detection is necessary to recognize objects. Colour detection is the process of detecting
the name of any colour. For humans this is an extremely easy task but for computers, it is not
straightforward. Human eyes and brains work together to translate light into colour. Light
receptors that are present in our eyes transmit the signal to the brain. Our brain then recognizes
the colour. Colours are made up of 3 primary colours; red, green, and blue.
In computers, we define each colour value within a range of 0 to 255. So in how many
ways we can define a colour.There are approximately 16.5 million different ways to represent a
colour. We represent colours on a computer by colour space or colour models which describes
range of colours as tuples of numbers . We will be using a dataset that contains RGB values
with their corresponding names and the colour name of apixel.
In our dataset, we need to map each colour’s values with their corresponding names and
we can know the range and names of colours on image by using K Nearest Neighbours).When
we double click on image it will display RGB values of color at x,y coordinates.Shortly, the
data includes formats colour names and Hex values/RGB mappings in various output. We are
also use K-means Clustering algorithm which creates clusters of colours and average cluster
colours and the proportion of pixels assigned to them the resulting cluster colours appear close
to our eye perceives. Here we fit and predict on the image to extract the colours and separate
them.
i
LIST OF FIGURES
ii
LIST OF SCREENS
1 Output-1 31
2 Output-2 32
3 Output-3 33
4 Output-4 34
5 Output-5 35
6 Output-6 36
7 Output-7 37
8 Output-8 38
iii
1. INTRODUCTION
In the advancement of AI Computer vision came into the image in late The 1960s. Its whole
purpose was to extend the intellect of the synthetic mechanism available by installing the
cameras into them or from an image and describe whatever they saw just like humans’
sensory systems. Thus, Computer vision should be ready to detect actual daily-life 3D objects
through 2D pictures . We have the r, g and b values. Now we need another function which
will return use the color name from RGB value. To get the color name, we calculate a
distance(d) which tells us how close we are to choose the one having minimum distance.
Many applications require real-time image processing like motion detection and color
recognition. Color recognition has many applications including biometric identification,
video surveillance, and object tracking. K-nearest neighbors (KNN) is widely used in neural
network and machine learning algorithm.KNN algorithm is a supervised classification
algorithm that needs labelled data to train on.
By Using color feature extraction, which is one among the image processing techniques,
the features that distinguish these colors are determined. These features increase the
effectiveness of the KNN classifier. The Euclidean distance is calculated at the position
clicked. The distance is calculated from each point and the shortest one is taken out of them.
The mouse events used when mouse is clicked on the Image it will display RGB values for
the color at the x,y coordinates. In this way at different positions the RGB values were
calculated.
1.1.Scope:
After this project work will have completed, In this Research area with all research
methodology, future scope, and results we learned about colors and therefore the way we will
extract color RGB values and the color name of a pixel. We learned the way to handle events
like double clicking on the window and CSV files with pandas and apply the Open CV library
to perform operations on data. This is often utilized in numerous image editing and drawing
apps. Here this is easy task for humans to detect the color and choose one. But computer
cannot detect the color easily. Many of the project and research papers are written on this
1
problem. But we use different techniques for this project. KNN algorithm, Pandas and Open
CV libraries used in python languages. KNN may be a simple technique for constructing
classifiers: models that assign class labels to problem instances, represented as vectors of
feature values, where the category labels are drawn from some finite set .we learned about
colors and how we can extract color RGB values and the color name of a pixel.
The existing system separates the colors based on their ranges. This is time taking
approach in order to detect fastly. It is not possible other than experts in order to detect
millions of colors and their ranges RGB values.
We can be able to detect and recognize the colors using K Nearest Neighbors by
implementing the KNN model in Open Cv module in Python programming Language.
Python programming Language provides libraries which also focus on the implementation of
KNN model.
Advantages:
2
2. LITERATURE SURVEY
3
3. SYSTEM ANALYSIS
Data Extraction:
Importing the libraries, and loading image using Open Cv creating the method in read( )
which reads or loads image from the specified path, RGB values also present these are stored
in a numpy array, at last is converted into .csv file.
KNN Model:
Extract the labels column from the first column of dataset, convert the labels into categorical
values. Now import the classifiers of knn model from the sciket Learn(sk learn) module and
create the model and calculate distance using Euclidean distance method and see howe
neighbors are responded and clissify, compile the model which provides accuracy of 94%.
Results Evaluation:
Test the model, provide the input image of colors and evaluate the results of the values.
4
requirements have to be known during the initial stages so that the system can be designed
according to those requirements. It is very difficult to change the system once it has been
designed and on the other hand designing a system, which does not cater to the requirements
of the user, is of no use.
The requirement specification for any system can be broadly stated as given below:
5
4. SYSTEM DESIGN
This section describes the system in narrative form using non-technical terms. It
should provide a high-level system architecture diagram showing a subsystem breakout of the
system, if applicable. The high-level system architecture or subsystem diagrams should, if
applicable, show interfaces to external systems. Supply a high-level context diagram for the
system and subsystems, if applicable. Refer to the requirements trace ability matrix (RTM)
in the Functional Requirements Document (FRD), to identify the allocation of the functional
requirements into this design document.
This section describes any constraints in the system design (reference any trade-off
analyses conducted such, as resource use versus productivity, or conflicts with other systems)
and includes any assumptions made by the project team in developing the system design.
The organization code and title of the key points of contact (and alternates if
appropriate) for the information system development effort. These points of contact should
include the Project Manager, System Proponent, User Organization, Quality Assurance
(QA) Manager, Security Manager, and Configuration Manager, as appropriate.
6
4.1 System Architecture
4.2 Modules
Data Extraction
KNN Model
Results Evaluation
7
Data Extraction:
Importing the libraries, and loading image using OpenCv creating the method in read()
which reads or loads image from the specified path, RGB values also present these are stored
in a numpy array, at last is converted into .csv file.
Extract the labels column from the first column of dataset, convert the labels into
categorical values. Now import the classifiers of knn model from the sciket Learn(sk learn)
module and create the model and calculate distance using Euclidean distance method and see
how neighbors are responded and classify, compile the model which provides accuracy of 94%
Results Evaluation:
Test the model, provide the input image of and evaluate the results of the RGB values.
UML is not a programming vernacular yet rather instruments can be utilized to make
code in different tongues utilizing UML graphs. UML has an incite relationship with question
composed examination and outline. UML expect a fundamental part in portraying trade
viewpoints of a structure.
The use case graph is for demonstrating the direct of the structure. This chart contains the
course of action of use cases, performing pros and their relationship. This chart might be
utilized to address the static perspective of the structure.
8
Fig: 3.3.1 Use Case Diagram
In the above diagram, the user import the data and do data extraction, the actor python
libraries install and import required libraries, which are useful for extracting features by user,
next the user divide the data into train and test and both user and system trains the model, then
system fits the data to model test the model and finally evaluate the result.
9
4.3.2 Class Diagram:
The class graph is the most normally pulled in layout UML. It addresses the static course of
action perspective of the structure. It solidifies the strategy of classes, interfaces, joint
attempts and theiraffiliations.
In the above class diagram, the relationship that is the dependence between each one of the
classes is sketched out. Additionally, even the operations performed in each and every class is
similarly appeared.
10
4.3.3 Sequence Diagram:
This is a cooperation design which tends to the time requesting of messages. It includes set of
parts and the messages sent and gotten by the instance of parts. This chart is utilized to
address the dynamic perspective of the structure.
An Activity in the activity diagram is also known as Activity state. It is used to represent the
invocation of operation, a step in an entire business process. Swimlane is a way in which the
performed activities can be grouped by the same actor on an Activity diagram.
Swimlanes are used to show which activities are performed by which organisation in the
activity diagram. The lanes are boundaries are drawn and the activities of a particular
organisation are drawn in the same lane as that of the organisation. Swimlanes have to be
ordered in a Logical Manner. It is suggested to have less than five swimlanes in an activity
diagram. Swimlanes are good in that they combine the activity diagram’s depiction of logic
with the interaction diagram’s depiction of responsibility.
Fig:4.3.4Activity Diagram
12
5.SYSTEM IMPLMENTATION
5.1 Color_Detection.py
import cv2
import pandas as pd
img_path = 'colorpic.jpg'
img = cv2.imread(img_path)
# declaring global variables (are used later on)
clicked = False
r = g = b = x_pos = y_pos = 0
# Reading csv file with pandas and giving names to each column
index = ["color", "color_name", "hex", "R", "G", "B"]
csv = pd.read_csv('colors.csv', names=index, header=None)
# function to calculate minimum distance from all colors and get the most
matching color
def get_color_name(R, G, B):
minimum = 10000
for i in range(len(csv)):
d = abs(R - int(csv.loc[i, "R"])) + abs(G - int(csv.loc[i, "G"])) +
abs(B - int(csv.loc[i, "B"]))
if d <= minimum:
minimum = d
cname = csv.loc[i, "color_name"]
return cname
# function to get x,y coordinates of mouse double click
def draw_function(event, x, y, flags, param):
if event == cv2.EVENT_LBUTTONDBLCLK:
global b, g, r, x_pos, y_pos, clicked
clicked = True
x_pos = x
y_pos = y
b, g, r = img[y, x]
b = int(b)
g = int(g)
r = int(r)
cv2.namedWindow('image')
cv2.setMouseCallback('image', draw_function)
while True:
cv2.imshow("image", img)
if clicked:
# cv2.rectangle(image, start point, endpoint, color, thickness)-1
fills entire rectangle
cv2.rectangle(img, (20, 20), (750, 60), (b, g, r), -1)
# Creating text string to display( Color name and RGB values )
text = get_color_name(r, g, b) + ' R=' + str(r) + ' G=' + str(g) + '
B=' + str(b)
# cv2.putText(img,text,start,font(0-
7),fontScale,color,thickness,lineType )
cv2.putText(img, text, (50, 50), 2, 0.8, (255, 255, 255), 2,
cv2.LINE_AA)
# For very light colours we will display text in black colour
if r + g + b >= 600:
cv2.putText(img, text, (50, 50), 2, 0.8, (0, 0, 0), 2,
cv2.LINE_AA)
clicked = False
# Break the loop when user hits 'esc' key
if cv2.waitKey(20) & 0xFF == 27:
break
cv2.destroyAllWindows()
13
5.1.2 Colors.csv
28
6. OUTPUT SCREENS
When double clicked on one of the position of blue color we obtained Honalulu blue color
with RGB values=(0,128,200)
29
When one of the postion of pink is double clicked we obtained values for shocking pink as
253,0,205 and pink has high resolution compared to other colors.
30
When one of the position of orange color is clicked we obtained Tea rose color with RGB as
(256,133,129)
31
For pearly Purple which is one ofcolor of Violet color is R=166,G=80,B=160
32
For medium Blue color RGB values are R=0,G=1,B=120 which looks most of the color in
Blue Color and for one of the postion on Green Color gives color name as Islamic Green
with R=1,G=179,B=0
33
When one of the position of violet color is clicked then the Dark Lavender color is
obtained with RGB values as 113,89,159
34
35
For the values that are R+G+B>700 we made them to values in Black color here we can see
And for another position of Green color the color is obtained as Lawn Green with R,G,B
as (119,212,2)
36
7. CONCLUSION AND FUTURE SCOPE
In this project , we learned about colors and how we can extract color RGB values and the
color name of a pixel. This is used in numerous image editing and Uses to search images
based on colours, or looking for a piece of clothing that has certain colour in it. Used for
recognising the Objects. Many applications require real-time image processing like motion
detection and color recognition. Color recognition has many applications including biometric
identification, video surveillance, and object tracking. KNN is widely used in neural network
and machine learning algorithm. This has number of advantages which mainly lead to saving
of time during color detection which will certainly be helpful for many fields which currently
have a schedule to go with the time loss in color detection.
Future Scope:
Hence after completion of this project, it can be released which in turn can be used by many
people for purposes like detection, feature extraction, recognition and calculation of distance
from each point to give accurate rgb values and also for further use in personal or advanced
projects
37
8. REFERENCES
[1] Rabia Bayraktar, Batur Alp Akgul and Kadir Sercan Bayram,"Colour recognition using
colour histogram feature extraction and K-nearest neighbour classifier",[2020].
[2] Shima Ramesh Maniyath,Akshatha K N, Architha L S,Ramachandra Hebbar and Dr. S Rama
Subramoniam, "Soil Color Detection Using Knn Classifier", 2018(IEEE)
[3] P.Sudharshan Duth and M. Mary Deepa, "Color Detection in RGB-modeled images using
MATLAB", 2018(IJET)
[4] Thathupara Subramanyan Kavya, Erdenetuya Tsogtbaatar, Young-Min Jang and Sang-Bock
Cho, "Night- time Vehicle Detection Based On Brake/Tail Light Color", 2018.
[5] Cui Liu and Lianming Wang,"Multi-scale Fuzzy Color Recognition and Segmentation of
Color Image", 2016. IEEE 12th International Conference on Natural Computation, Fuzzy
Systems and Knowledge Discovery (ICNC-FSKD)
[6] Can Eyupoglu, "Implementation of Color Face Recognition Using PCA and k-NN Classifier
", 2016
[7] Alexander Filonenko, Danilo Caceres e n andez, Wahyono, and Kang-Hyun Jo, "Smoke
Detection for Surveillance Cameras Based on color, motion, and on Color, Motion, and Shape",
2016
[8] Ema Rachmawati, Masayu Leylia Khodra and Iping Supriana,"Histogram based Color
Pattern Identification of Multiclass Fruit using feature Selection", 2015 IEEE 5th International
Conference on Electrical Engineering and Informatics
[10] Bhagya R Navada, Santhosh K V, Prajwal S and Harikishan B Shetty "An Image Processing
Technique for Color Detection and Distinguish Patterns with Similar Color: An aid for Color
Blind People", 2014
[11] LI Jing, WANG Junzheng and Mao Jiali, "Color moving object detection method based on
automatic color clustering", 2014
[12] Sidhanta Kumar Kar and Mihir Narayan Mohanty, "Statistical approach for color image
detection", 2013.
[13] Kataria and Singh, "A review of dataclassification Using K-nearest neighbour algorithm.
International Journal of Emerging Technology and Advanced” [2013]
38
[14] Dashti, "Efficient computation of K-nearest neighbor graphs for large high-dimensional data
sets on GPU clusters", 2013.
[15] J.Prabin Jose, P.Poornima and Kukkapalli Manoj Kumar, "A Novel Method for Color Face
Recognition Using KNN Classifier", 2012.
39