-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpytorch_lbp.py
111 lines (89 loc) · 2.93 KB
/
pytorch_lbp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# -*- coding: utf-8 -*-
# Akgun, Devrim. "A PyTorch Operations Based Approach for Computing Local Binary Patterns." U. Porto Journal of Engineering 7.4 (2021): 61-69.
import torch
#import os
import torch.nn.functional as F
#import cv2
import numpy as np
#import time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
print("torch.cuda.is_available():",torch.cuda.is_available())
#- Python implementation of LBP transform -------------------------------------
def lbp_python(Im):
sat=len(Im)
sut=len(Im[0])
L=np.zeros((sat,sut))
I=np.zeros((sat+2,sut+2))
I[1:sat+1,1:sut+1]=Im
for i in range(1,sat+1):
for j in range(1,sut+1):
L[i-1,j-1]=\
( I[i-1,j] >= I[i,j] )*1+\
( I[i-1,j+1]>= I[i,j] )*2+\
( I[i,j+1] >= I[i,j] )*4+\
( I[i+1,j+1]>= I[i,j] )*8+\
( I[i+1,j] >= I[i,j] )*16+\
( I[i+1,j-1]>= I[i,j] )*32+\
( I[i,j-1] >= I[i,j] )*64+\
( I[i-1,j-1]>= I[i,j] )*128;
return L
#- PyTorch implementation of LBP transform ------------------------------------
def lbp_torch(x):
#pad image for 3x3 mask size
x = F.pad(input=x, pad = [1, 1, 1, 1], mode='constant')
b=x.shape
M=b[1]
N=b[2]
y=x
#select elements within 3x3 mask
y00=y[:,0:M-2, 0:N-2]
y01=y[:,0:M-2, 1:N-1]
y02=y[:,0:M-2, 2:N ]
#
y10=y[:,1:M-1, 0:N-2]
y11=y[:,1:M-1, 1:N-1]
y12=y[:,1:M-1, 2:N ]
#
y20=y[:,2:M, 0:N-2]
y21=y[:,2:M, 1:N-1]
y22=y[:,2:M, 2:N ]
# Apply comparisons and multiplications
bit=torch.ge(y01,y11)
tmp=torch.mul(bit,torch.tensor(1))
bit=torch.ge(y02,y11)
val=torch.mul(bit,torch.tensor(2))
val=torch.add(val,tmp)
bit=torch.ge(y12,y11)
tmp=torch.mul(bit,torch.tensor(4))
val=torch.add(val,tmp)
bit=torch.ge(y22,y11)
tmp=torch.mul(bit,torch.tensor(8))
val=torch.add(val,tmp)
bit=torch.ge(y21,y11)
tmp=torch.mul(bit,torch.tensor(16))
val=torch.add(val,tmp)
bit=torch.ge(y20,y11)
tmp=torch.mul(bit,torch.tensor(32))
val=torch.add(val,tmp)
bit=torch.ge(y10,y11)
tmp=torch.mul(bit,torch.tensor(64))
val=torch.add(val,tmp)
bit=torch.ge(y00,y11)
tmp=torch.mul(bit,torch.tensor(128))
val=torch.add(val,tmp)
return val
print('Random test numbers:')
imgs=np.random.randint(0,256,(7,7))
print(imgs)
# Compute using pytorch
y1=lbp_torch(torch.from_numpy(imgs.reshape(1,7,7)))
# Compute using python
y2=lbp_python(imgs)
print('Python computation result:')
print(y2.reshape(7,7).astype('uint8'))
print('PyTorch computation result:')
print(y1.numpy().reshape(7,7).astype('uint8'))
print('Error check:')
e=y1.numpy()-y2
print(e)
#******************************************************************************