Skip to content

Instantly share code, notes, and snippets.

@humpydonkey
Created November 16, 2023 23:30
Show Gist options
  • Save humpydonkey/ad40f07211449fee281420038b815b62 to your computer and use it in GitHub Desktop.
Save humpydonkey/ad40f07211449fee281420038b815b62 to your computer and use it in GitHub Desktop.
Check consistency of four corners of an image
import itertools
import PIL.Image
import numpy as np
def four_corners_similar(image: PIL.Image.Image):
pixel_value_diff_tolerance = 40 # tolerance for pixel value difference, 0-255
discrepancy_threshold = 0.01 # max percentage of pixels that can be different between corners to be considered similar
corner_image_ratio = 0.06
crop_size = int(corner_image_ratio * min(image.size))
# print(crop_size)
w, h = image.size
img_np = np.asarray(image.convert("RGB"), dtype=np.int16)
top_left = img_np[0:crop_size, 0:crop_size]
top_right = img_np[0:crop_size, w - crop_size:w]
bottom_left = img_np[h - crop_size:h, 0:crop_size]
bottom_right = img_np[h - crop_size:h, w - crop_size:w]
corners = [top_left, top_right, bottom_left, bottom_right]
max_diff = 0
for i, j in itertools.product(range(len(corners)), range(len(corners))):
if j <= i:
continue
diff = np.absolute(corners[i] - corners[j])
diff[diff < pixel_value_diff_tolerance] = 0
percentage_diff = np.count_nonzero(diff) / (crop_size**2 * 3)
max_diff = max(max_diff, percentage_diff)
if percentage_diff > discrepancy_threshold:
# print(f"Corners {i} and {j} are not similar. Percentage: {percentage_diff:.3f}")
# display(PIL.Image.fromarray(corners[i].astype(np.uint8)))
# display(PIL.Image.fromarray(corners[j].astype(np.uint8)))
# display(image.resize((256, 256)))
return False, max_diff
return True, max_diff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment