Skip to content

Instantly share code, notes, and snippets.

@darkyen
Created February 27, 2015 10:55
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/a69bf8466c1ffd9e8573 to your computer and use it in GitHub Desktop.
Save darkyen/a69bf8466c1ffd9e8573 to your computer and use it in GitHub Desktop.
cc.py
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('./cc4.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)
w = 244 * 10
h = 154 * 10
ar = rectify(approx)
hr = np.array([ [0,0],[w,0],[w,h],[0,h] ],np.float32)
transform = cv2.getPerspectiveTransform(ar,hr)
warp = cv2.warpPerspective(gray,transform,(w,h))
clahe = cv2.createCLAHE(clipLimit=1.0, tileGridSize=(8,8))
c1 = clahe.apply(warp)
blur = cv2.GaussianBlur(c1,(5,5),0)
flagwrap, threshwrap = cv2.threshold(blur , 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imwrite('card.jpg', threshwrap);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment