cv2.warpPerspective调用异常:透视变换白屏及maxWidth为0问题
问题:cv2.warpPerspective透视变换白屏,maxWidth始终为0的排查与解决
按左上角、左下角、右下角、右上角顺序标记四点后,Warped窗口仅显示白屏,无法得到预期变换图像。此外,four_point_transform函数中maxWidth变量值几乎始终为0,不清楚诱因。
环境配置
- Windows 11 64位
- Python 3.10.7
- opencv-contrib-python 4.5.5.62
相关截图


问题代码
import numpy import cv2 import numpy as np def on_click(event, x, y, flags, param): global a_, b_, c_, d_, to_set if event == cv2.EVENT_LBUTTONDOWN: print("click") if to_set == 0: to_set = 1 a_ = [x, y] elif to_set == 1: to_set = 2 b_ = [x, y] elif to_set == 2: to_set = 3 c_ = [x, y] elif to_set == 3: to_set = 0 d_ = [x, y] def order_points(pts): # initialzie a list of coordinates that will be ordered # such that the first entry in the list is the top-left, # the second entry is the top-right, the third is the # bottom-right, and the fourth is the bottom-left rect = np.zeros((4, 2), dtype="float32") # the top-left point will have the smallest sum, whereas # the bottom-right point will have the largest sum s = pts.sum(axis=1) rect[0] = pts[np.argmin(s)] rect[2] = pts[np.argmax(s)] # now, compute the difference between the points, the # top-right point will have the smallest difference, # whereas the bottom-left will have the largest difference diff = np.diff(pts, axis=1) rect[1] = pts[np.argmin(diff)] rect[3] = pts[np.argmax(diff)] # return the ordered coordinates return rect def four_point_transform(image, pts): # obtain a consistent order of the points and unpack them # individually rect = order_points(pts) (tl, tr, br, bl) = rect # compute the width of the new image, which will be the # maximum distance between bottom-right and bottom-left # x-coordiates or the top-right and top-left x-coordinates widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) # compute the height of the new image, which will be the # maximum distance between the top-right and bottom-right # y-coordinates or the top-left and bottom-left y-coordinates heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) # now that we have the dimensions of the new image, construct # the set of destination points to obtain a "birds eye view", # (i.e. top-down view) of the image, again specifying points # in the top-left, top-right, bottom-right, and bottom-left # order dst = np.array([ [0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32") # compute the perspective transform matrix and then apply it M = cv2.getPerspectiveTransform(rect, dst) warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight)) # return the warped image return warped #cap = cv2.VideoCapture(1, cv2.CAP_DSHOW) cv2.namedWindow("Corner points") cv2.setMouseCallback("Corner points", on_click) to_set = 0 a_ = b_ = c_ = d_ = [0, 0] while True: big_img = cv2.imread("Test.png") #_, big_img = cap.read() ratio = big_img.shape[0] / 500.0 org = big_img.copy() img = imutils.resize(big_img, height=500) cv2.putText(img, f"{to_set}", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0)) values = numpy.array([a_, b_, c_, d_], dtype="float32") warped = four_point_transform(org, values * ratio) cv2.circle(img, a_, 5, (0, 0, 255)) cv2.circle(img, b_, 5, (0, 0, 255)) cv2.circle(img, c_, 5, (0, 0, 255)) cv2.circle(img, d_, 5, (0, 0, 255)) cv2.imshow("Warped", warped) cv2.imshow('Corner points', img) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows()
问题排查与解决
1. 核心问题:初始点未赋值导致maxWidth为0
程序启动时a_、b_、c_、d_初始化为[0,0],此时传入four_point_transform的四个点都是原点,计算出的widthA和widthB都是0,maxWidth自然为0,变换后得到1x1的白图(因为maxWidth-1=0)。
且循环中每次都会重新读取图片,未判断四个点是否全部标记完成,只要没完成四次点击,就会有部分点还是初始的[0,0],依然会计算出错误尺寸。
2. 次要问题:缺失imutils导入
代码中使用imutils.resize但未导入库,需补上:
import imutils
3. 修正后的完整代码
import numpy import cv2 import numpy as np import imutils # 补上缺失的导入 def on_click(event, x, y, flags, param): global a_, b_, c_, d_, to_set if event == cv2.EVENT_LBUTTONDOWN: print("click") if to_set == 0: to_set = 1 a_ = [x, y] elif to_set == 1: to_set = 2 b_ = [x, y] elif to_set == 2: to_set = 3 c_ = [x, y] elif to_set == 3: to_set = 0 d_ = [x, y] 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 def four_point_transform(image, pts): rect = order_points(pts) (tl, tr, br, bl) = rect widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) dst = np.array([ [0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32") M = cv2.getPerspectiveTransform(rect, dst) warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight)) return warped cv2.namedWindow("Corner points") cv2.setMouseCallback("Corner points", on_click) to_set = 0 a_ = b_ = c_ = d_ = [0, 0] # 标记是否完成四个点的选择 points_selected = False while True: big_img = cv2.imread("Test.png") ratio = big_img.shape[0] / 500.0 org = big_img.copy() img = imutils.resize(big_img, height=500) cv2.putText(img, f"Current point to mark: {to_set+1}", (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0)) # 绘制已标记的点 if to_set >=1: cv2.circle(img, a_, 5, (0, 0, 255), -1) if to_set >=2: cv2.circle(img, b_, 5, (0, 0, 255), -1) if to_set >=3: cv2.circle(img, c_, 5, (0, 0, 255), -1) if to_set ==0 and a_ != [0,0]: # 完成四个点标记 cv2.circle(img, d_, 5, (0, 0, 255), -1) points_selected = True # 只有完成四个点标记后才执行变换 if points_selected: values = numpy.array([a_, b_, c_, d_], dtype="float32") warped = four_point_transform(org, values * ratio) cv2.imshow("Warped", warped) else: # 未完成标记时显示提示图 empty_img = np.zeros((500,500,3), dtype=np.uint8) cv2.putText(empty_img, "Please mark 4 points in order", (20,250), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255,255,255)) cv2.imshow("Warped", empty_img) cv2.imshow('Corner points', img) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows()
4. 额外注意事项
- 标记点时尽量按照提示顺序(左上角→左下角→右下角→右上角),
order_points函数会重新排序,但保证输入准确性能减少异常 - 确保
Test.png与脚本在同一目录,或使用绝对路径避免读取失败 - 变换后的窗口尺寸由标记四点自动计算,适配目标区域大小
内容的提问来源于stack exchange,提问作者user19345539
相关产品推荐
相关产品推荐

