OpenCV warpPerspective报错求助:图像读取失败问题解决
解决OpenCV透视变换中cv2.warpPerspective无法读取图像的问题
我编写了一个用OpenCV实现图像变换与透视扭曲的脚本,但运行时提示cv2.warpPerspective无法读取图像,添加cv2.waitKey()也无效。以下是问题代码、错误分析及修正后的可运行代码:
原问题代码
import cv2 import numpy as np import matplotlib.pyplot as plt plt.ion() img = cv2.imread('path to jpeg') img_copy = np.copy(img) img_copy = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB) plt.imshow(img_copy) pt_A =[162,83] pt_B = [68,324] pt_C = [542,324] pt_D = [405,83] width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2)) width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2)) maxWidth = max(int(width_AD), int(width_BC)) height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) **2)) height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) **2)) maxHeight = max(int(height_AB), int(height_CD)) input_pts = np.float32([pt_A, pt_B, pt_C, pt_D]) output_pts = np.float32([[0,0],[0,maxHeight -1],[maxWidth -1, maxHeight -1], [maxWidth -1, 0]]) M = cv2.perspectiveTransform(input_pts, output_pts) out = cv2.warpPerspective(img,M,(maxWidth,maxHeight),flags=cv2.INTER_LINEAR)
错误分析
- 误用
cv2.perspectiveTransform函数:该函数用于对坐标点执行透视变换,计算透视变换矩阵应使用cv2.getPerspectiveTransform。 - 未检查图像读取状态:若图像路径错误,
cv2.imread会返回None,后续操作必然报错。
修正后的代码
import cv2 import numpy as np import matplotlib.pyplot as plt plt.ion() # 读取图像,替换为实际路径 img = cv2.imread('path to jpeg') # 检查图像是否读取成功 if img is None: print("无法读取图像,请检查路径是否正确") exit() img_copy = np.copy(img) img_copy = cv2.cvtColor(img_copy, cv2.COLOR_BGR2RGB) plt.imshow(img_copy) plt.title("原始图像") plt.pause(0.5) pt_A = [162,83] pt_B = [68,324] pt_C = [542,324] pt_D = [405,83] width_AD = np.sqrt(((pt_A[0] - pt_D[0]) ** 2) + ((pt_A[1] - pt_D[1]) ** 2)) width_BC = np.sqrt(((pt_B[0] - pt_C[0]) ** 2) + ((pt_B[1] - pt_C[1]) ** 2)) maxWidth = max(int(width_AD), int(width_BC)) height_AB = np.sqrt(((pt_A[0] - pt_B[0]) ** 2) + ((pt_A[1] - pt_B[1]) **2)) height_CD = np.sqrt(((pt_C[0] - pt_D[0]) ** 2) + ((pt_C[1] - pt_D[1]) **2)) maxHeight = max(int(height_AB), int(height_CD)) input_pts = np.float32([pt_A, pt_B, pt_C, pt_D]) output_pts = np.float32([[0,0],[0,maxHeight -1],[maxWidth -1, maxHeight -1], [maxWidth -1, 0]]) # 使用正确的函数计算透视变换矩阵 M = cv2.getPerspectiveTransform(input_pts, output_pts) out = cv2.warpPerspective(img,M,(maxWidth,maxHeight),flags=cv2.INTER_LINEAR) # 显示变换后的图像 out_rgb = cv2.cvtColor(out, cv2.COLOR_BGR2RGB) plt.figure() plt.imshow(out_rgb) plt.title("透视变换后图像") plt.show(block=True)
使用的测试图像为标准透视变换示例图。
内容的提问来源于stack exchange,提问作者Padavan
相关产品推荐
相关产品推荐

