Binary search algorithm is one of the common search algorithms. It is suitable for ordered sequence. By dividing the sequence into intervals, it can determine whether the search value exists or not. The advantage is fast speed.
First, assuming that the elements in the table are arranged in ascending order, the keywords recorded in the middle position of the table are compared with the keywords searched. If they are equal, the search is successful; otherwise, the table is divided into two sub-tables by using the middle position record; if the keywords recorded in the middle position are larger than the keywords searched, the former sub-table is searched further; otherwise, the latter sub-table is searched further. Repeat the above process until you find a record that meets the criteria, so that the search is successful, or until the subtable does not exist, then the search is unsuccessful.
Using python recursion to implement its algorithm:
def binary_search(items: list, item: str) -> float:
if not len(items):
return False
if item > items[-1]:
return False
elif item < items[0]:
return False
n = len(items) // 2
if items[n] == item:
return True
else:
if items[n] < item:
return binary_search(items[n:], item)
else:
return binary_search(items[:n], item)
Binary lookup is used in scenes with large amount of data, such as RGB array operations of some pictures, typically in slider verification to determine the best distance.
def match(self, target, template):
img_rgb = cv2.imread(target)
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
template = cv2.imread(template,0)
run = 1
w, h = template.shape[::-1]
print(w, h)
res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
#Use dichotomy to find the exact threshold value
L = 0
R = 1
while run < 20:
run += 1
threshold = (R + L) / 2
print(threshold)
if threshold < 0:
print('Error')
return None
loc = np.where( res >= threshold)
print(len(loc[1]))
if len(loc[1]) > 1:
L += (R - L) / 2
elif len(loc[1]) == 1:
print('Target area starting point x The coordinates are:%d' % loc[1][0])
break
elif len(loc[1]) < 1:
R -= (R - L) / 2
for pt in zip(*loc[::-1]):
cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (7, 279, 151), 2)
cv2.imshow('Dectected', img_rgb)
cv2.waitKey(0)
cv2.destroyAllWindows()
return loc[1][0]