Skip to content

Instantly share code, notes, and snippets.

@cobanov
Created June 13, 2022 17:26
Show Gist options
  • Save cobanov/d385934d2ce94ef651a760c5527c887f to your computer and use it in GitHub Desktop.
Save cobanov/d385934d2ce94ef651a760c5527c887f to your computer and use it in GitHub Desktop.
import numpy as np
import cv2
import pickle
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
def angle_cos(p0, p1, p2):
d1, d2 = (p0-p1).astype('float'), (p2-p1).astype('float')
return abs( np.dot(d1, d2) / np.sqrt( np.dot(d1, d1)*np.dot(d2, d2) ) )
img = cv2.imread('./test2.png')
img = cv2.GaussianBlur(img, (5, 5), 0)
height, width = img.shape[:2]
print(height * width)
squares = []
for gray in cv2.split(img):
for thrs in range(240, 255, 26):
_, threshold = cv2.threshold(gray, thrs, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(
threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cnt_len = cv2.arcLength(cnt, True)
cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)
if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isContourConvex(cnt):
cnt = cnt.reshape(-1, 2)
max_cos = np.max([angle_cos(cnt[i], cnt[(i+1) % 4], cnt[(i+2) % 4]) for i in range(4)])
if max_cos < 0.1:
squares.append(cnt)
print('area: ', cv2.contourArea(cnt), 'mean: ', cv2.minMaxLoc(cnt))
print()
cv2.drawContours(img, squares, -1, (0, 255, 0), 5)
plt.figure(figsize=(8, 8))
plt.imshow(img)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment