Commit 06b16eed authored by Rebecca Nihara Ranaweerasinghe 's avatar Rebecca Nihara Ranaweerasinghe

Merge branch 'Nehara' into 'master'

updated

See merge request !12
parents 511d578c 33f2055e
This diff is collapsed.
current,paint,coat
red,red,1
red,orange,1
red,yellow,2
red,green,1
red,blue,1
red,purple,2
red,beige,3
red,offwhite,3
orange,orange,1
orange,red,1
orange,yellow,2
orange,green,1
orange,blue,1
orange,purple,2
orange,beige,3
orange,offwhite,3
yellow,yellow,1
yellow,red,1
yellow,orange,1
yellow,green,1
yellow,blue,1
yellow,purple,1
yellow,beige,2
yellow,offwhite,2
green,green,1
green,red,1
green,orange,2
green,yellow,2
green,blue,1
green,purple,2
green,beige,3
green,offwhite,3
blue,blue,1
blue,red,1
blue,orange,1
blue,yellow,2
blue,green,1
blue,purple,2
blue,beige,3
blue,offwhite,3
purple,purple,1
purple,red,1
purple,orange,2
purple,yellow,2
purple,green,1
purple,blue,1
purple,beige,3
purple,offwhite,3
beige,beige,1
beige,red,1
beige,orange,1
beige,yellow,2
beige,green,1
beige,blue,1
beige,purple,1
beige,offwhite,2
offwhite,offwhite,1
offwhite,red,1
offwhite,orange,1
offwhite,yellow,2
offwhite,green,1
offwhite,blue,1
offwhite,purple,1
offwhite,beige,2
# -*- coding: utf-8 -*-
"""paint_coats.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Z5k0mxozD6NAZ2sHFj2BlvIqZ8GE_COm
"""
# Commented out IPython magic to ensure Python compatibility.
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
import pandas as pd
#to save model file
import pickle
#to load model file
#from keras.models import load_model
#define file paths
csv_path = "D:\PaintVisualizer\Python\Color Coats Calculator\paint1.csv"
input_captured_color_file_path = r'D:\PaintVisualizer\Python\Color Coats Calculator\Inputs\Current_color.txt'
input_picked_color_file_path = r'D:\PaintVisualizer\Python\Color Coats Calculator\Inputs\Pick_color.txt'
color_coat_output_file_path = r'D:\PaintVisualizer\Python\Color Coats Calculator\Outputs\results.txt'
#load tarined model
#modelDir=r'E:\My Project\Paint Visualizer\Python\Color Coats Calculator\Trained Model\finalized_model.h5'
#modelTrained=load_model(modelDir)
df = pd.read_csv(csv_path)
df.head()
#read captured and picked colors from input text files
fileCapturedColor = open(input_captured_color_file_path, "r")
capturedColor = fileCapturedColor.read()
fileCapturedColor.close()
#print(capturedColor)
filePickedColor = open(input_picked_color_file_path, "r")
pickedColor = filePickedColor.read()
filePickedColor.close()
#print(pickedColor)
inputs = df.drop('coat', axis='columns')
target = df['coat']
#print("inputs " + str(inputs))
#print("target " + str(target))
from sklearn.preprocessing import LabelEncoder
le_current = LabelEncoder()
le_paint = LabelEncoder()
inputs['current_n'] =le_current.fit_transform(inputs['current'])
inputs['paint_n'] =le_current.fit_transform(inputs['paint'])
#print("inputs['current_n'] " + str(inputs['current_n']))
#print("inputs['paint_n'] " + str(inputs['paint_n']))
inputs.head()
inputs_n = inputs.drop(['current','paint'],axis = 'columns')
#length = len(inputs_n)
#print(inputs_n)
#print(inputs_n.iloc[0]['current_n'])
#print(inputs_n.iloc[7]['paint_n'])
#assign label index for main 8 colors
red = inputs_n.iloc[7]['current_n']
orange = inputs_n.iloc[15]['current_n']
yellow = inputs_n.iloc[23]['current_n']
green = inputs_n.iloc[31]['current_n']
blue = inputs_n.iloc[39]['current_n']
purple = inputs_n.iloc[47]['current_n']
beige = inputs_n.iloc[55]['current_n']
offwhite = inputs_n.iloc[63]['current_n']
def getColorIndex(color):
colorCode = 8
if(color == "red"):
colorCode = red
elif(color == "orange"):
colorCode = orange
elif(color == "yellow"):
colorCode = yellow
elif(color == "green"):
colorCode = green
elif(color == "blue"):
colorCode = blue
elif(color == "purple"):
colorCode = purple
elif(color == "beige"):
colorCode = beige
elif(color == "offwhite"):
colorCode = offwhite
else:
colorCode = 8
return colorCode
capturedColorIndex = getColorIndex(capturedColor)
pickedColorIndex = getColorIndex(pickedColor)
from sklearn import tree
model = tree.DecisionTreeClassifier()
model.fit(inputs_n,target)
#save model
#filename = 'finalized_model.sav'
#filename = 'finalized_model.h5'
#pickle.dump(model, open(filename, 'wb'))
#model.score(inputs_n,target)
print(model.score(inputs_n,target))
#model.predict([[27,27]])
#print(model.predict([[6,7]]))
colorCoats = model.predict([[capturedColorIndex,pickedColorIndex]])
fileColorCoat = open(color_coat_output_file_path, "w+")
fileColorCoat.write(str(colorCoats))
fileColorCoat.close()
print(colorCoats)
#from sklearn.model_selection import train_test_split
#x_train, x_test, y_train, y_test = train_test_split(inputs_n,target,test_size=0.2, random_state = 2656)
#len(x_train)
#len(x_test)
#from sklearn import tree
#model = tree.DecisionTreeClassifier()
#model.fit(x_train,y_train)
#model.score(x_test,y_test)
import numpy as np
import pandas as pd
import cv2
img_path = r'D:\PaintVisualizer\Python\Color Identify\Images\test.jpg'
#img_path = "E:\My Project\Paint Visualizer\Color Identify\Images\color_image2.jpg"
#img_path = "E:\My Project\Paint Visualizer\Color Identify\Images\color_image3.jpg"
#img_path = r'E:\My Project\Paint Visualizer\Color Identify\Images\colorpic.jpg'
#img_path = "E:\My Project\Paint Visualizer\Color Identify\Images\ic_logo.png"
#img_path = 'E:\My Project\Paint Visualizer\Color Identify\Images\test.jpg'
csv_path = "D:\PaintVisualizer\Python\Color Identify\Colors\colors.csv"
color_output_file_path = "D:\PaintVisualizer\Python\Color Identify\Outputs\Result_color.txt"
img = cv2.imread(img_path)
index = ["color", "color_name", "hex", "R", "G", "B"]
csv = pd.read_csv(csv_path, names=index, header=None)
clicked = True
r = g = b = xpos = ypos = 0
def recognize_color(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
#b,g,r = img[0,0]
#b = int(b)
#g = int(g)
#r = int(r)
cv2.namedWindow('Color Recognition App')
#print(cv2.getWindowImageRect(cv2.imshow("Color Recognition App",img)))
while(1):
cv2.imshow("Color Recognition App",img)
if (clicked):
scale = str(cv2.getWindowImageRect("Color Recognition App"))
scale2 = scale.replace("(","")
scale3 = scale2.replace(")","")
slitScale = scale3.split(",")
xpos = int(int(slitScale[2].strip())/2)
ypos = int(int(slitScale[3].strip())/2)
#print(scale)
#print(xpos)
#print(ypos)
b,g,r = img[ypos,xpos]
b = int(b)
g = int(g)
r = int(r)
#cv2.rectangle(image, startpoint, 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 = recognize_color(r,g,b) + ' R='+ str(r) + ' G='+ str(g) + ' B='+ str(b)
#text_write = str(r) + ',' + str(g) + ',' + str(b)
#text_write = recognize_color(r,g,b) + '|'+ str(r) + ','+ str(g) + ','+ str(b)
#convert rgb to hex
text_write = '#{:02x}{:02x}{:02x}'.format(r,g,b)
f = open(color_output_file_path, "w+")
f.write(str(text_write))
f.close()
#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
#Break the loop when user hits 'esc' key
#if cv2.waitKey(20) & 0xFF ==27:
#break
cv2.destroyAllWindows()
There are two pythons scipts used. Those file names are 'paint' (inside the color coats folder)
and 'color_detector' (color identify folder).
In the 'paint' python script, it should give the file paths which is typed under the comment
of '#define file paths'
In the 'color_detector' pyhton script, change the file paths according to the locations of the files.
\ No newline at end of file
Wall paint
implement on camera
<?php
class ColorFound
{
public $baseColors =
[
'ff0000' => 'red',
'ff7f00' => 'orange',
'ffff00' => 'yellow',
'00ff00' => 'green',
'0000ff' => 'blue',
'9400d3' => 'purple',
'f5f5dc' => 'beige',
'ffffff' => 'offwhite'
];
function __construct($baseColors = false)
{
if ($baseColors && is_array($baseColors))
{
$this->baseColors = $baseColors;
}
}
/**
* Convert A HEX Code to an array of RGB values
* @param string $color Hex Code of Color with or without "#"
* @return array|boolean Array of RGB values
*/
public function hex2RGB($color)
{
if ($color != "")
{
$color = ltrim($color, '#');
list($r,$g,$b) = array_map('hexdec',str_split($color,2));
return array
(
'r' => $r,
'g' => $g,
'b'=>$b
);
}
return false;
}
/**
* Calculate distance between the 2 colors
*
* @param array $color1 RGB values of Color 1
* @param array $color RGB values of Color 2
* @return int Distance of the 2 RGB values
*/
public function dist2Colors($color1, $color2)
{
if (is_array($color1) && is_array($color2))
{
$delta_r = $color1['r'] - $color2['r'];
$delta_g = $color1['g'] - $color2['g'];
$delta_b = $color1['b'] - $color2['b'];
return $delta_r * $delta_r + $delta_g * $delta_g + $delta_b * $delta_b;
}
else
{
return false;
}
}
/**
* Get the color name from the pre-defined base colors
*
* @param string $color1 Hex Code of Color 1
* @param array $baseColors Base Colors to check from
* @return array|string Color name or False
*/
public function getName($color, $baseColors = false)
{
$dist_arr = [];
$nearest = false;
if ($baseColors && is_array($baseColors))
{
$this->baseColors = $baseColors;
}
foreach ($this->baseColors as $k => $v)
{
$dist = $this->dist2Colors($this->hex2RGB($color), $this->hex2RGB($k));
if ($nearest === false)
{
$nearest = $dist;
}
else
{
if ($nearest > $dist)
{
$nearest = $dist;
}
}
$dist_arr[$dist] = $v;
}
if (isset($dist_arr[$nearest]))
{
return $dist_arr[$nearest];
}
else
{
return false;
}
}
}
?>
\ No newline at end of file
<?php
//ini_set('display_errors',1);
//error_reporting(E_ALL);
require_once('ColorFound.php');
$colorFound = new ColorFound;
$data = array();
$imageData = "";
$pickedColorHEX = "";
$imageName = "";
$capturedImageColorHEX = "";
$savedImagePath = "D:/PaintVisualizer/Python/Color Identify/Images/";
$pythonScriptPathForColorPick = "D:/PaintVisualizer/Python/Color Identify/color_detector.py";
$pythonScriptPathForColorCoats = "D:/PaintVisualizer/Python/Color Coats Calculator/paint.py";
$capturedColorHEXOutputFilePath = "D:/PaintVisualizer/Python/Color Identify/Outputs/Result_color.txt";
$inputCapturedColorPath = "D:/PaintVisualizer/Python/Color Coats Calculator/Inputs/Current_color.txt";
$inputPickedColorPath = "D:/PaintVisualizer/Python/Color Coats Calculator/Inputs/Pick_color.txt";
$colorCoatOutputPath = "D:/PaintVisualizer/Python/Color Coats Calculator/Outputs/results.txt";
if(isset($_POST['image_data']) && isset($_POST['pick_color_hex']))
{
$imageData = $_POST['image_data'];
$pickedColorHEX = $_POST['pick_color_hex'];
//write picked color hex value
$pickColorFile = fopen($inputPickedColorPath, "w");
fwrite($pickColorFile, $colorFound->getName($pickedColorHEX));
fclose($pickColorFile);
$imageName = "test";//$_POST['image_name'];
$ImagePathPC = $savedImagePath . $imageName . ".jpg";
//save image to pc folder
file_put_contents($ImagePathPC, base64_decode($imageData));
sleep(4);
//run color idendify python script
$command = escapeshellcmd($pythonScriptPathForColorPick);
$output = shell_exec($command);
sleep(4);
//read captured image color output
$resultColor = fopen($capturedColorHEXOutputFilePath, "r");
$capturedImageColorHEX = fread($resultColor, filesize($capturedColorHEXOutputFilePath));
fclose($resultColor);
//write captured image color hex value
$captureColorFile = fopen($inputCapturedColorPath, "w");
fwrite($captureColorFile, $colorFound->getName($capturedImageColorHEX));
fclose($captureColorFile);
//run color coat python script
$commandCoat = escapeshellcmd($pythonScriptPathForColorCoats);
$outputCoat = shell_exec($commandCoat);
sleep(6);
//read color coats as final output
$resultColorCoats = fopen($colorCoatOutputPath, "r");
$colorCoats = fread($resultColorCoats, filesize($colorCoatOutputPath));
fclose($resultColorCoats);
$data['respond'] = "OK";
$data['result_color_coats'] = $colorCoats;
}
else
{
$data['respond'] = "data not set";
}
header('Content-Type: application/json');
echo json_encode($data);
?>
\ No newline at end of file
<?php
require_once('ColorFound.php');
$colorFound = new ColorFound;
echo $colorFound->getName("#3385ff");
?>
\ No newline at end of file
Here having the php scripts to call the APIs
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment