def fix_target_perspective(contour, bin_shape):
"""
Fixes the perspective so it always looks as if we are viewing it head-on
:param contour:
:param bin_shape: numpy shape of the binary image matrix
:return: a new version of contour with corrected perspective, a new binary image to test against,
"""
before_warp = np.zeros(bin_shape, np.uint8)
cv2.drawContours(before_warp, [contour], -1, 255, -1)
try:
corners = get_corners(contour)
# get a perspective transformation so that the target is warped as if it was viewed head on
shape = (400, 280)
dest_corners = np.array([(0, 0), (shape[0], 0), (0, shape[1]), (shape[0], shape[1])], np.float32)
warp = cv2.getPerspectiveTransform(corners, dest_corners)
fixed_perspective = cv2.warpPerspective(before_warp, warp, shape)
fixed_perspective = fixed_perspective.astype(np.uint8)
if int(cv2.__version__.split('.')[0]) >= 3:
_, contours, _ = cv2.findContours(fixed_perspective, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
else:
contours, _ = cv2.findContours(fixed_perspective, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
new_contour = contours[0]
return new_contour, fixed_perspective
except ValueError:
raise ValueError('Failed to detect rectangle')
评论列表
文章目录