# -- Code Cell --
import pandas as pd
train = pd.read_csv('train.csv')
test=pd.read_csv("test.csv")

# -- Code Cell --
test

# -- Code Cell --
from PIL import Image
import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np

# -- Code Cell --
img = cv.imread("./emoji_dataset/test/test_1516.png")
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
img_b = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
grayscale = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
blur = cv.medianBlur(grayscale, 11)
_, threshold = cv.threshold(blur, 254.9, 256, cv.THRESH_BINARY_INV)
n_labels, labels, stats, centroids = cv.connectedComponentsWithStats(threshold, connectivity=4)
count = 0
for i in range(1, n_labels):
    x = stats[i, cv.CC_STAT_LEFT]
    y = stats[i, cv.CC_STAT_TOP]
    w = stats[i, cv.CC_STAT_WIDTH]
    h = stats[i, cv.CC_STAT_HEIGHT]
    area = stats[i, cv.CC_STAT_AREA]

    if 10 <area:
            cv.rectangle(img, (x, y), (x + w, y + h), (255,0,0), 1)
            roi = img_b[y:y+h, x:x+w]
            count+=1

plt.imshow(threshold,cmap='gray')
count

# -- Code Cell --
test

# -- Code Cell --
counts=[]
for i in range(len(test)):
    img = cv.imread(test['Path'][i])
    img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    img_b = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
    grayscale = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
    blur = cv.medianBlur(grayscale, 11)
    _, threshold = cv.threshold(blur, 254.9, 256, cv.THRESH_BINARY_INV)
    n_labels, labels, stats, centroids = cv.connectedComponentsWithStats(threshold, connectivity=4)
    count = 0
    for i in range(1, n_labels):
        x = stats[i, cv.CC_STAT_LEFT]
        y = stats[i, cv.CC_STAT_TOP]
        w = stats[i, cv.CC_STAT_WIDTH]
        h = stats[i, cv.CC_STAT_HEIGHT]
        area = stats[i, cv.CC_STAT_AREA]
        if 10 <area:
                cv.rectangle(img, (x, y), (x + w, y + h), (255,0,0), 1)
                roi = img_b[y:y+h, x:x+w]
                count+=1
    counts.append(count)

# -- Code Cell --
test

# -- Code Cell --
sub = pd.DataFrame({
    'SampleID':test['SampleID'],
    'PredictedLabel':counts
}).to_csv("subs.csv",index=False)

# -- Code Cell --
train

# -- Code Cell --
from skimage.feature import hog

# -- Code Cell --
hogs = []
for i in range(len(train)):
    img = cv.imread(train['Path'][i])
    img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    values = hog(img,channel_axis=2)
    hogs.append(values)

# -- Code Cell --
hogs

# -- Code Cell --
from sklearn.svm import LinearSVC
from sklearn.metrics import f1_score
from sklearn.model_selection import train_test_split
import numpy as np

X = np.array(hogs)
y = train['Label']

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)

model = LinearSVC()
model.fit(X_train, y_train)

pred = model.predict(X_test)
print(f1_score(y_test, pred, average='macro'))

# -- Code Cell --
