本文整理汇总了Python中skimage.feature.local_binary_pattern函数的典型用法代码示例。如果您正苦于以下问题:Python local_binary_pattern函数的具体用法?Python local_binary_pattern怎么用?Python local_binary_pattern使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了local_binary_pattern函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: logistic_lbp_diff
def logistic_lbp_diff(image1, image2, gamma=1e-3, points=4, radius=2):
"""
Generate local binary patterns (LBP) for each of the images by taking the
average across the color components (assumed to be axis = 0), and then
generating a LBP using a given number of points and comparing at a given
radius away from the center of the image. The distance between the LBPs
is regressed. gamma, points, and radius defaults chosen purely
hearuistically to provide decent dynamic range as seen in
image_handling_tb.ipynb, figure 14.
"""
return logistic_vector_dist(
local_binary_pattern(np.average(image1, axis=0), points, radius),
local_binary_pattern(np.average(image2, axis=0), points, radius),
gamma)
开发者ID:likojack,项目名称:DepthPrediction,代码行数:14,代码来源:image_handling_with_xy.py
示例2: fit
def fit(self, modality, ground_truth=None, cat=None):
"""Compute the LBP images in the three-ortogonal planes.
Parameters
----------
modality : object of type TemporalModality
The modality object of interest.
ground-truth : object of type GTModality or None
The ground-truth of GTModality. If None, the whole data will be
considered.
cat : str or None
String corresponding at the ground-truth of interest. Cannot be
None if ground-truth is not None.
Return
------
self : object
Return self.
"""
super(LBPExtraction, self).fit(modality=modality,
ground_truth=ground_truth,
cat=cat)
# Fix the z axis
lbp_z = np.zeros(modality.data_.shape)
for z in range(modality.data_.shape[2]):
lbp_z[:, :, z] = local_binary_pattern(modality.data_[:, :, z],
self.p, self.r,
method=self.kind)
# Fix the x axis
lbp_x = np.zeros(modality.data_.shape)
for x in range(modality.data_.shape[1]):
lbp_x[:, x, :] = local_binary_pattern(modality.data_[:, x, :],
self.p, self.r,
method=self.kind)
# Fix the y axis
lbp_y = np.zeros(modality.data_.shape)
for y in range(modality.data_.shape[0]):
lbp_y[y, :, :] = local_binary_pattern(modality.data_[y, :, :],
self.p, self.r,
method=self.kind)
self.data_ = np.array((lbp_z, lbp_x, lbp_y))
return self
开发者ID:glemaitre,项目名称:protoclass,代码行数:49,代码来源:lbp_extraction.py
示例3: lbp
def lbp(self, image, label_bboxes, axes, mins, maxs):
rawbbox = image
ccbboxobject, passed, ccbboxexcl = label_bboxes
#FIXME: there is a mess about which of the lbp features are computed (obj, excl or incl)
import skimage.feature as ft
P=8
R=1
lbp_total = np.zeros(passed.shape)
for iz in range(maxs.z - mins.z):
#an lbp image
bboxkey = [slice(None)] * 3
bboxkey[axes.z] = iz
bboxkey = tuple(bboxkey)
lbp_total[bboxkey] = ft.local_binary_pattern(rawbbox[bboxkey], P, R, "uniform")
#extract relevant parts
lbp_incl = lbp_total[passed]
lbp_excl = lbp_total[ccbboxexcl.astype(bool)]
lbp_obj = lbp_total[ccbboxobject.astype(bool)]
lbp_hist_incl, _ = np.histogram(lbp_incl, normed=True, bins=(P + 2), range=(0, P + 2))
lbp_hist_excl, _ = np.histogram(lbp_excl, normed=True, bins=(P + 2), range=(0, P + 2))
lbp_hist_obj, _ = np.histogram(lbp_obj, normed=True, bins=(P + 2), range=(0, P + 2))
result = {}
result["lbp_incl"] = lbp_hist_incl
result["lbp_excl"] = lbp_hist_excl
result["lbp"] = lbp_hist_obj
return result
开发者ID:fblumenthal,项目名称:ilastik,代码行数:28,代码来源:anna_objfeats.py
示例4: predictImg
def predictImg(img):
img = transform.resize(img, (100, 150))
lbp = feature.local_binary_pattern(img, n_points, radius, METHOD)
lbp = lbp.flatten()
k = dt.predict(lbp)
return tags[k[0]]
开发者ID:sudhinsr,项目名称:ATI-ML,代码行数:6,代码来源:ATI_ML.py
示例5: trainSys
def trainSys():
global a
global tags
i = 0
print "Starting training..."
directory = "/home/leroy/Desktop/ATI - Mini/datasets/"
for key, ta in tags.iteritems():
folder = directory + ta + '/'
for file in os.listdir(folder):
file2 = folder + file
img = io.imread(file2, as_grey = True)
img = transform.resize(img, (100, 150))
lbp = feature.local_binary_pattern(img, n_points, radius, METHOD)
lbp = lbp.flatten()
a[i] = lbp
i = i + 1
input_images_tags = numpy.ones(20)
input_images_tags2 = numpy.empty(20)
input_images_tags2.fill(2)
input_images_tags3 = numpy.empty(20)
input_images_tags3.fill(3)
input_images_tags4 = numpy.empty(20)
input_images_tags4.fill(4)
#input_images_tags3 = numpy.concatenate([input_images_tags3, input_images_tags4])
input_images_tags2 = numpy.concatenate([input_images_tags2, input_images_tags3])
input_images_tags = numpy.concatenate([input_images_tags, input_images_tags2])
dt.fit(a, input_images_tags)
print "Training Successfully Completed!"
开发者ID:sudhinsr,项目名称:ATI-ML,代码行数:35,代码来源:ATI_ML.py
示例6: calculateLBP
def calculateLBP(self):
paramList = list()
with open(self.paramTxt) as f:
for line in f:
paramList.append(int(line.strip()))
print(paramList)
for image in self.trainDict.iterkeys():
print(image)
img = cv2.imread(image)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# radius = 3
# noPoints = 8 * radius
radius = paramList[0]
noPoints = paramList[1] * radius
print(radius)
print(noPoints)
lbpImage = local_binary_pattern(imgGray, noPoints, radius, method='uniform')
# Calculate the histogram
x = itemfreq(lbpImage.ravel())
# normalize the histogram
hist = x[:, 1] / sum(x[:, 1])
# hist = cv2.calcHist(lbp, [0], None, [256], [0, 256])
# cv2.normalize(hist,hist)
# hist = hist.flatten()
self.addrImg.append(image)
self.lbpHistogram.append(hist)
self.tagNo.append(self.trainDict.get(image))
joblib.dump((self.addrImg, self.lbpHistogram, self.tagNo), "lbp.pkl", compress=3)
开发者ID:Elegant1016,项目名称:OpenCV,代码行数:32,代码来源:CalculateLBP.py
示例7: LBP
def LBP(self, img, save=False, parms=None, subtract=False):
"""Get the LBP image
(reference: http://goo.gl/aeADZd)
@param img: image array
Keyword arguments:
save -- True to save the image
parms -- [points, radius] (default: None)
subtract -- True to subtract values to pts (default: False)
"""
from skimage.feature import local_binary_pattern
if self.is_rgb(img):
img = self.gray(img)
if parms is None:
pts = int(img.shape[0]*img.shape[1]*0.0003)
radius = min(img.shape[0], img.shape[1])*0.015
else:
pts = parms[0]
radius = parms[1]
lbp = local_binary_pattern(img, pts, radius, method='uniform')
if subtract:
lbp = np.abs(lbp - pts)
if save:
self.pl.plot_matrix(lbp, fname='lbp_cm.png', show_text=False,
show_axis=False, norm=False)
return lbp
开发者ID:tammyyang,项目名称:simdat,代码行数:28,代码来源:image.py
示例8: pca_hash
def pca_hash(fxy,pca):
lbp = local_binary_pattern(fxy,3,24)
#print(len(flattn(lbp)))
#print(np.array([flattn(lbp)]).shape)
res = pca.transform(np.array([flattn(lbp)]))
#print(res.shape)
return res[0]
开发者ID:d-klein,项目名称:image-hash,代码行数:7,代码来源:Lbp.py
示例9: __init__
def __init__(self, clf):
'''
Classifies and scores eyes based
on whether they are open or closed.
INPUTS:
clf - a classifier
the following are defined by the clf:
n_size - a float, the size of the LBP
n_circ_sym - number of the LBP divisions to use
n_splt - how many times to symmetrically
subdivide the image
trim - the number of pixels to trim off the
the borders of the returned LBP image.
scaler - a standard scaler
'''
self.clf = clf
self._n_size = clf.n_size
self._n_circ_sym = clf.n_circ_sym
self._n_split = clf.n_splits
self._trim = clf.trim
self._resize = clf.img_size
self.scaler = clf.scaler
self.f_lbp = lambda x: feature.local_binary_pattern(x,
self._n_circ_sym,
self._n_size).astype(int)
开发者ID:neonopen,项目名称:aquila-python,代码行数:26,代码来源:score_eyes.py
示例10: get_features
def get_features(directory):
features = []
for fn in iglob("%s/*.png" % directory):
image = color.rgb2gray(io.imread(fn))
lbp_image = feature.local_binary_pattern(image, LBP_POINTS, LBP_RADIUS, "uniform")
features.append(get_histogram_feature(lbp_image))
return features
开发者ID:mls-itoc,项目名称:susanoo,代码行数:7,代码来源:get_feature.py
示例11: ExtractLBPFeatures
def ExtractLBPFeatures(img):
# This function extracts LBP features from a given image
radius = 3
n_points = 8 * radius
lbp_feature = local_binary_pattern(image,n_points,radius)
return lbp_feature
开发者ID:jainsameer20,项目名称:LogisticProgression,代码行数:7,代码来源:FaceDetector.py
示例12: retrieve_LBP_feature_histogram
def retrieve_LBP_feature_histogram(image_path):
try:
# Read feature directly from file
image_feature_path = image_path + FEATURE_EXTENSION
if os.path.isfile(image_feature_path):
LBP_feature_histogram = np.genfromtxt(image_feature_path, delimiter=",")
return LBP_feature_histogram
# Define LBP parameters
radius = 5
n_points = 8
bins_num = pow(2, n_points)
LBP_value_range = (0, pow(2, n_points) - 1)
# Retrieve feature
assert os.path.isfile(image_path)
image_content_in_gray = imread(image_path, as_grey=True)
image_content_in_gray = img_as_ubyte(image_content_in_gray)
LBP_feature = local_binary_pattern(image_content_in_gray, n_points, radius)
LBP_feature_histogram, _ = np.histogram(LBP_feature, bins=bins_num, range=LBP_value_range, density=True)
# Save feature to file
assert LBP_feature_histogram is not None
np.savetxt(image_feature_path, LBP_feature_histogram, delimiter=",")
return LBP_feature_histogram
except:
print("Unable to retrieve LBP feature histogram in %s." % (os.path.basename(image_path)))
return None
开发者ID:nixingyang,项目名称:Kaggle-Competitions,代码行数:28,代码来源:solution.py
示例13: lbf
def lbf(infile):
result = []
label = []
ix = 0
for here, i in enumerate(open(infile).readlines()):
ix +=1
imgpath, l = i.split(',')
if os.path.exists(imgpath):
im = cv2.imread(imgpath)
im = cv2.resize(im, (200, 200))
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
radius = 3
no_points = 8 * radius
lbp = local_binary_pattern(im_gray, no_points, radius, method='uniform')
x = itemfreq(lbp.ravel())
hist = x[:, 1]/sum(x[:, 1])
result.append(hist)
if "FE" in l:
label.append(1)
else:
label.append(-1)
print len(result)
print len(label)
开发者ID:smartyining,项目名称:IMFDB,代码行数:26,代码来源:lbf.py
示例14: extract
def extract(self, image):
features = np.array([])
vec = []
if 'raw' in self.features:
vec = image.flatten()
features = np.append(features, vec)
vec = []
if 'textons' in self.features:
import gen_histogram as tx
vec = np.array(tx.histogram(image, self.centers))
features = np.append(features, vec)
vec = []
if 'hog' in self.features:
vec = hog(image, cells_per_block=(3, 3))
vec = np.append(vec, hog(image, cells_per_block=(4, 4)))
vec = np.append(vec, hog(image, cells_per_block=(1, 1)))
vec = np.append(vec, hog(image, cells_per_block=(2, 2)))
features = np.append(features, vec)
vec = []
if 'lbp' in self.features:
vec = local_binary_pattern(image, 24, 3).flatten()
features = np.append(features, vec)
vec = []
if 'daisy' in self.features:
vec = daisy(image).flatten()
features = np.append(features, vec)
return features
开发者ID:DuongHoangThuy,项目名称:iris-recognition-1,代码行数:28,代码来源:features.py
示例15: get_lbp
def get_lbp(img):
# settings for LBP
radius = 4
n_points = 8 * radius
METHOD = 'uniform'
lbp = local_binary_pattern(color.rgb2gray(img), n_points, radius, METHOD)
return lbp
开发者ID:fucusy,项目名称:gait-simple-cnn,代码行数:7,代码来源:lbp.py
示例16: k_means_classifier
def k_means_classifier(image):
n_clusters = 8
# blur and take local maxima
blur_image = gaussian(image, sigma=8)
blur_image = ndi.maximum_filter(blur_image, size=3)
# get texture features
feats = local_binary_pattern(blur_image, P=40, R=5, method="uniform")
feats_r = feats.reshape(-1, 1)
# cluster the texture features
km = k_means(n_clusters=n_clusters, batch_size=500)
clus = km.fit(feats_r)
# copy relevant attributes
labels = clus.labels_
clusters = clus.cluster_centers_
# reshape label arrays
labels = labels.reshape(blur_image.shape[0], blur_image.shape[1])
# segment shadow
img = blur_image.ravel()
shadow_seg = img.copy()
for i in range(0, n_clusters):
# set up array of pixel indices matching cluster
mask = np.nonzero((labels.ravel() == i) == True)[0]
if len(mask) > 0:
thresh = threshold_otsu(img[mask])
shadow_seg[mask] = shadow_seg[mask] < thresh
shadow_seg = shadow_seg.reshape(*image.shape)
return shadow_seg
开发者ID:charlienewey,项目名称:shadow-detection-notebook,代码行数:34,代码来源:shadow.py
示例17: testLBP
def testLBP (format, formatMask, path, output) :
dataset = pd.read_csv(path)
idxCls = dataset['idx']
# cnts = dataset['Cnt']
fnList = dataset['path']
# out = open(output, 'w')
lbps = list(map(lambda x: local_binary_pattern(cv2.bitwise_and(imread(format.format(x)),imread(formatMask.format(x))), lbpP, lbpR, lbpMethod), fnList))
histograms = list(map(lambda x: np.histogram(x, bins=range(int(np.max(lbps)) + 1))[0], lbps))
distances = prw.pairwise_distances(histograms, metric='l1')
np.fill_diagonal(distances, math.inf)
guessedClasses = np.apply_along_axis(lambda x: np.argmin(x), 1, distances)
scores = np.apply_along_axis(lambda x: np.min(x), 1, distances)
correct = list(map(lambda i: idxCls[guessedClasses[i]] == idxCls[i], range(0, np.alen(idxCls))))
# out.write(str(np.average(correct)))
# fpr, tpr, thresholds = roc_curve(correct, scores, pos_label=1)
# pyplot.plot(tpr, fpr)
# pyplot.show()
with open(output + 'lbp_distances.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerows(distances)
with open(output + 'lbp_guessedClasses.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerow(guessedClasses)
with open(output + 'lbp_correct.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerow(correct)
with open(output + 'lbp_real.csv', 'w', newline='') as fp:
a = csv.writer(fp, delimiter=',')
a.writerow(idxCls)
开发者ID:mariaTatarintseva,项目名称:Diploma,代码行数:32,代码来源:LBPSpeedUp.py
示例18: limpa_imagem
def limpa_imagem(img_cinza):
#binariza a imagem em escala de cinza
img_bin_cinza = np.where(img_cinza < np.mean(img_cinza), 0, 255)
# aplica lbp sobre a imagem em escala de cinza
# lbp foi aplicado para evitar perda de informacao em regioes
# proximas as regioes escuras (provaveis celulas)
lbp_img = local_binary_pattern(img_cinza, 24, 3, method='uniform')
# aplica efeito de blurring sobre a imagem resultante do lbp
blur_img = gaussian(lbp_img,sigma=6)
img_bin_blur = np.where(blur_img < np.mean(blur_img), 0, 255)
# junta as duas regiões definidas pela binarizacao da imagem em escala
# de cinza e a binarizacao do blurring
mascara = np.copy(img_bin_cinza)
for (a,b), valor in np.ndenumerate(img_bin_blur):
if valor == 0:
mascara[a][b] = 0
# aplica a mascara obtida sobre a imagem original (em escala de cinza)
# para delimitar melhor as regiões que não fornecerao informacoes (regioes
# totalmente brancas)
img_limpa = np.copy(img_cinza)
for (a,b), valor in np.ndenumerate(mascara):
if valor == 255:
img_limpa[a][b] = 255
return (img_limpa)
开发者ID:willianfatec,项目名称:PatchWiser,代码行数:29,代码来源:binarypattern.py
示例19: train_lbp
def train_lbp():
train_dir = "/home/gast/ImageHashing/face_train/"
suffix = ".png"
size = 200
train = []
for fn in sorted(os.listdir(train_dir)):
if fn.endswith(suffix):
rgb = Image.load(train_dir + fn)
gray = Image.rgb2gray(rgb)
resized = Image.resize(gray,size)
img = Image.gray2real(resized)
lbps = local_binary_pattern(img,3,24)
#print(flatten(lbps))
#print(len(flatten(lbps)))
train.append(flatten(lbps))
#print(lbps)
pca = PCA(n_components=100)
#print(len(train))
#print(len(train[0]))
train_np = np.array(train)
#print(train_np.shape)
pca.fit(train_np)
return pca
开发者ID:d-klein,项目名称:image-hash,代码行数:25,代码来源:pca.py
示例20: lbp_extract
def lbp_extract(self, image):
"""
利用LBP,对给定的图片提取特征向量。使用前必须先初始化特征提取器。
Parameters
----------
image : 二维numpy数组
灰度图的二维numpy数组。
Returns
-------
一维numpy数组
图片的特征向量。
"""
assert self.red, "self.red should be initial!"
height, width = image.shape
w = width // 2
h = height // 3
feature = np.array([])
for i in range(2):
for j in range(3):
cell = image[h*j:h*(j+1), w*i:w*(i+1)]
lbp = local_binary_pattern(cell, 8, 1)
histogram = np.zeros(256)
for pattern in lbp.ravel():
histogram[int(pattern)] += 1
histogram = (histogram - histogram.mean()) / histogram.std()
feature = np.hstack((feature, histogram))
feature = self.red.transform(feature.reshape(1, -1))
return feature.ravel()
开发者ID:HustMLTeam,项目名称:huiyou,代码行数:30,代码来源:basic.py
注:本文中的skimage.feature.local_binary_pattern函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论