File size: 1,575 Bytes
ffb4efb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from sklearn.datasets import fetch_openml
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
import gradio as gr
import requests
from sklearn import svm, metrics
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
import numpy as np
import cv2

X, y = fetch_openml("mnist_784", version=1, return_X_y=True, as_frame=False)
scaler = StandardScaler()
X = scaler.fit_transform(X)

X_train_img, X_test_img, y_train_img, y_test_img = train_test_split(
    X, y, test_size=0.2, shuffle=True)


# Create a classifier
project_classifier = svm.SVC(kernel='linear',probability=True)
project_classifier.fit(X_train_img, y_train_img)

predicted = project_classifier.predict(X_test_img)

def inference(img):
    labels =["0","1", "2","3", "4","5", "6","7", "8","9"]
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    H,W = 28,28
    img = cv2.resize(img, (H, W))
    ret,img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    img = np.array(img)
    img = img.astype("float32")
    img = img.flatten()
    img = img.reshape(1,H*W)
    img = scaler.transform(img)
    pred = project_classifier.predict_proba(img).flatten()
    dictionary = dict(zip(labels, map(float, pred)))
    return dictionary


nbr_top_classes = 3
gr.Interface(fn=inference,
             inputs=gr.inputs.Image(source="upload"), # source= "upload" "webcam" "canvas"
             outputs=gr.outputs.Label(num_top_classes=nbr_top_classes),
             theme="darkdefault").launch(share=True) #, debug=True Use in Colab