首页 > 解决方案 > 如何使用open cv python从倾斜图像中获取拉直图像

问题描述

我有一个倾斜的图像。我想要从倾斜的图像中拉直图像。为此,我在这个函数中使用了 fout 点变换函数,我使用了 getpersptive 变换方法。莫代码在这里:

   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")
      # compute the perspective transform matrix and then apply it
      M = cv2.getPerspectiveTransform(rect, dst)
      warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))

      return warped

 contours , hierarchy=cv2.findContours(canny_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
 contours=sorted(contours, key=cv2.contourArea, reverse=True)
 for c in contours:
    p=cv2.arcLength(c, True)
    approx=cv2.approxPolyDP(c, 0.02*p, True)
    if len(approx)==4:
        target=approx.reshape(4,2)
        break
        
 target_image=four_point_transform(canny_img, target)
 plt.imshow(target_image)

我的代码或其他方法中缺少什么。请告诉我

标签: pythonopencvimage-processing

解决方案


推荐阅读