Skip to content

Instantly share code, notes, and snippets.

@MorkHub
Created September 8, 2017 05:15
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 MorkHub/0a7394eb802b44a32c790dee5dfe0ca6 to your computer and use it in GitHub Desktop.
Save MorkHub/0a7394eb802b44a32c790dee5dfe0ca6 to your computer and use it in GitHub Desktop.
trying to warp an image into a placeholder in another image
import numpy as np, cv2, imutils
image = cv2.imread("images/thumbscreen.png")
lower = np.array([250, 0, 250])
upper = np.array([255, 0, 255])
shapeMask = cv2.inRange(image, lower, upper)
cnts = cv2.findContours(shapeMask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
c = max(cnts, key=cv2.contourArea)
dst = cv2.cornerHarris(shapeMask,2,3,0.09)
dst = cv2.dilate(dst,None)
ret, dst = cv2.threshold(dst,0.01*dst.max(),255,0)
dst = np.uint8(dst)
ret, labels, stats, centroids = cv2.connectedComponentsWithStats(dst)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.001)
corners = cv2.cornerSubPix(shapeMask,np.float32(centroids),(5,5),(-1,-1),criteria)
res = np.hstack((centroids,corners))
res = np.int0(res)
res = np.array([x[:2] for x in res[1:5]])
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
for i in order_points(res):
cv2.circle(image, tuple(i[:2]), 4, (255,255,255), 2)
# show the output image
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment