Skip to content

Instantly share code, notes, and snippets.

@gtindo
Last active January 26, 2020 14:49
Show Gist options
  • Save gtindo/563003b397c047f69e91e48484d9c52c to your computer and use it in GitHub Desktop.
Save gtindo/563003b397c047f69e91e48484d9c52c to your computer and use it in GitHub Desktop.
Detect rectangular focus on picture
import numpy as np
import imutils
try:
import cv2
except ImportError:
from cv2 import cv2
def order_points(pts):
rect = np.zeros((4, 2), dtype="float32")
s = pts.sum(axis=1)
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
return rect
def four_point_transform(img, pts):
rect = order_points(pts)
(tl, tr, br, bl) = rect
width_a = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
width_b = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
max_width = max(int(width_a), int(width_b))
height_a = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
height_b = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
max_height = max(int(height_a), int(height_b))
dst = np.array([
[0, 0],
[max_width - 1, 0],
[max_width - 1, max_height - 1],
[0, max_height - 1]], dtype="float32")
matrix = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(img, matrix, (max_width, max_height))
return warped
def main():
img = cv2.imread("cni_2.jpg")
shape = np.shape(img)
ratio = shape[0] / shape[1]
height = 500
width = int(float(height) / ratio)
img = cv2.resize(img, (height, width), interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)
print("STEP 1: Edge Detection")
cv2.imshow("Image", img)
cv2.imshow("Edged", edged)
cnts = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5]
screen_cnt = None
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
print(len(approx))
if len(approx) == 4:
screen_cnt = approx
print("STEP 2: Find contours of card")
if screen_cnt is not None:
cv2.drawContours(img, [screen_cnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", img)
warped = four_point_transform(img, screen_cnt.reshape(4, 2) * ratio)
cv2.imshow("Warped", warped)
else:
print("Cannot find contours")
cv2.waitKey(0)
cv2.destroyAllWindows()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment