Я пытаюсь реализовать искусственную нейронную сеть, которую я только что обучил, используя этот код.
import numpy as np
import os
training_path = 'Imagenes/train'
training_names = os.listdir(training_path)
image_paths = []
image_classes = []
class_id = 0
def imglist(path):
return [os.path.join(path,f) for f in os.listdir(path)]
for training_name in training_names:
dir = os.path.join(training_path, training_name)
class_path = imglist(dir)
image_paths += class_path
image_classes += [class_id]*len(class_path)
class_id+=1
des_list = []
sift = cv2.xfeatures2d.SIFT_create(100)
for image_path in image_paths:
im = cv2.imread(image_path, 0)
kp, des = sift.detectAndCompute(im, None)
des_list.append((image_path, des))
descriptors = des_list[0][1]
for image_path, descriptor in des_list[1:]:
descriptors = np.vstack((descriptors,descriptor))
descriptors_float = descriptors.astype(float)
from scipy.cluster.vq import kmeans, vq
k = 1000
voc, variance = kmeans(descriptors_float, k, 1)
im_features = np.zeros((len(image_paths), k), "float32")
for i in range(len(image_paths)):
words, distance = vq(des_list[i][1], voc)
for w in words:
im_features[i][w] += 1
nbr_ocurrences = np.sum((im_features > 0) * 1, axis = 0)
idf = np.array(np.log((1.0*len(image_paths)+1) / (1.0*nbr_ocurrences + 1)), 'float32')
from sklearn.preprocessing import StandardScaler
stdSlr = StandardScaler().fit(im_features)
im_features = stdSlr.transform(im_features)
print(np.shape(im_features))
print(np.shape(image_classes))
from sklearn.neural_network import MLPClassifier
clf = MLPClassifier(hidden_layer_sizes=(50,50), max_iter=5000, alpha=0.001,
solver='sgd', verbose=10, random_state=21,tol=0.000000001)
clf.fit(im_features, np.array(image_classes))
from sklearn.externals import joblib
joblib.dump((clf, training_names, stdSlr, k, voc), 'sift.pkl', compress = 3)
Ну, в основном это все, и я пытаюсь реализовать это
import cv2
import numpy as np
from sklearn.externals import joblib
#Cargando parámetros del modelo, clases y desviaciones estandar par normalizar, además de los clusters
clf, class_names, stdSlr, k, voc = joblib.load('sift.pkl')
#Creando SIFT
sift = cv2.xfeatures2d.SIFT_create(100)
#Objeto de video
video = cv2.VideoCapture('video2.mp4')
fgbg = cv2.createBackgroundSubtractorMOG2()
#Ciclo infinito
while True:
#Leer siguiente cuadro
ret, frame = video.read()
#Si hay siguiente cuadro, ret es TRUE de lo contrario es false y se rompe el ciclo
if ret:
porcentaje_escala = 100 # percent of original size
width = int(frame.shape[1] * porcentaje_escala / 100)
height = int(frame.shape[0] * porcentaje_escala / 100)
dim = (width, height)
frame = cv2.resize(frame, dim, interpolation = cv2.INTER_AREA)
#Mostramos el cuadro leído
cv2.imshow('Video Original', frame)
#Convertimos el cuadro a escala de grises para procesarlo
frame_gris = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('Escala de Grises',frame_gris)
#Aplicamos MOG acá
fgmask = fgbg.apply(frame_gris)
#Le hacemos thresholding para eliminar las sombras que el MOG2 deja en gris
ret,fgmask = cv2.threshold(fgmask,250,255,cv2.THRESH_BINARY)
#Aplicamos un pequeño filtro para quitarle ruido a la máscara
fgmask = cv2.GaussianBlur(fgmask,(3,3),0)
#Ahora vamos a dilatar y erosionar un poco la máscara para poder darle un espacio blanco al objeto
#no que detecte la forma sino sólo su espacio
kernel = np.ones((8,8),np.uint8)
fgmask = cv2.dilate(fgmask,kernel,iterations = 1)
fgmask = cv2.erode(fgmask,kernel,iterations = 1)
cv2.imshow('Mascara de MOG2',fgmask)
#Ahora hacemos el AND bit a bit de la máscara y la imagen original
res = cv2.bitwise_and(frame,frame,mask = fgmask)
cv2.imshow('resultado',res)
#Hallamos los componentes que comparten bits blancos en la imagen
contours, hierarchy = cv2.findContours(fgmask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)[-2:]
#Se dibuja cada contorno si su alto y ancho es mayor a 20 pixeles
ROI=[]
for c in contours:
x,y,w,h = cv2.boundingRect(c)
if((w>20) and (h>20)):
ROI.append(frame[x:x+w,y:y+h])
ROI_Valida=[]
for i in range(len(ROI)):
if(np.shape(ROI[i])[0] > 0):
ROI_Valida.append(ROI[i])
for i in range(len(ROI_Valida)):
kp, des = sift.detectAndCompute(ROI_Valida[i], None)
test_features = np.zeros(k, "float32")
from scipy.cluster.vq import vq
words, distance = vq(des, voc)
for w in words:
test_features[w] += 1
Mostramos la imagen final
if cv2.waitKey(1) & 0xFF == ord('q'):
break;
else:
break;
Однако в этой строке реализации
words, distance = vq(des, voc)
Я получаю следующую ошибку
Traceback (последний вызов последним): File "C: \ Universidad \ Trabajo de Grado \ Pruebas \ p2.py ", строка 60, прописью, distance = vq (des, vo c) File" C: \ Python36 \ lib \ site-packages \ scipy \ cluster \ vq.py ", строка 201, в vq obs = _asarray_validated (obs, check_finite = check_finite) Файл" C: \ Python36 \ lib \ site-packages \ scipy_lib_util.py ", строка 249, в _asarray_validated поднять ValueError ( 'массивы объектов не поддерживаются') ValueError: массивы объектов не поддерживаются
Что не имеет для меня смысла, поскольку это та же строка, которая используется при обучении с набором матриц.
I Буду признателен за любую помощь.