Skip to content

Instantly share code, notes, and snippets.

@oofnivek
Created August 30, 2021 07:22
Show Gist options
  • Save oofnivek/c40eb6877143e71e92f2f4f4b43b75ff to your computer and use it in GitHub Desktop.
Save oofnivek/c40eb6877143e71e92f2f4f4b43b75ff to your computer and use it in GitHub Desktop.
import sys
import numpy as np
from PIL import Image
def verify(haystack_start_y, haystack_start_x, arr_haystack, arr_needle):
y = haystack_start_y
x = haystack_start_x
searched = 0
identical = 0
for b in range(0, len(arr_needle)):
for a in range(0, len(arr_needle[0])):
searched = searched + 1
if list(arr_needle[b][a]) == list(arr_haystack[y+b][x+a]):
identical = identical + 1
return identical/searched
#-------------------------------------------------------
def search_image(png_haystack, png_needle):
arr_haystack = np.array(png_haystack)
arr_needle = np.array(png_needle)
if len(arr_haystack)<len(arr_needle) or len(arr_haystack[0])<len(arr_needle[0]):
return [[-1,-1]]
height = len(arr_needle) #row
width = len(arr_needle[0]) #column
pixel_top_left = arr_needle[0][0]
pixel_bottom_left = arr_needle[height-1][0]
pixel_top_right = arr_needle[0][width-1]
pixel_bottom_right = arr_needle[height-1][width-1]
results1 = []
for y in range(0, len(arr_haystack)):
for x in range(0, len(arr_haystack[0])):
if list(arr_haystack[y][x]) == list(pixel_top_left):
results1.append([y,x])
results2 = []
for n in range(0, len(results1)):
y = results1[n][0]
x = results1[n][1]
if list(arr_haystack[y+height-1][x]) == list(pixel_bottom_left):
results2.append([y,x])
results3 = []
for n in range(0, len(results2)):
y = results2[n][0]
x = results2[n][1]
if list(arr_haystack[y][x+width-1]) == list(pixel_top_right):
results3.append([y,x])
results4 = []
for n in range(0, len(results3)):
y = results3[n][0]
x = results3[n][1]
if list(arr_haystack[y+height-1][x+width-1]) == list(pixel_bottom_right):
results4.append([y,x])
results5 = []
for n in range(0, len(results4)):
y = results4[n][0]
x = results4[n][1]
if verify(y, x, arr_haystack, arr_needle) == 1.0:
results5.append([x,y])
if len(results5) == 0:
return [[-1,-1]]
else:
return results5
#-------------------------------------------------------
png_haystack = Image.open(sys.argv[1])
png_needle = Image.open(sys.argv[2])
print(search_image(png_haystack, png_needle))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment