<jupyter_start><jupyter_text>Color Identification  (<NAME>)  PROBLEM STATEMENT:- Interns are expected to create a Tensorflow model for indentification of color. Your code will be givenan image as an input and the code is supposed to catergorize which RGB color it matches to. This code is to be done in Python<jupyter_code># imports

import os
import random
import cv2
import numpy as np
import pandas as pd
from keras.preprocessing import image
import tensorflow as tf
from keras import Sequential
from keras.layers import MaxPooling2D, Conv2D, Flatten, Dense, Dropout
from sklearn.model_selection import train_test_split
from keras.engine.saving import load_model
# setting GPU memory growth for no memory glitches
physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
config = tf.config.experimental.set_memory_growth(physical_devices[0], True)<jupyter_output><empty_output><jupyter_text>Dataset Creator As no pre data set is provided, we will make one ourself<jupyter_code>def create_img(color, add_other=False):
    counter = 0

    for ind in range(25, 245, 10):
        counter += 1
        if color == 'red':
            blank_image[:, 0:width] = (0, 0, ind)

        elif color == 'blue':
            blank_image[:, 0:width] = (ind, 0, 0)

        elif color == 'green':
            blank_image[:, 0:width] = (0, ind, 0)

        path_image = base + color + "_" + str(counter) + '.jpg'
        cv2.imwrite(path_image, blank_image)

        if add_other:
            tot = 0
            for c1 in range(110, 230, 120):
                for c2 in range(110, 230, 120):
                    tot += 1
                    if color == 'red':
                        blank_image[:, 0:width] = (c1, c2, ind)

                    elif color == 'blue':
                        blank_image[:, 0:width] = (ind, c1, c2)

                    elif color == 'green':
                        blank_image[:, 0:width] = (c1, ind, c2)

                    path_image = base + color + "_" + str(counter) + str(tot) + '.jpg'
                    cv2.imwrite(path_image, blank_image)
def get_dataset(base):
    total_images = os.listdir(base)
    total_red = [x for x in total_images if x.split('_')[0] == 'red']
    total_blue = [x for x in total_images if x.split('_')[0] == 'blue']
    total_green = [x for x in total_images if x.split('_')[0] == 'green']

    print('total images:', len(total_images))
    print('total red:', len(total_red))
    print('total blue:', len(total_blue))
    print('total green:', len(total_green))

    return total_images
def create_custom(value):
    # BGR
    blank_image[:, 0:width] = value
    blue, green, red = value
    #    path_image = base + "cc_" + str(value) + '.jpg'
    path_image = base + "cc_(" + str(red) + ", " + str(green) + ", " + str(blue) + ').jpg'
    cv2.imwrite(path_image, blank_image)
height, width = 100, 100
blank_image = np.zeros((height, width, 3), np.uint8)
base = 'dataset\\'
add = True
create_img('blue', add_other=add)
create_img('red', add_other=add)
create_img('green', add_other=add)
get_dataset(base)
len(os.listdir(base))
base = 'input\\'
for i in range(0, 100):
    create_custom((random.choice(range(0, 255)),
                   random.choice(range(0, 255)),
                   random.choice(range(0, 255))))
len(os.listdir(base))
base = 'dataset\\'
total_images = get_dataset(base)
len(total_images)
total_images[:5]
data = list()
for x in total_images:
    ent = [x, x.split('_')[0]]
    data.append(ent)
data[:5]
train = pd.DataFrame(data, columns=['image', 'color'])
train.head()
train = pd.concat([train.drop('color', axis=1),
                   pd.get_dummies(train['color'],
                                  prefix='color',
                                  prefix_sep='_',
                                  dummy_na=False)],
                  axis=1)
train.head()
train_image = []
for i in range(len(total_images)):
    img = image.load_img(base + train['image'][i])
    img = image.img_to_array(img)
    img = img / 255
    train_image.append(img)
len(train_image)<jupyter_output><empty_output><jupyter_text>Load the data into numpy arrays<jupyter_code>X = np.array(train_image)
y = np.array(train[['color_red', 'color_green', 'color_blue']])
y[:5]<jupyter_output><empty_output><jupyter_text>Model Training<jupyter_code>model_path = 'model.h5'
def model_definition(X, y):
    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.2)

    model = Sequential()

    model.add(Conv2D(filters=32, kernel_size=(5, 5), activation='relu', input_shape=(100, 100, 3)))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Conv2D(filters=64, kernel_size=(5, 5), activation="relu"))
    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Flatten())

    model.add(Dense(64, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(3, activation='sigmoid'))

    model.compile(optimizer='SGD', loss='binary_crossentropy', metrics=['accuracy'])

    model.fit(X_train, y_train,
              epochs=90,
              validation_data=(X_test, y_test),
              batch_size=32,
              verbose=0)

    return model
def pred_color(in_img, model):
    in_img = image.load_img(in_img)
    in_img = image.img_to_array(in_img)
    in_img = in_img / 255
    in_img = np.expand_dims(in_img, axis=0)

    y_hat = model.predict(in_img)

    red = y_hat[0][0]
    green = y_hat[0][1]
    blue = y_hat[0][2]

    return get_color((red, green, blue))
def get_color(value):
    color = None
    red, green, blue = value
    if red > blue and red > green:
        color = 'RED'

    elif blue > red and blue > green:
        color = 'BLUE'

    elif green > blue and green > red:
        color = 'GREEN'

    elif green == blue and (green > red or blue > red):
        color = 'GREEN+BLUE'

    elif green == red and (red > blue or green > blue):
        color = 'GREEN+RED'

    elif blue == red and (red > green or blue > green):
        color = 'BLUE+RED'

    elif blue == red and green == blue:

        if blue == 0:
            color = 'BLACK'
        elif blue == 255:
            color = 'WHITE'
        else:
            color = 'RED+GREEN+BLUE'

    return color
model = model_definition(X, y)
model.summary()
model.save(model_path)
print('Model saved to:', model_path)<jupyter_output>Model saved to: model.h5<jupyter_text>Testing<jupyter_code>def model_load():
    model_path = 'model.h5'
    if os.path.exists(model_path):
        model = load_model(model_path)
        print("Loading Model")
    else:
        print("Model not found, please train model first")

    return model
def run_check(image, mod):
    col = pred_color(image, mod)
    return col
model = model_load()
base = 'input\\'

images = os.listdir(base)
total = len(images)
accu = 0

for img_name in images:

    p_col = run_check(base + img_name, model)

    val = tuple(int(x) for x in img_name.split("(")[1].split(")")[0].split(','))
    c = get_color(val)

    print('Image:', img_name)
    print('Predicted:', p_col, '\nActual:', c)

    if c == p_col:
        accu += 1

print("\nTotal: " + str(total))
print("Accurately Predicted: " + str(accu))
import matplotlib.pyplot as plt
%matplotlib inline 
wrng = total - accu
wrng
wrng = total - accu
labels = ['Wrong  Predicted', 'Accurately Predicted']
sizes = [Wrong_pred, accu]

plt.figure(figsize=(8,8))
plt.pie(sizes,
      labels=labels,
      autopct='%1.1f%%',
      wedgeprops={"edgecolor":"k",
                  'linewidth': 1,
                  'antialiased': True});
y_values = [total, accu, wrng]
x_labels = ['Total', 'Accurately Predicted', 'Wrong  Predicted']
plt.title('Accuracy Graphs')
plt.bar(x_labels, y_values);<jupyter_output><empty_output><jupyter_text>We see that the model acheived 96% of accuracy, now lets try to pass a custom image create right into this notebook  Test with a custom image<jupyter_code>height, width = 100, 100
blank_image = np.zeros((height, width, 3), np.uint8)
# red image
img1 = blank_image
img1[:, 0:width] = (200, 10, 10)
img1 = np.array(img1)
plt.imshow(img1)
plt.show()
img1.shape
in_img = img1 / 255
in_img = np.expand_dims(in_img, axis=0)

y_hat = model.predict(in_img)

red = y_hat[0][0]
green = y_hat[0][1]
blue = y_hat[0][2]
get_color((red, green, blue))
# blue image
img2 = blank_image
img2[:, 0:width] = (123, 53, 234)
img2 = np.array(img2)
plt.imshow(img2)
plt.show()
img2.shape
in_img = img2 / 255
in_img = np.expand_dims(in_img, axis=0)

y_hat = model.predict(in_img)

red = y_hat[0][0]
green = y_hat[0][1]
blue = y_hat[0][2]
get_color((red, green, blue))
# green image
img3 = blank_image
img3[:, 0:width] = (233, 255, 214)
img3 = np.array(img3)
plt.imshow(img3)
plt.show()
in_img = img3 / 255
in_img = np.expand_dims(in_img, axis=0)

y_hat = model.predict(in_img)

red = y_hat[0][0]
green = y_hat[0][1]
blue = y_hat[0][2]
get_color((red, green, blue))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14166574002001556, 'fraction_numerical': 0.027132213944178807, 'mean_word_length': 3.158113730929265, 'pattern_counts': {'":': 1, '<': 25, '<?xml version=': 0, '>': 38, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '459296', 'license': 'MIT', 'n_tokens_mistral': 3348, 'n_tokens_neox': 3150, 'n_words': 790, 'path': 'Color-Identifier.ipynb', 'repo_name': 's0umitra/CCLP3-Color-Identifier', 'size': '9013'}