本文整理汇总了Python中cv2.perspectiveTransform方法的典型用法代码示例。如果您正苦于以下问题:Python cv2.perspectiveTransform方法的具体用法?Python cv2.perspectiveTransform怎么用?Python cv2.perspectiveTransform使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cv2
的用法示例。
在下文中一共展示了cv2.perspectiveTransform方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def render(img, obj, projection, model, color=False):
"""
Render a loaded obj model into the current video frame
"""
vertices = obj.vertices
scale_matrix = np.eye(3) * 3
h, w = model.shape
for face in obj.faces:
face_vertices = face[0]
points = np.array([vertices[vertex - 1] for vertex in face_vertices])
points = np.dot(points, scale_matrix)
# render model in the middle of the reference surface. To do so,
# model points must be displaced
points = np.array([[p[0] + w / 2, p[1] + h / 2, p[2]] for p in points])
dst = cv2.perspectiveTransform(points.reshape(-1, 1, 3), projection)
imgpts = np.int32(dst)
if color is False:
cv2.fillConvexPoly(img, imgpts, (137, 27, 211))
else:
color = hex_to_rgb(face[-1])
color = color[::-1] # reverse
cv2.fillConvexPoly(img, imgpts, color)
return img
示例2: filter_matrix_corners_homography
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def filter_matrix_corners_homography(pts, max, matrix) -> (float, List):
'''
Compute the images of the image corners and of its center (i.e. the points you get when you apply the homography to those corners and center),
and verify that they make sense, i.e. are they inside the image canvas (if you expect them to be)? Are they well separated from each other?
Return a distance and a list of the transformed points
'''
# Transform the 4 corners thanks to the transformation matrix calculated
transformed_pts = cv2.perspectiveTransform(pts, matrix)
# Compute the difference between original and modified position of points
dist = round(cv2.norm(pts - transformed_pts, cv2.NORM_L2) / max, 10) # sqrt((X1-X2)²+(Y1-Y2)²+...)
# Totally an heuristic (geometry based):
if dist < 0.20:
return dist, transformed_pts
else:
return 1, transformed_pts
示例3: filter_matrix_corners_affine
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def filter_matrix_corners_affine(pts, max, matrix) -> (float, List):
'''
Compute the images of the image corners and of its center (i.e. the points you get when you apply the homography to those corners and center),
and verify that they make sense, i.e. are they inside the image canvas (if you expect them to be)? Are they well separated from each other?
Return a distance and a list of the transformed points
'''
# Make affine transformation
add_row = np.array([[0, 0, 1]])
affine_matrix = np.concatenate((matrix, add_row), axis=0)
transformed_pts_affine = cv2.perspectiveTransform(pts, affine_matrix)
# Affine distance
tmp_dist_affine = round(cv2.norm(pts - transformed_pts_affine, cv2.NORM_L2) / max, 10) # sqrt((X1-X2)²+(Y1-Y2)²+...)
# Totally an heuristic (geometry based):
if tmp_dist_affine < 0.20:
return tmp_dist_affine, transformed_pts_affine
else:
return 1, transformed_pts_affine
示例4: _augment_keypoints
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def _augment_keypoints(self, keypoints_on_images, random_state, parents, hooks):
result = keypoints_on_images
matrices, max_heights, max_widths = self._create_matrices(
[kps.shape for kps in keypoints_on_images],
random_state
)
for i, (M, max_height, max_width) in enumerate(zip(matrices, max_heights, max_widths)):
keypoints_on_image = keypoints_on_images[i]
kps_arr = keypoints_on_image.get_coords_array()
#nb_channels = keypoints_on_image.shape[2] if len(keypoints_on_image.shape) >= 3 else None
warped = cv2.perspectiveTransform(np.array([kps_arr], dtype=np.float32), M)
warped = warped[0]
warped_kps = ia.KeypointsOnImage.from_coords_array(
warped,
shape=(max_height, max_width) + keypoints_on_image.shape[2:]
)
if self.keep_size:
warped_kps = warped_kps.on(keypoints_on_image.shape)
result[i] = warped_kps
return result
示例5: getTransformedLocation
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def getTransformedLocation(x_coord,y_coord, calData):
try:
# transform only the hit point with the saved transformation matrix
# ToDo: idea for second camera -> transform complete image and overlap both images to find dart location?
dart_loc_temp = np.array([[x_coord, y_coord]], dtype="float32")
dart_loc_temp = np.array([dart_loc_temp])
dart_loc = cv2.perspectiveTransform(dart_loc_temp, calData.transformation_matrix)
new_dart_loc = tuple(dart_loc.reshape(1, -1)[0])
return new_dart_loc
#system not calibrated
except AttributeError as err1:
print err1
return (-1, -1)
except NameError as err2:
#not calibrated error
print err2
return (-2, -2)
#Returns dartThrow (score, multiplier, angle, magnitude) based on x,y location
示例6: persTransform
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def persTransform(pts, H):
"""Transforms a list of points, `pts`,
using the perspective transform `H`."""
src = np.zeros((len(pts), 1, 2))
src[:, 0] = pts
dst = cv2.perspectiveTransform(src, H)
return np.array(dst[:, 0, :], dtype='float32')
示例7: track
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def track(self, frame):
'''Returns a list of detected TrackedTarget objects'''
self.frame_points, frame_descrs = self.detect_features(frame)
if len(self.frame_points) < MIN_MATCH_COUNT:
return []
matches = self.matcher.knnMatch(frame_descrs, k = 2)
matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * 0.75]
if len(matches) < MIN_MATCH_COUNT:
return []
matches_by_id = [[] for _ in xrange(len(self.targets))]
for m in matches:
matches_by_id[m.imgIdx].append(m)
tracked = []
for imgIdx, matches in enumerate(matches_by_id):
if len(matches) < MIN_MATCH_COUNT:
continue
target = self.targets[imgIdx]
p0 = [target.keypoints[m.trainIdx].pt for m in matches]
p1 = [self.frame_points[m.queryIdx].pt for m in matches]
p0, p1 = np.float32((p0, p1))
H, status = cv2.findHomography(p0, p1, cv2.RANSAC, 3.0)
status = status.ravel() != 0
if status.sum() < MIN_MATCH_COUNT:
continue
p0, p1 = p0[status], p1[status]
x0, y0, x1, y1 = target.rect
quad = np.float32([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
quad = cv2.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2)
track = TrackedTarget(target=target, p0=p0, p1=p1, H=H, quad=quad)
tracked.append(track)
tracked.sort(key = lambda t: len(t.p0), reverse=True)
return tracked
示例8: visualize_homo
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def visualize_homo(img1, img2, kp1, kp2, matches, homo, mask):
h, w, d = img1.shape
pts = [[0, 0], [0, h - 1], [w - 1, h - 1], [w - 1, 0]]
pts = np.array(pts, dtype=np.float32).reshape((-1, 1, 2))
dst = cv.perspectiveTransform(pts, homo)
img2 = cv.polylines(img2, [np.int32(dst)], True, [255, 0, 0], 3, 8)
matches_mask = mask.ravel().tolist()
draw_params = dict(matchesMask=matches_mask,
singlePointColor=None,
matchColor=(0, 255, 0),
flags=2)
res = cv.drawMatches(img1, kp1, img2, kp2, matches, None, **draw_params)
return res
示例9: track_target
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def track_target(self, frame):
self.cur_keypoints, self.cur_descriptors = self.detect_features(frame)
if len(self.cur_keypoints) < self.min_matches: return []
try: matches = self.feature_matcher.knnMatch(self.cur_descriptors, k=2)
except Exception as e:
print('Invalid target, please select another with features to extract')
return []
matches = [match[0] for match in matches if len(match) == 2 and match[0].distance < match[1].distance * 0.75]
if len(matches) < self.min_matches: return []
matches_using_index = [[] for _ in range(len(self.tracking_targets))]
for match in matches:
matches_using_index[match.imgIdx].append(match)
tracked = []
for image_index, matches in enumerate(matches_using_index):
if len(matches) < self.min_matches: continue
target = self.tracking_targets[image_index]
points_prev = [target.keypoints[m.trainIdx].pt for m in matches]
points_cur = [self.cur_keypoints[m.queryIdx].pt for m in matches]
points_prev, points_cur = np.float32((points_prev, points_cur))
H, status = cv2.findHomography(points_prev, points_cur, cv2.RANSAC, 3.0)
status = status.ravel() != 0
if status.sum() < self.min_matches: continue
points_prev, points_cur = points_prev[status], points_cur[status]
x_start, y_start, x_end, y_end = target.rect
quad = np.float32([[x_start, y_start], [x_end, y_start], [x_end, y_end], [x_start, y_end]])
quad = cv2.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2)
track = self.tracked_target(target=target, points_prev=points_prev, points_cur=points_cur, H=H, quad=quad)
tracked.append(track)
tracked.sort(key = lambda x: len(x.points_prev), reverse=True)
return tracked
# Detect features in the selected ROIs and return the keypoints and descriptors
示例10: dealcurve
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def dealcurve(curve):
cmean = curve.mean(0)
angle = (random.random()*10)-5
scale = ((random.random()-0.5)*0.1)+1.0
m = cv2.getRotationMatrix2D((0,0),angle,scale)
m = np.vstack([m,[0,0,1]])
dmean = (np.random.rand(1,2)-0.5)*10
curve = curve - cmean
curve = cv2.perspectiveTransform(np.array([curve]),m)
curve += cmean
curve += dmean
return curve[0]
示例11: _homography
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def _homography(src_pts,dst_pts,template_width,template_height,match_point=None):
row,col,dim = dst_pts.shape
if match_point:
for i in range(row):
match_point.append([int(dst_pts[i][0][0]),int(dst_pts[i][0][1])])
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
pts = np.float32([[0, 0], [0, template_height - 1],
[template_width - 1, template_height - 1],
[template_width - 1, 0]]).reshape(-1, 1, 2)
#找到一个变换矩阵,从查询图映射到检测图片
dst = cv2.perspectiveTransform(pts, M)
return dst
示例12: find
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def find(search_file, image_file, threshold=None):
'''
param threshold are disabled in sift match.
'''
sch = _cv2open(search_file, 0)
img = _cv2open(image_file, 0)
kp_sch, des_sch = sift.detectAndCompute(sch, None)
kp_img, des_img = sift.detectAndCompute(img, None)
if len(kp_sch) < MIN_MATCH_COUNT or len(kp_img) < MIN_MATCH_COUNT:
return None
FLANN_INDEX_KDTREE = 0
index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params, search_params)
matches = flann.knnMatch(des_sch, des_img, k=2)
good = []
for m,n in matches:
if m.distance < 0.7*n.distance:
good.append(m)
if len(good) > MIN_MATCH_COUNT:
sch_pts = np.float32([kp_sch[m.queryIdx].pt for m in good]).reshape(-1, 1, 2)
img_pts = np.float32([kp_img[m.trainIdx].pt for m in good]).reshape(-1, 1, 2)
M, mask = cv2.findHomography(sch_pts, img_pts, cv2.RANSAC, 5.0)
# matchesMask = mask.ravel().tolist()
h, w = sch.shape
pts = np.float32([ [0, 0], [0, h-1], [w-1, h-1], [w-1, 0] ]).reshape(-1, 1, 2)
dst = cv2.perspectiveTransform(pts, M)
lt, br = dst[0][0], dst[2][0]
return map(int, (lt[0]+w/2, lt[1]+h/2))
else:
return None
示例13: _homography
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def _homography(src_pts,dst_pts,template_width,template_height,match_point=None):
row,col,dim = dst_pts.shape
if match_point:
for i in range(row):
match_point.append([int(dst_pts[i][0][0]),int(dst_pts[i][0][1])])
M, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
pts = np.float32([[0, 0], [0, template_height - 1],
[template_width - 1, template_height - 1],
[template_width - 1, 0]]).reshape(-1, 1, 2)
#找到一个变换矩阵,从查询图映射到检测图片
dst = cv2.perspectiveTransform(pts, M)
return dst
#SIFT + Homography
示例14: ld2bbSample
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def ld2bbSample(sample, h):
sample = np.float32([sample]).reshape(-1, 1, 2)
con = cv2.perspectiveTransform(sample, h)
return np.array(list(con[0][0]))
示例15: transform_pnts
# 需要导入模块: import cv2 [as 别名]
# 或者: from cv2 import perspectiveTransform [as 别名]
def transform_pnts(self, pnts, M33):
"""
:param pnts: 2D pnts, left-top, right-top, right-bottom, left-bottom
:param M33: output from transform_image()
:return: 2D pnts apply perspective transform
"""
pnts = np.asarray(pnts, dtype=np.float32)
pnts = np.array([pnts])
dst_pnts = cv2.perspectiveTransform(pnts, M33)[0]
return dst_pnts