Skip to content

Instantly share code, notes, and snippets.

@GTimothee
Last active June 14, 2018 10:19
Show Gist options
  • Save GTimothee/38dd8fd5c114c179e36dc86d67ac3232 to your computer and use it in GitHub Desktop.
Save GTimothee/38dd8fd5c114c179e36dc86d67ac3232 to your computer and use it in GitHub Desktop.
img_path = outDirPath + 'images/' + imgName
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
'''FIRST VERSION'''
mask = cv2.cvtColor(mask, cv2.COLOR_RGB2GRAY)
dest = cv2.bitwise_and(img, img, mask = mask)
for coordinates in coordinatesList:
coords = coordinates[:len(coordinates)-1]
#ANCIEN
X = [pt[0] for pt in coords]
Y = [pt[1] for pt in coords]
Xmin=np.amin(X)
Xmax=np.amax(X)
Ymin=np.amin(Y)
Ymax=np.amax(Y)
crop_img = dest[int(Ymin):int(Ymax), int(Xmin):int(Xmax)]
'''SECOND VERSION (way better)'''
lengths=[dist(coords[i],coords[i+1]) for i in range(3)]
maxLen = np.amax(lengths)
width = maxLen
height = maxLen / 1.41891891
src = np.float32([
[coords[0][0], coords[0][1]],
[coords[1][0], coords[1][1]],
[coords[3][0], coords[3][1]],
[coords[2][0], coords[2][1]]
], dtype=float)
dst = np.float32([
[0., 0.],
[width, 0.],
[0., height],
[width, height]
], dtype=float)
M = cv2.getPerspectiveTransform(src, dst)
new_crop_img = cv2.warpPerspective(img, M, (int(width), int(height)))
'''
plt.subplot(121), plt.imshow(crop_img), plt.title('Input')
plt.subplot(122), plt.imshow(new_crop_img), plt.title('Output')
plt.show()
cv2.waitKey(0)
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment