Exemplo n.º 1
0
def sample():
    images = [
        np.zeros((2, 2)),
        np.zeros((2, 2)),
        np.zeros((3, 3)),
        np.zeros((3, 3)),
        np.zeros((2, 2))
    ]

    feature_types = ['type-2-x', 'type-2-y', 'type-3-x', 'type-3-y', 'type-4']
    fig, axs = plt.subplots(3, 2)
    for ax, img, feat_t in zip(np.ravel(axs), images, feature_types):
        coord, _ = haar_like_feature_coord(img.shape[0], img.shape[1], feat_t)
        haar_feature = draw_haar_like_feature(img,
                                              0,
                                              0,
                                              img.shape[0],
                                              img.shape[1],
                                              coord,
                                              max_n_features=1,
                                              random_state=0)
        ax.imshow(haar_feature)
        ax.set_title(feat_t)
        ax.set_xticks([])
        ax.set_yticks([])

    fig.suptitle('The different Haar-like feature descriptors')
    plt.axis('off')
    plt.show()
Exemplo n.º 2
0
def test_haar_like_feature_error():
    img = np.ones((5, 5), dtype=np.float32)
    img_ii = integral_image(img)

    feature_type = 'unknown_type'
    with pytest.raises(ValueError):
        haar_like_feature(img_ii, 0, 0, 5, 5, feature_type=feature_type)
        haar_like_feature_coord(5, 5, feature_type=feature_type)
        draw_haar_like_feature(img, 0, 0, 5, 5, feature_type=feature_type)

    feat_coord, feat_type = haar_like_feature_coord(5, 5, 'type-2-x')
    with pytest.raises(ValueError):
        haar_like_feature(img_ii,
                          0,
                          0,
                          5,
                          5,
                          feature_type=feat_type[:3],
                          feature_coord=feat_coord)
def draw_and_plot_haar_features(img, feature_coords):

    fig, axs = plt.subplots(5, 2)
    for ax, feat_c in zip(np.ravel(axs), feature_coords):
        haar_feature = draw_haar_like_feature(img, 0, 0, img.shape[0],
                                              img.shape[1], [feat_c])
        ax.imshow(haar_feature)
        ax.set_xticks([])
        ax.set_yticks([])
    fig.suptitle('After Boosting')
    plt.axis('off')
    plt.show()
Exemplo n.º 4
0
def print_features(images, idx_sorted, feature_coord):
    idx_sorted = np.argsort(clf.feature_importances_)[::-1]
    fig, axes = plt.subplots(3, 2)
    for idx, ax in enumerate(axes.ravel()):
        image = images[0]
        image = draw_haar_like_feature(image, 0, 0, images.shape[2],
                                       images.shape[1],
                                       [feature_coord[idx_sorted[idx]]])
        ax.imshow(image)
        ax.set_xticks([])
        ax.set_yticks([])

    _ = fig.suptitle('The most important features')
Exemplo n.º 5
0
def test_draw_haar_like_feature(max_n_features, nnz_values):
    img = np.zeros((5, 5), dtype=np.float32)
    coord, _ = haar_like_feature_coord(5, 5, 'type-4')
    image = draw_haar_like_feature(img,
                                   0,
                                   0,
                                   5,
                                   5,
                                   coord,
                                   max_n_features=max_n_features,
                                   random_state=0)
    assert image.shape == (5, 5, 3)
    assert np.count_nonzero(image) == nnz_values
def plot_haar_feature(best_feature_coordinates, name='ada_boost'):
    for idx, feature_coordinate in enumerate(best_feature_coordinates):
        image = cv2.normalize(tr_data[0],
                              None,
                              alpha=0,
                              beta=1,
                              norm_type=cv2.NORM_MINMAX,
                              dtype=cv2.CV_32F)
        image = draw_haar_like_feature(image, 0, 0, face_dim[0], face_dim[1],
                                       [best_feature_coordinates[idx]])
        plt.imsave(
            dir_path + output_path + "{}_best_feature_{}".format(name, idx),
            image)
Exemplo n.º 7
0
    def display(self, significant_features, image):
        """ Plot the most significant haar-like features on top of an image """
        feature_coord, _ = haar_like_feature_coord(width=32, height=64)

        fig, axes = plt.subplots(3, 2)
        for idx, ax in enumerate(axes.ravel()):
            image = draw_haar_like_feature(
                image, 0, 0, 32, 64,
                [feature_coord[significant_features[idx]]])
            ax.imshow(image)
            ax.set_xticks([])
            ax.set_yticks([])

        fig.suptitle('The most important features')
        plt.show()
Exemplo n.º 8
0
def plot(clfss,name):
  i = 0
  for c in clfss:
    i+=1
    pos = c.pos_region
    neg = c.neg_region
    feature = []
    if len(pos) == 1 and len(neg)==1:
      for p in pos:
        feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      for p in neg:
        feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
    elif len(pos) == 2 and len(neg)==1:
      p = pos[0]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = neg[0]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = pos[1]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
    elif len(pos) == 1 and len(neg)==2:
      p = neg[0]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = pos[0]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = neg[1]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
    elif len(pos) == 2 and len(neg)==2:
      p = pos[0]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = neg[0]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = pos[1]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])
      p = neg[1]
      feature.append([(p.y, p.x), (p.y+p.height,p.x+p.width)])

    image = training[0][0]
    image = draw_haar_like_feature(image, 0, 0,19, 19, [feature])
    plt.imshow(image)
    plt.savefig(str(name)+'-'+str(i))
                             max_features=100,
                             n_jobs=-1,
                             random_state=0)
t_start = time()
clf.fit(X_train, y_train)
time_full_train = time() - t_start
auc_full_features = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])

# Sort features in order of importance, plot six most significant
idx_sorted = np.argsort(clf.feature_importances_)[::-1]

fig, axes = plt.subplots(3, 2)
for idx, ax in enumerate(axes.ravel()):
    image = images[0]
    image = draw_haar_like_feature(image, 0, 0, images.shape[2],
                                   images.shape[1],
                                   [feature_coord[idx_sorted[idx]]])
    ax.imshow(image)
    ax.set_xticks([])
    ax.set_yticks([])

fig.suptitle('The most important features')

###############################################################################
# We can select the most important features by checking the cumulative sum of
# the feature importance index; below, we keep features representing 70% of the
# cumulative value which represent only 3% of the total number of features.

cdf_feature_importances = np.cumsum(clf.feature_importances_[idx_sorted])
cdf_feature_importances /= np.max(cdf_feature_importances)
sig_feature_count = np.count_nonzero(cdf_feature_importances < 0.7)
Exemplo n.º 10
0
    np.zeros((2, 2)),
    np.zeros((2, 2)),
    np.zeros((3, 3)),
    np.zeros((3, 3)),
    np.zeros((2, 2))
]

feature_types = ['type-2-x', 'type-2-y', 'type-3-x', 'type-3-y', 'type-4']

fig, axs = plt.subplots(3, 2)
for ax, img, feat_t in zip(np.ravel(axs), images, feature_types):
    coord, _ = haar_like_feature_coord(img.shape[0], img.shape[1], feat_t)
    haar_feature = draw_haar_like_feature(img,
                                          0,
                                          0,
                                          img.shape[0],
                                          img.shape[1],
                                          coord,
                                          max_n_features=1,
                                          random_state=0)
    ax.imshow(haar_feature)
    ax.set_title(feat_t)
    ax.set_xticks([])
    ax.set_yticks([])

fig.suptitle('The different Haar-like feature descriptors')
plt.axis('off')
plt.show()

###############################################################################
# The value of the descriptor is equal to the difference between the sum of the
# intensity values in the green rectangle and the red one.  the red area is
Exemplo n.º 11
0
gray = rgb2gray(img1)    
plt.imshow(gray, cmap=plt.get_cmap('gray'), vmin=0, vmax=1)
plt.show()

plt.imshow(gray)
shape(gray)

?haar_like_feature


extract_feature_image(gray, feature_coord=cset)



image = draw_haar_like_feature(gray, 0, 0,
                               600,
                               600,
                               'type-2-x')


### experimenting with the HAAR like features
feature_types = ['type-2-x', 'type-2-y']
image = images[0]
image=(images[0])
feature_coord, _ = haar_like_feature_coord(12, 24, 'type-2-y')
image = draw_haar_like_feature(image, 0, 0,
                               images.shape[2],
                               images.shape[1],
                               feature_coord,
                               alpha=0.1)
plt.imshow(image)
x_test = np.array(x_test.compute(scheduler='threads'))

i = np.multiply(x_test, a)
output = np.sign(np.sum(i, axis=1))
s = output == y_test
err = 0
for i in range(s.shape[0]):
    if s[i] == True:
        err = err + 1
accuracy = err / images_test.shape[0]
print("accuracy: " + "{:.2%}".format(accuracy))

fig, axes = plt.subplots(5, 2)
for idx, ax in enumerate(axes.ravel()):
    image = images_test[0]
    image = draw_haar_like_feature(image, 0, 0, 16, 16,
                                   [feature_coord[weak_classifiers[idx]]])
    ax.imshow(image)
    ax.set_xticks([])
    ax.set_yticks([])

_ = fig.suptitle('The most important features after boosting')

plt.show()
fpr, tpr, h = metrics.roc_curve(y_test, s)
plt.plot(fpr, tpr)

plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Receiver operating characteristic')
plt.show()
Exemplo n.º 13
0
    return haar_like_feature(ii,
                             0,
                             0,
                             ii.shape[0],
                             ii.shape[1],
                             feature_type=feature_type,
                             feature_coord=feature_coord)


TOTAL = path + path2
print(path)
img = cv2.imread(path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
feat_coord, feat_type = haar_like_feature_coord(2, 2, feature_types)

features = draw_haar_like_feature(img, 2, 3, 39, 39, feat_coord)

#X = delayed(extract_feature_image(img, feature_types)
#for imgs in img)
#print(X)

#x= extract_feature_image(img,'type-4', feature_coord=None)

img2 = integral_image(img)
feature = haar_like_feature(img, 0, 0, 7, 7, feature_types)
print(len(feature))
print(feature)

#img = cv2.imread('D:\Documents\OPENCV\DB_PLATES\carro (1).jpg')

cv2.namedWindow('Digito', cv2.WINDOW_NORMAL)
Exemplo n.º 14
0
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score

from skimage.data import lfw_subset
from skimage.transform import integral_image
from skimage.feature import haar_like_feature
from skimage.feature import haar_like_feature_coord
from skimage.feature import draw_haar_like_feature

#### get the images from example dataset face recognition

images = lfw_subset()
### experimenting with the HAAR like features
feature_types = ['type-2-x', 'type-2-y']
image = images[0]
image = (images[0])
feature_coord, _ = haar_like_feature_coord(12, 24, 'type-2-y')
image = draw_haar_like_feature(image,
                               0,
                               0,
                               images.shape[2],
                               images.shape[1],
                               feature_coord,
                               alpha=0.1)
plt.imshow(image)

#?draw_haar_like_feature

#?haar_like_feature_coord
Exemplo n.º 15
0
# between the sum of intensity values in the green and the red one.

images = [np.zeros((2, 2)), np.zeros((2, 2)),
          np.zeros((3, 3)), np.zeros((3, 3)),
          np.zeros((2, 2))]

feature_types = ['type-2-x', 'type-2-y',
                 'type-3-x', 'type-3-y',
                 'type-4']

fig, axs = plt.subplots(3, 2)
for ax, img, feat_t in zip(np.ravel(axs), images, feature_types):
    coord, _ = haar_like_feature_coord(img.shape[0], img.shape[1], feat_t)
    haar_feature = draw_haar_like_feature(img, 0, 0,
                                          img.shape[0],
                                          img.shape[1],
                                          coord,
                                          max_n_features=1,
                                          random_state=0)
    ax.imshow(haar_feature)
    ax.set_title(feat_t)
    ax.set_xticks([])
    ax.set_yticks([])

fig.suptitle('The different Haar-like feature descriptors')
plt.axis('off')
plt.show()

###############################################################################
# The value of the descriptor is equal to the difference between the sum of the
# intensity values in the green rectangle and the red one.  the red area is
# subtracted to the sum of the pixel intensities of the green In practice, the
# Train a random forest classifier and check performance
clf = RandomForestClassifier(n_estimators=1000, max_depth=None,
                             max_features=100, n_jobs=-1, random_state=0)
t_start = time()
clf.fit(X_train, y_train)
time_full_train = time() - t_start
auc_full_features = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1])

# Sort features in order of importance, plot six most significant
idx_sorted = np.argsort(clf.feature_importances_)[::-1]

fig, axes = plt.subplots(3, 2)
for idx, ax in enumerate(axes.ravel()):
    image = images[0]
    image = draw_haar_like_feature(image, 0, 0,
                                   images.shape[2],
                                   images.shape[1],
                                   [feature_coord[idx_sorted[idx]]])
    ax.imshow(image)
    ax.set_xticks([])
    ax.set_yticks([])

fig.suptitle('The most important features')

###############################################################################
# We can select the most important features by checking the cumulative sum of
# the feature importance index; below, we keep features representing 70% of the
# cumulative value which represent only 3% of the total number of features.

cdf_feature_importances = np.cumsum(clf.feature_importances_[idx_sorted])
cdf_feature_importances /= np.max(cdf_feature_importances)
sig_feature_count = np.count_nonzero(cdf_feature_importances < 0.7)
Created on Mon Jul  8 15:32:47 2019

@author: marijnhazelbag
"""



images = lfw_subset()
### experimenting with the HAAR like features
feature_types = ['type-2-x', 'type-2-y']
image = images[0]
image=(images[0])
feature_coord, _ = haar_like_feature_coord(12, 24, 'type-2-y')
image = draw_haar_like_feature(image, 0, 0,
                               images.shape[2],
                               images.shape[1],
                               feature_coord,
                               alpha=0.1)
plt.imshow(image)

?draw_haar_like_feature

?haar_like_feature_coord