AL-2020/coder/image.py

65 lines
1.4 KiB
Python
Raw Normal View History

2020-05-20 07:32:13 +02:00
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.metrics import accuracy_score
from sklearn.neural_network import MLPClassifier
2020-05-20 07:32:13 +02:00
import cv2
# training
# recznie napisane cyfry
digits = datasets.load_digits()
2020-05-20 07:32:13 +02:00
y = digits.target
x = digits.images.reshape((len(digits.images), -1))
2020-05-20 12:57:31 +02:00
#ogarnac zbior, zwiekszyc warstwy
2020-05-20 07:32:13 +02:00
x_train = x[:1000000]
y_train = y[:1000000]
2020-05-20 12:57:31 +02:00
x_test = x[1000000:]
y_test = y[1000000:]
2020-05-20 07:32:13 +02:00
mlp = MLPClassifier(hidden_layer_sizes=(15,), activation='logistic', alpha=1e-4,
solver='sgd', tol=1e-4, random_state=1,
learning_rate_init=.1, verbose=True)
2020-05-20 07:32:13 +02:00
mlp.fit(x_train, y_train)
predictions = mlp.predict(x_test)
print(accuracy_score(y_test, predictions))
# image
img = cv2.cvtColor(cv2.imread('test3.png'), cv2.COLOR_BGR2GRAY)
2020-05-20 11:45:55 +02:00
img = cv2.blur(img, (9, 9)) # poprawia jakosc
img = cv2.resize(img, (8, 8), interpolation=cv2.INTER_AREA)
print(type(img))
print(img.shape)
print(img)
plt.imshow(img ,cmap='binary')
plt.show()
data = []
rows, cols = img.shape
for i in range(rows):
for j in range(cols):
k = img[i, j]
2020-05-20 11:45:55 +02:00
if k > 225:
k = 0 # brak czarnego
else:
k = 1
data.append(k)
data = np.asarray(data, dtype=np.float32)
print(data)
predictions = mlp.predict([data])
print("Liczba to:", predictions[0])
2020-05-20 07:36:18 +02:00