Exemplo n.º 1
0
def haar_feature_fit(pos_dir, neg_dir):
    para = [[]]
    y = []
    classi = ensemble.AdaBoostClassifier(
        tree.DecisionTreeClassifier(max_depth=2),
        algorithm="SAMME.R",
        n_estimators=50,
        learning_rate=1.2)
    for root, director, files in os.walk(pos_dir):
        print(files)
        i = 0
        for file in files:
            i += 1
            if (i > 50):
                break
            print(file)
            image = io.imread(pos_dir + file)
            img_gray = color.rgb2gray(image)
            img_union = transform.resize(img_gray, (190, 100))
            coord, ft = haar_like_feature_coord(100, 60, feature_types[0])
            feature = haar_like_feature(img_union, 0, 0, 100, 60, ft, coord)

            para = np.array([feature])
            #y = np.array(1)
            classi.fit(para, [0])

    for root, director, files in os.walk(neg_dir):
        print(files)
        i = 0
        for file in files:
            i += 1
            if (i > 50):
                break
            print(file)
            image = io.imread(neg_dir + file)

            img_gray = color.rgb2gray(image)
            coord, ft = haar_like_feature_coord(100, 60, feature_types[0])
            feature = haar_like_feature(img_gray, 0, 0, 100, 60, ft, coord)

            para = np.array([feature])
            #y = np.array(0)
            classi.fit(para, [0])

    joblib.dump(classi, "D:/dataset/haarmodel.m")
    image = io.imread(
        "D:/dataset/ccpd_select1/242&422_86&414_80&364_235&372-0_0_16_32_11_32_26.jpg"
    )
    img_gray = color.rgb2gray(image)
    coord, ft = haar_like_feature_coord(100, 60, feature_types[0])
    feature = haar_like_feature(img_gray, 0, 0, 100, 60, ft, coord)

    test = np.array([feature])
    res = classi.predict(test)

    print(res)
Exemplo n.º 2
0
 def haar(img):
     img = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
     img_ii = integral_image(img)
     haar_2x = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-2-x')
     haar_2y = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-2-y')
     haar_3x = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-3-x')
     haar_3y = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-3-y')
     haar_4 = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-4')
     haar = np.concatenate([haar_2x, haar_2y, haar_3x, haar_3y, haar_4])
     return haar
Exemplo n.º 3
0
def test_haar_like_feature_list():
    img = np.ones((5, 5), dtype=np.int8)
    img_ii = integral_image(img)
    feature_type = ['type-2-x', 'type-2-y', 'type-3-x', 'type-3-y', 'type-4']
    haar_list = haar_like_feature(img_ii,
                                  0,
                                  0,
                                  5,
                                  5,
                                  feature_type=feature_type)
    haar_all = haar_like_feature(img_ii, 0, 0, 5, 5)
    assert_array_equal(haar_list, haar_all)
Exemplo n.º 4
0
def haar_features(train, test, feature_maps):
    train_harr=[]
    test_harr=[]
    for i in train:
        img_ii=integral_image(i)
        feature=haar_like_feature(img_ii,0,0,20,20,feature_maps)
        train_harr.append(feature)
    for i in test:
        img_ii=integral_image(i)
        feature=haar_like_feature(img_ii,0,0,20,20,feature_maps)
        test_harr.append(feature)
    train_harr=np.array(train_harr)
    test_harr=np.array(test_harr)
    return train_harr, test_harr
def haar_feature_descriptor(img, type, feature_coords=None, feature_type=None):
    integ_img = integral_image(img)
    if type == 0:
        features = haar_like_feature(integ_img, 0, 0, img.shape[1],
                                     img.shape[0], feature_types)
    else:
        features = haar_like_feature(integ_img,
                                     0,
                                     0,
                                     img.shape[1],
                                     img.shape[0],
                                     feature_type=feature_type,
                                     feature_coord=feature_coords)
    #print(len(features))
    return features
Exemplo n.º 6
0
def haar_compute(integral_images, top_left_x, top_left_y, width_, height_,
                 feature_type_):
    """
    Compute Haar-like features with given parameters

    :param integral_images  : list of integral images for feature computation
    :param top_left_x       : top left window corner(row)
    :param top_left_y       : top left window corner(col)
    :param width_           : window width
    :param height_          : window height
    :param feature_type_    : type of Haar-like feature(check scikit-image docs)

    :return: haar_feature_vector: a vector of haar like features for each image
                                    shape: (no_of_images, no_of_features)
                                    -> one row corresponds to one image
    """

    haar_feature_vector = [
        haar_like_feature(int_image=integral_image,
                          r=top_left_x,
                          c=top_left_y,
                          width=width_,
                          height=height_,
                          feature_type=feature_type_)
        for integral_image in integral_images
    ]

    return haar_feature_vector
Exemplo n.º 7
0
def haar_like_features(image):
    """calculates the set of haar-like features 
    
    Calculates the haar-like per channel. It first reshape the image to 64*64*C and
    then calcualtes the ['type-2-x', 'type-2-y'] features.
    For more info please refer to:
    https://scikit-image.org/docs/dev/auto_examples/applications/plot_haar_extraction_selection_classification.html

    Parameters
    ----------
    image : 3D array, shape (M, N, C)
        The input image with multiple channels.

    Returns
    -------
    features :  dict  
        dictionary including haar_1_Ch1, haar_2_Ch1 ...

    """
    # storing the feature values
    features = dict()
    for ch in range(image.shape[2]):
        temp_image = resize(image[:, :, ch].copy(), (64, 64))
        ii = integral_image(temp_image)
        haar_fatures = haar_like_feature(ii, 0, 0, ii.shape[0], ii.shape[1],
                                         ['type-2-x', 'type-2-y'])
        for i in range(len(haar_fatures)):
            features["haar_" + str(i + 1) + "_Ch" +
                     str(ch + 1)] = haar_fatures[i]

    return features
def sliding_window_(image, stepSize, windowSize):
    for y in range(0, image.shape[0]):
        for x in range(0, image.shape[1]):
            window = image[x:x + windowSize, y:y + windowSize]
            cv2.namedWindow('Digito1', cv2.WINDOW_NORMAL)
            cv2.imshow('Digito1', window)
            clone = image.copy()
            cv2.rectangle(image, (x, y), (x + windowSize, y + windowSize),
                          (0, 255, 0), 0)
            cv2.namedWindow('Digito2', cv2.WINDOW_NORMAL)
            cv2.imshow('Digito2', clone)
            cv2.waitKey()
            cv2.destroyAllWindows()
            try_window_feature = integral_image(window)
            features = haar_like_feature(try_window_feature, 0, 0, 5, 5,
                                         feature_types)
            print(features)
            print('sliding window')
            print(len(features))
            features_windows.append(features)
            print(len(features_windows))
            '''windows.append(window)
            print('cantidad de ventanas: ', len(windows))'''

    return features_windows
Exemplo n.º 9
0
def get_haar_features(digits, type='type-2-x'):
    from skimage.feature import haar_like_feature
    X = []
    _, w, h = digits.shape
    for digit in digits:
        X.append(haar_like_feature(digit, 0, 0, w, h, feature_type=type))
    return np.array(X)
Exemplo n.º 10
0
def scikit_feature(img, feature):

    ii = integral_image(img)
    return haar_like_feature(ii,
                             0,
                             0,
                             img.shape[0],
                             img.shape[1],
                             feature_type=feature)
Exemplo n.º 11
0
def extract_feature_image(img, feature_type, feature_coord=None):
    ii = integral_image(img)
    return haar_like_feature(ii,
                             0,
                             0,
                             ii.shape[0],
                             ii.shape[1],
                             feature_type=feature_type,
                             feature_coord=feature_coord)
Exemplo n.º 12
0
def extract_feature_image(img, feature_type, feature_coord=None):
    """Extract the haar feature for the current image"""
    
    # compute integral image
    ii = integral_image(img)
    
    # return list of all haar features in image
    return haar_like_feature(ii, 0, 0, ii.shape[0], ii.shape[1],
                             feature_type=feature_type,
                             feature_coord=feature_coord)
Exemplo n.º 13
0
def process_image(image, args=object):
    if args.DES_TYPE == "HOG":
        fd = hog(image, block_norm='L2', pixels_per_cell=args.PIXELS_PER_CELL)
    elif args.DES_TYPE == "LBP":
        fd = lbp(image, args.LBP_POINTS, args.LBP_RADIUS)
    elif args.DES_TYPE == "HAAR":
        fd = haar_like_feature(integral_image(image), 0, 0, 5, 5, 'type-3-x')
    else:
        raise KeyError("==> The Processing method does not exist!")
    return fd
def extract_feature_image(img, feature_type, feature_coord=None):
    """Extract the haar feature for the current image"""
    ii = integral_image(img)
    return haar_like_feature(ii,
                             0,
                             0,
                             ii.shape[0],
                             ii.shape[1],
                             feature_type=feature_type,
                             feature_coord=feature_coord)
Exemplo n.º 15
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)
Exemplo n.º 16
0
    def _compute_for_roi(self, region_of_interest):
        height, width = region_of_interest.shape[:2]
        desc = haar_like_feature(region_of_interest,
                                 width=width,
                                 height=height,
                                 r=0,
                                 c=0)
        desc = np.reshape(desc, (1, -1))

        return desc
Exemplo n.º 17
0
 def extract_feature_image(self, img, feature_type, feature_coord=None):
     # Extract the haar feature for the current image
     # Integral image is computed for optimization of convolution operation
     ii = integral_image(img)
     return haar_like_feature(ii,
                              0,
                              0,
                              ii.shape[0],
                              ii.shape[1],
                              feature_type=feature_type,
                              feature_coord=feature_coord)
Exemplo n.º 18
0
def test_haar_like_feature(feature_type, shape_feature, expected_feature_value,
                           dtype):
    # test Haar-like feature on a basic one image
    img = np.ones((5, 5), dtype=dtype)
    img_ii = integral_image(img)
    haar_feature = haar_like_feature(img_ii,
                                     0,
                                     0,
                                     5,
                                     5,
                                     feature_type=feature_type)
    assert_allclose(np.sort(np.unique(haar_feature)), expected_feature_value)
Exemplo n.º 19
0
def test_haar_like_feature_precomputed(feature_type):
    img = np.ones((5, 5), dtype=np.int8)
    img_ii = integral_image(img)
    if isinstance(feature_type, list):
        # shuffle the index of the feature to be sure that we are output
        # the features in the same order
        shuffle(feature_type)
        feat_coord, feat_type = zip(
            *
            [haar_like_feature_coord(5, 5, feat_t) for feat_t in feature_type])
        feat_coord = np.concatenate(feat_coord)
        feat_type = np.concatenate(feat_type)
    else:
        feat_coord, feat_type = haar_like_feature_coord(5, 5, feature_type)
    haar_feature_precomputed = haar_like_feature(img_ii,
                                                 0,
                                                 0,
                                                 5,
                                                 5,
                                                 feature_type=feat_type,
                                                 feature_coord=feat_coord)
    haar_feature = haar_like_feature(img_ii, 0, 0, 5, 5, feature_type)
    assert_array_equal(haar_feature_precomputed, haar_feature)
Exemplo n.º 20
0
def test_haar_like_feature_fused_type(dtype, feature_type):
    # check that the input type is kept
    img = np.ones((5, 5), dtype=dtype)
    img_ii = integral_image(img)
    expected_dtype = img_ii.dtype
    # to avoid overflow, unsigned type are converted to signed
    if 'uint' in expected_dtype.name:
        expected_dtype = np.dtype(expected_dtype.name.replace('u', ''))
    haar_feature = haar_like_feature(img_ii,
                                     0,
                                     0,
                                     5,
                                     5,
                                     feature_type=feature_type)
    assert haar_feature.dtype == expected_dtype
Exemplo n.º 21
0
 def process_image(self, image):
     '''
     This function is used to extract features from input image
     according to the config
     :param image: input image
     :return: The features extracted from input image
     '''
     if self.config.DES_TYPE == "HOG":
         fd = hog(image,
                  block_norm='L2',
                  pixels_per_cell=self.config.PIXELS_PER_CELL)
     elif self.config.DES_TYPE == "LBP":
         fd = lbp(image, self.config.LBP_POINTS, self.config.LBP_RADIUS)
     elif self.config.DES_TYPE == "HAAR":
         fd = haar_like_feature(integral_image(image), 0, 0, 5, 5,
                                'type-3-x')
     else:
         raise KeyError("==> The Processing method does not exist!")
     return fd
Exemplo n.º 22
0
def detection(img):
    width = img.shape[0]
    height = img.shape[1]
    print(height)
    ptr_w = 0
    ptr_h = 0
    classi = joblib.load("D:/dataset/haarmodel.m")

    while ptr_h < height:
        while ptr_w < width:
            part_img = img[ptr_w:ptr_w + 60, ptr_h:ptr_h + 100]

            img_gray = color.rgb2gray(part_img)
            io.imshow(img_gray)
            io.show()
            coord, ft = haar_like_feature_coord(100, 60, feature_types[0])
            feature = haar_like_feature(img_gray, 0, 0, 100, 60, ft, coord)
            test = np.array([feature])
            res = classi.predict(test)
            if res == 1:
                print("PL detected")
            else:
                print("NOT detected" + str(ptr_w) + "_" + str(ptr_h))
            if (ptr_w + 90) == width:
                ptr_w = width + 1
            else:
                ptr_w += 70
                if (ptr_w + 70) > width:
                    ptr_w = width - 90
        ptr_w = 0
        if (ptr_h + 100) == height:
            ptr_h = height + 1
        else:
            ptr_h += 100
            if (ptr_h + 100) > height:
                print("end")
                ptr_h = height - 100
Exemplo n.º 23
0
    elif sourcer_params['color_model'] == "hls":
      img = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
    elif sourcer_params['color_model'] == "yuv":
      img = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)
    elif sourcer_params['color_model'] == "ycrcb":
      img = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB)
    elif sourcer_params['color_model'] == "grey":
      img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    else: 
      raise Exception('ERROR:', 'No se puede cambiar de color')
    
    '''hogA_img = img[:, :, 0]
    hogB_img = img[:, :, 1]
    hogC_img = img[:, :, 2]'''
    
    return img#, hogA_img, hogB_img, hogC_img


 

svm = joblib.load('D:\Documents\OPENCV\MODELS\HAAR_SVM_MODEL_0.9501557632398754.pkl')

img = cv2.imread('D:\\Documents\\OPENCV\\TRAINING\\6.jpg')
imgGREY = change_color(img, sourcer_params)
imgX = integral_image(imgGREY)        
features = haar_like_feature(imgX, 0, 0, 40, 40, feature_types)

nbr = svm.predict(np.array([features]))
print(nbr[0])
end = timer()
print("{0:.3f}".format(end - start)+' seconds') # Time in seconds
Exemplo n.º 24
0
def haar_feature(img,feature_type_):
    int_img = integral_image(img)
    return haar_like_feature(int_img, 0, 0, int_img.shape[0],int_img.shape[1],feature_type_)
Exemplo n.º 25
0
def get_adaboost_haar(img,index_,f_type,f_coord):
    int_img = integral_image(np.asarray(img))
    return haar_like_feature(int_img, 0, 0, int_img.shape[0],int_img.shape[1],\
                      f_type[index_:index_+1],f_coord[index_:index_+1])
Exemplo n.º 26
0
        feat_coord = np.delete(feat_coord, i)
        feat_type = np.delete(feat_type, i)
    else:
        i += 1
# one over 4
feat_coord = feat_coord[::4]
feat_type = feat_type[::4]
print('features', feat_coord.shape)

first = True
for image in x_train:
    int_image = transform.integral_image(image)
    features = feature.haar_like_feature(int_image,
                                         0,
                                         0,
                                         28,
                                         28,
                                         feature_type=feat_type,
                                         feature_coord=feat_coord)
    if first:
        ftrain = [features]
    else:
        ftrain = np.append(ftrain, [features], axis=0)
    first = False

# TRAINING

myboosting = ensemble.AdaBoostClassifier(n_estimators=50,
                                         learning_rate=1.0,
                                         algorithm='SAMME.R')
myboosting.fit(ftrain, y_train)
def extract_feature_image(img, feature_type, feature_coord=None):
    """Extract the haar feature for the current image"""
    ii = integral_image(img)
    return haar_like_feature(ii, 0, 0, ii.shape[0], ii.shape[1],
                             feature_type=feature_type,
                             feature_coord=feature_coord)
Exemplo n.º 28
0
from skimage.feature import haar_like_feature_coord
from skimage.feature import draw_haar_like_feature

img = np.ones((6, 6), dtype=np.uint8)
print('IMAGE:')
print(img)

print('IMAGE DIMENSIONS')
print('{} * {}'.format(img.shape[0], img.shape[1]))

img_ii = integral_image(img)
print(img_ii)
coord = (np.array([[(0, 0), (0, 0)], [(0, 1), (0, 1)], [(0, 2), (0, 2)]]))
feature_coord, feature_type = haar_like_feature_coord(width=img.shape[1],
                                                      height=img.shape[0],
                                                      feature_type="type-3-x")
print('COORDINATES OF EACH FEATURE')
print(type(feature_coord))
print(feature_type)
print(len(feature_type))
print('VALUE OF IMAGE AFTER APPLYING THE FEATURES')
feature = haar_like_feature(img_ii,
                            0,
                            0,
                            img.shape[1],
                            img.shape[0],
                            feature_type[0],
                            feature_coord=feature_coord[0])
print(feature)
print(len(feature))
    tr_non_face_labels), len(te_face_data), len(te_non_face_data), len(
        te_face_labels), len(te_non_face_labels)

# In[ ]:

tr_data = np.concatenate((tr_face_data, tr_non_face_data))
te_data = np.concatenate((te_face_data, te_non_face_data))

# # Extracting HAAR Features and HAAR Co-ordinates

# In[ ]:

X_train = np.array([
    haar_like_feature(integral_image(tr_data[i]),
                      width=face_dim[0],
                      height=face_dim[1],
                      r=0,
                      c=0) for i in range(len(tr_data))
])
y_train = np.array([+1] * len(tr_face_data) + [-1] * len(tr_non_face_data))

# In[ ]:

X_test = np.array([
    haar_like_feature(integral_image(te_data[i]),
                      width=face_dim[0],
                      height=face_dim[1],
                      r=0,
                      c=0) for i in range(len(te_data))
])
y_test = np.array([+1] * len(te_face_data) + [-1] * len(te_non_face_data))
Exemplo n.º 30
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)
cv2.imshow('Digito', features)
cv2.waitKey()
cv2.destroyAllWindows()









import numpy as np
from skimage.transform import integral_image
from skimage.feature import haar_like_feature
img = np.ones((5, 5), dtype=np.uint8)
img_ii = integral_image(img)
feature = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-3-x')
feature
array([-1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1,
       -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -1, -2, -3, -1, -2, -3, -1,
       -2, -1, -2, -1, -2, -1, -1, -1])


from skimage.feature import haar_like_feature_coord
feature_coord, feature_type = zip(
    *[haar_like_feature_coord(5, 5, feat_t)
      for feat_t in ('type-2-x', 'type-3-x')])
# only select one feature over two
feature_coord = np.concatenate([x[::2] for x in feature_coord])
feature_type = np.concatenate([x[::2] for x in feature_type])
feature = haar_like_feature(img_ii, 0, 0, 5, 5,
                            feature_type=feature_type,