Exemplo n.º 1
0
def representar_con_textones(cubo, N, C, textons, fb):
    assert len(cubo.shape) == 4
    cubo = cubo.reshape((N, cubo.shape[2], cubo.shape[3]))
    for i in range(cubo.shape[0]):
        cubo[i,:,:] = assignTextons(fbRun(fb,cubo[i,:,:]),textons.transpose())
    cubo = cubo.reshape(cubo.shape[0], cubo.shape[1]*cubo.shape[2])
    return cubo
Exemplo n.º 2
0
    import numpy as np
    map_to_bins = np.digitize(X, bins)
    r = np.zeros(bins.shape)
    for i in map_to_bins:
        r[i - 1] += 1
    return np.array(r)


# AssignTextons
from assignTextons import assignTextons
from fbRun import fbRun

mapTrain = []
#Calculate texton representation with current texton dictionary
for img in Train:
    mymap = assignTextons(fbRun(fb, img), Dict.transpose())
    mapTrain.append(mymap)
print('Train Images textones assign')

histTrain = []
for map in mapTrain:
    histTrain.append(histc(map.flatten(), np.arange(300)))
print('Train Images histograms created')

mapTest = []
for img in Test:
    mymap = assignTextons(fbRun(fb, img), Dict.transpose())
    mapTest.append(mymap)
print('Test Images textones assign')

histTest = []
Exemplo n.º 3
0
from assignTextons import assignTextons

def histc(X, bins):
    import numpy as np
    map_to_bins = np.digitize(X,bins)
    r = np.zeros(bins.shape)
    for i in map_to_bins:
        r[i-1] += 1
    return np.array(r)
size=np.shape(textons)
k=size[0]
hists_test=np.zeros((len(test_images),k))
tmap_test=np.zeros((len(test_images),32,32))
for d in l
  for a in list_test:    
      tmap_test[a]=assignTextons(fbRun(fb,color.rgb2gray(test_images[d,:,:,:])),textons.transpose())
      hists_test[a]=np.linalg.norm(histc(tmap_test[d].flatten(), np.arange(k))/tmap_test[d].size) #Normalize histograms
    
Prediccion=model.predict(hists_test)
for i in list_test:
    Prediccion[i]=round(Prediccion[i])
Prediccion=Prediccion.astype(int)

c=confusion_matrix(test_labels, Prediccion)
c=c / c.astype(np.float).sum(axis=1) #Normalize matrix

d=0
for i in range(len(c)):
    d=d+c[i,i]
ACA=d/(len(c))
print('ACA test:',ACA)
Exemplo n.º 4
0
fb = fbCreate(support=2, startSigma=0.6)
k = 16 * 32

from assignTextons import assignTextons
from fbRun import fbRun
import matplotlib.pyplot as plt
import random

plt.figure()
for i in range(1, 8, 2):

    rand = random.randint(0, 10000)
    im = images_test[rand, :, :]
    lab = labels_test[rand]

    txtmap = assignTextons(fbRun(fb, im), textons.transpose())
    hist = []
    hist.append(histc(np.array(txtmap).flatten(), np.arange(k)) / (32**2))
    prediction = RF.predict(np.array(hist))

    if lab == 0:
        labe = "airplane"
    elif lab == 1:
        labe = "automobile"
    elif lab == 2:
        labe = "bird"
    elif lab == 3:
        labe = "cat"
    elif lab == 4:
        labe = "deer"
    elif lab == 5:
Exemplo n.º 5
0
fb = fbCreate(support=2, startSigma=0.6)

k = 16 * 32

from fbRun import fbRun
num = 200
sample = np.hstack(images_train[0:num, :, :])
filterResponses = fbRun(fb, sample)

from computeTextons import computeTextons
map, textons = computeTextons(filterResponses, k)

from assignTextons import assignTextons
texton_maps = []
for im in images_train:
    texton_maps.append(assignTextons(fbRun(fb, im), textons.transpose()))

from sklearn.ensemble import RandomForestClassifier
RF = RandomForestClassifier(n_estimators=350, max_depth=50)

hists = []
for txtmap in texton_maps:
    hists.append(histc(np.array(txtmap).flatten(), np.arange(k)) / (32**2))

RF.fit(np.array(hists), labels_train)

predictions = RF.predict(np.array(hists))

from sklearn.metrics import confusion_matrix, accuracy_score
confusionmat = confusion_matrix(labels_train, predictions)
ACA = accuracy_score(labels_train, predictions)
Exemplo n.º 6
0
acum = DataBalanced[0, :, :]
for i in range(0, len(DataBalanced) - 1):
    acum = np.hstack((acum, DataBalanced[i + 1, :, :]))

filterResponses = fbRun(fb, acum)

from computeTextons import computeTextons

map, textons = computeTextons(filterResponses, k)

from assignTextons import assignTextons
import numpy

tmap = numpy.zeros((len(DataBalanced), 32, 32), dtype=float)
for i in range(0, len(DataBalanced)):
    tmap[i, :, :] = assignTextons(fbRun(fb, DataBalanced[i, :, :]),
                                  textons.transpose())


def histc(X, bins):
    import numpy as np
    map_to_bins = np.digitize(X, bins)
    r = np.zeros(bins.shape)
    for i in map_to_bins:
        r[i - 1] += 1
    return np.array(r)


histogramas = numpy.zeros((len(DataBalanced), k), dtype=float)
for i in range(0, len(tmap)):
    histogramas[i] = histc(tmap[i].flatten(), np.arange(k)) / tmap[i].size
Exemplo n.º 7
0
acum = data_test[0, :, :]
for i in range(0, len(data_test) - 1):
    acum = np.hstack((acum, data_test[i + 1, :, :]))

filterResponses = fbRun(fb, acum)

k = 16 * 10

from computeTextons import computeTextons
map, textons = computeTextons(filterResponses, k)

from assignTextons import assignTextons
import numpy
tmap = numpy.zeros((len(data_test), 32, 32), dtype=float)
for i in range(0, len(data_test)):
    tmap[i, :, :] = assignTextons(fbRun(fb, data_test[i, :, :]),
                                  textons.transpose())


def histc(X, bins):
    import numpy as np
    map_to_bins = np.digitize(X, bins)
    r = np.zeros(bins.shape)
    for i in map_to_bins:
        r[i - 1] += 1
    return np.array(r)


histogramas = numpy.zeros((len(data_test), k), dtype=float)
for i in range(0, len(tmap)):
    histogramas[i] = histc(tmap[i].flatten(), np.arange(k)) / tmap[i].size
Exemplo n.º 8
0
b = sorted(a)

test = []

for n in range(len(b)):
    e = cv2.imread(ruta2 + b[n], 0)
    e = cv2.resize(e, (200, 200))
    test.append(e)

#Calculate texton representation with current texton dictionary
from assignTextons import assignTextons

tmapTrain = []

for n in range(len(train)):
    r = assignTextons(fbRun(fb, train[n]), textons.transpose())
    tmapTrain.append(r)

tmapTest = []

for n in range(len(test)):
    z = assignTextons(fbRun(fb, test[n]), textons.transpose())
    tmapTest.append(z)

final = time()

#Check the euclidean distances between the histograms and convince yourself that the images of the goats are closer because they have similar texture pattern

# --> Can you tell why we need to create a histogram before measuring the distance? <---

Exemplo n.º 9
0
k = 100
n = 10

bestAlgPath = './data/bestAlgo.pkl'

clf = loadPickle(bestAlgPath)

testTextonMapPath = './data/testTextonMap.pkl'
if not fileExists(testTextonMapPath):
    print('Loading test images')
    testImgs = loadPickle('./data/testFilterResponses.pkl')
    print('Loading textons')
    textonPath = './data/mapAndTexton' + str(k) + '.pkl'
    textons = loadPickle(textonPath)['textons']
    print('Asigning textons to test images')
    textonMap = assignTextons(testImgs, textons.transpose())
    toPickle(textonMap, './data/testTextonMap')
else:
    textonMap = loadPickle(testTextonMapPath)

print('Loading test labels')
testLabels = cf.load_cifar10('./cifar-10-batches-py/', mode='test')['labels']

nTest = len(testLabels)
rfPred = []
print('Evaluating on test set')
for t in range(nTest):
    print('\r {:.2f}%'.format((t + 1) * 100 / nTest), end='')
    img = textonMap[:, t * 32:(t + 1) * 32]
    histo = histc(img.flatten(), np.arange(k))
    rfPred.append(clf.predict([histo])[0])
Exemplo n.º 10
0

filterResponses = fbRun(fb,train)
print('Filter responses created')
#Computer textons from filter
mapT, textons = computeTextons(filterResponses, k)
print('Computed textones done')
#Load more images
endt=datetime.now()-sinit
File.write('Time computing time of textons='+str(endt.total_seconds())+'\n')
tmapTrain=[]
histTrain=[]
#Calculate texton representation with current texton dictionary
sinit=datetime.now()
for j in range(0,len(imagesTrain)):
    actTmap=assignTextons(fbRun(fb,imagesTrain[j,:,:]),textons.transpose())
    tmapTrain.append(actTmap)
    histTrain.append(histc(actTmap.flatten(), np.arange(k)))
    print('Image %d'%(j)+' from train already textones assign')
    
tmapTest = []
histTest=[]
for j in range (0,len(imagesTest)):
    actTmap=assignTextons(fbRun(fb,imagesTest[j,:,:]),textons.transpose())
    tmapTest.append(actTmap)
    histTest.append(histc(actTmap.flatten(), np.arange(k)))
    print('Image %d'%(j)+' from test already textones assign')

endt=datetime.now()-sinit
File.write('Time Assign Textons= '+ str(endt.total_seconds())+'\n')
print("clasificando")
Exemplo n.º 11
0
#Compute textons from filter
from computeTextons import computeTextons
[map, textons] = computeTextons(filterResponses, k)
#Load more images
testImgs = []
for idx in range(testImages):
    imAux = color.rgb2gray(data_test[idx, :, :, :])
    testImgs.append(imAux)

#Calculate texton representation with current texton dictionary
from assignTextons import assignTextons

tmapsTrain = []
tmapsTest = []
for idx in range(imageAmount):
    mapTest = assignTextons(fbRun(fb, imgs[idx]), textons.transpose())
    tmapsTrain.append(mapTest)

for idx in range(testImages):
    mapTest = assignTextons(fbRun(fb, testImgs[idx]), textons.transpose())
    tmapsTest.append(mapTest)

trainHists = []
testHists = []
for idx in range(imageAmount):
    auxHist = histc(tmapsTrain[idx].flatten(), np.arange(k))
    trainHists.append(auxHist)

for idx in range(testImages):
    auxHist = histc(tmapsTest[idx].flatten(), np.arange(k))
    testHists.append(auxHist)
Exemplo n.º 12
0
        r[i - 1] += 1
    return np.array(r)


## Assign textons to the train images
X = np.zeros([nIm, k])
c = 0
y = np.zeros([nIm])
la = 0
print('4')

for folder in os.listdir(path):
    for img in os.listdir(os.path.join(path, folder)):
        image = color.rgb2gray(io.imread(os.path.join(path, folder, img)))
        image = cv2.resize(image, (imSize, imSize))
        tmap = assignTextons(fbRun(fb, image), textons.transpose())
        X[c, :] = histc(tmap.flatten(), np.arange(k)) / tmap.size
        y[c] = la
        c = c + 1
    la = la + 1
    print(la)

#Load test images
path = 'test/'
la = 0
c = 0
yTes = np.zeros([250])
xTes = np.zeros([250, k])
for folder in os.listdir(path):
    for img in os.listdir(os.path.join(path, folder)):
        imageTes = color.rgb2gray(io.imread(os.path.join(path, folder, img)))
Exemplo n.º 13
0
    import numpy as np
    map_to_bins = np.digitize(X, bins)
    r = np.zeros(bins.shape)
    for i in map_to_bins:
        r[i - 1] += 1
    return np.array(r)


hists_train = np.zeros((len(train_images), k))
tmap_train = np.zeros((len(train_images), 32, 32))

hists_test = np.zeros((len(test_images), k))
tmap_test = np.zeros((len(test_images), 32, 32))
for i in list_t:
    tmap_train[i] = assignTextons(
        fbRun(fb, color.rgb2gray(train_images[i, :, :, :])),
        textons.transpose())
    hists_train[i] = np.linalg.norm(
        histc(tmap_train[i].flatten(), np.arange(k)) /
        tmap_train[i].size)  #Normalize histograms
for a in list_test:
    tmap_test[a] = assignTextons(
        fbRun(fb, color.rgb2gray(test_images[a, :, :, :])),
        textons.transpose())
    hists_test[a] = np.linalg.norm(
        histc(tmap_test[a].flatten(), np.arange(k)) /
        tmap_test[a].size)  #Normalize histograms
import sklearn
import sklearn.neighbors
from sklearn.neighbors import KNeighborsClassifier
from sklearn import neighbors
Exemplo n.º 14
0
cubo = subsampling(1, 'Test')
cubo = random.sample(cubo, 3)
cubo = np.array(cubo)

cubo = cubo.reshape(cubo.shape[0] * cubo.shape[1], cubo.shape[2],
                    cubo.shape[3], cubo.shape[4])

cuboGris = (color.rgb2gray(cubo) * 255).astype('uint8')

fb = np.load('fb.npy')
textons = np.load('textons.npy')
cuboTextones = np.zeros(cuboGris.shape)

for i in range(cuboTextones.shape[0]):
    cuboTextones[i, :, :] = assignTextons(fbRun(fb, cuboGris[i, :, :]),
                                          textons.transpose())

with open('Knn.pickle', "rb") as input_file:
    knn = pickle.load(input_file)


def histc(X, bins):
    import numpy as np
    map_to_bins = np.digitize(X, bins)
    r = np.zeros(bins.shape)
    for i in map_to_bins:
        r[i - 1] += 1
    return np.array(r)


k = len(textons)