Skip to content

Instantly share code, notes, and snippets.

@darkyen
Created February 26, 2015 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darkyen/a8a0efcd4aec57d9caea to your computer and use it in GitHub Desktop.
Save darkyen/a8a0efcd4aec57d9caea to your computer and use it in GitHub Desktop.
Python script to detect credit card on plain background.
# Basic trickkk
import cv2;
import numpy as np;
def rectify(h):
h = h.reshape((4,2))
hnew = np.zeros((4,2),dtype = np.float32)
add = h.sum(1)
hnew[0] = h[np.argmin(add)]
hnew[2] = h[np.argmax(add)]
diff = np.diff(h,axis = 1)
hnew[1] = h[np.argmin(diff)]
hnew[3] = h[np.argmax(diff)]
return hnew
im = cv2.imread('./cc.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(1,1),1000)
flag, thresh = cv2.threshold(blur, 120, 255, cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea,reverse=True)[:2]
card = contours[1]
peri = cv2.arcLength(card,True)
approx = cv2.approxPolyDP(card,0.02*peri,True)
rect = cv2.minAreaRect(contours[1])
r = cv2.cv.BoxPoints(rect)
a = rectify(approx)
h = np.array([ [0,0],[244,0],[244,154],[0,154] ],np.float32)
transform = cv2.getPerspectiveTransform(a,h)
warp = cv2.warpPerspective(blur,transform,(244,154))
cv2.imwrite('python2.jpg', warp);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment