My code for a LocalBinaryPatern in python is running very slow. I tried optimizing it with tips from online. I'am still getting used to python, and programming in General so any tips are very welcome! Here is the code:
def localbinarypattern(image, radius=2):
h, w = image.shape
if radius == 1:
return 0
else:
abase = math.pi/4
xshift, yshift = [0 for _ in range(8)], [0 for _ in range(8)]
for i in range(8):
xshift[i] = - radius * sin(i*abase)
yshift[i] = radius * cos(i*abase)
feat = [0 for _ in range(255)]
lbp = [0 for _ in range(8)]
base = [1, 2, 4,8, 16, 32, 64, 128]
for y in (range(radius, (h-radius))):
for x in (range(radius, (w-radius))):
lbp = [0 for _ in range(8)]
for i in range(8):
cx = xshift[i]+x
cy = yshift[i]+y
ry = int(cy+0.5)
rx = int(cx + 0.5)
if image[ry][rx] > 0:
lbp[i] = 1
bits = 0
for i in range(8):
bits += int(lbp[i]*base[i])
if bits < 255:
feat[bits] += 1
sum_lbp = 0
for i in range(len(feat)):
sum_lbp += feat[i]
if sum_lbp ==0:
print ("warning: the sum of LBP feature is zero!\n")
else:
for i in range(len(feat)):
feat[i] /= sum_lbp
return feat
feat = [0 for _ in range(255)]
=>feat = [0]*255
\$\endgroup\$sum_lbp = 0 for i in range(len(feat)): sum_lbp += feat[i]
=>sum_lbp = sum(feat)
\$\endgroup\$sin
is frommath
ornumpy
. If you could also add some example in-/output, then answering this question would get a lot easier. \$\endgroup\$