-
Notifications
You must be signed in to change notification settings - Fork 6
/
utils.py
96 lines (79 loc) · 2.1 KB
/
utils.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
'''
@ 2022, Copyright AVIS Engine
'''
# Utils for AVISEngine Class
import base64
import cv2
import numpy as np
from PIL import Image
import io
__author__ = "Amirmohammad Zarif"
__email__ = "[email protected]"
def stringToImage(base64_string):
'''
Converts Base64 String to Image
Parameters
----------
base64_string : str
base64 image data to be converted
'''
imgdata = base64.b64decode(base64_string)
return Image.open(io.BytesIO(imgdata))
def BGRtoRGB(image):
'''
Converts PIL Image to an RGB image(technically a numpy array) that's compatible with opencv
'''
return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)
def KMPSearch(pat, txt):
'''
Knuth-Morris-Pratt(KMP) Algorithm : Efficient Search Algorithm to search for a pattern in a string.
Parameters
----------
pat: str
Pattern to be searched for
txt: str
Text to search in
'''
M = len(pat)
N = len(txt)
# create lps[] that will hold the longest prefix suffix
# values for pattern
lps = [0] * M
j = 0 # index for pat[]
# Preprocess the pattern (calculate lps[] array)
computeLPS(pat, M, lps)
i = 0 # Index for txt[]
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
return (i-j)
# Mismatch after j matches
elif i < N and pat[j] != txt[i]:
# Do not match lps[0..lps[j-1]] characters.
if j != 0:
j = lps[j-1]
else:
i += 1
return -1
def computeLPS(pat, M, lps):
'''
Computing the LPS
'''
len = 0 # length of the previous longest prefix suffix
lps[0] # lps[0] is always 0
i = 1
# The loop calculates lps[i] for i = 1 to M-1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
# To search step.
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1