美文网首页
薄板样条插值(THIN PLATE SPLINES)的实现与使用

薄板样条插值(THIN PLATE SPLINES)的实现与使用

作者: 疯人愿的疯言疯语 | 来源:发表于2022-04-07 15:48 被阅读0次

    薄板样条插值(Thin plate splines)的实现与使用一只帅气的小菜鸡的博客-CSDN博客薄板样条插值

    import cv2
    import numpy as np
    from PIL import Image
    
    # 首先读入img
    img_pil = Image.open('D:\\Postgraduate\\工作文件夹\\7-Table\\脚本\\img_0.jpg')
    img = cv2.cvtColor(np.asarray(img_pil), cv2.COLOR_RGB2BGR)
    label = open('D:\\Postgraduate\\工作文件夹\\7-Table\\脚本\\img_0.txt',
                 'r', encoding='utf8')
    
    lines = label.readlines()
    
    for line in lines:
        points = []
        point_ = line.split(' ')[0:8]
        for i in range(len(point_)//2):
            points.append((int(point_[2*i]), int(point_[2*i+1])))
    
        # 找面积最小的矩形
        rect = cv2.minAreaRect(np.array(points))
        # 得到最小矩形的坐标
        box = cv2.boxPoints(rect)
        dest_w, dest_h = int(rect[1][0]), int(rect[1][1])
        # 标准化坐标到整数
        box = np.int0(box)
    
        x, y, w, h = cv2.boundingRect(np.array(points))
        roi_img = img[y:y+h, x:x+w]
        cv2.imshow('roi_img', roi_img)
        cv2.waitKey()
        # 画上绿色的圆圈
        # for i in range(len(points)):
        #     points[i] = (points[i][0]-x, points[i][1]-y)
        # for point in points:
        #     cv2.circle(roi_img, point, 1, (0, 255, 0), 2)
        # cv2.imshow('img', roi_img)
        # cv2.waitKey()
    
        # 实例化tps
        tps = cv2.createThinPlateSplineShapeTransformer()
    
        # 源点集合,处理为合适的格式
        sourceshape = np.array(points, np.int32)
        sourceshape = sourceshape.reshape(1, -1, 2)
    
        # opencv中匹配函数
        matches = []
        N = len(points)
        for i in range(0, N):
            matches.append(cv2.DMatch(i, i, 0))
    
        # 开始变动,获取目标点
        newpoints = []
        N = N//2
        dx = int(w/(N-1))
        for i in range(0, N):
            newpoints.append((dx*i, 2))
        for i in range(N-1, -1, -1):
            newpoints.append((dx*i, h-2))
    
        print(points, newpoints)
        targetshape = np.array(newpoints, np.int32)
        targetshape = targetshape.reshape(1, -1, 2)
    
        # 估计插值矩阵,并进行tps插值获取插值后的图像
        tps.estimateTransformation(targetshape, sourceshape, matches)
        roi_img_ = tps.warpImage(roi_img)
    
        # for point in newpoints:
        #     cv2.circle(roi_img_, (int(point[0]), int(point[1])), 1, (0, 0, 255), 2)
    
        cv2.namedWindow('img2', cv2.WINDOW_FREERATIO)
    
        cv2.imshow('img2', roi_img_)
        roi_img_ = cv2.resize(roi_img_, (max(dest_w, dest_h), min(dest_w, dest_h)), interpolation=cv2.INTER_NEAREST)
        cv2.imwrite('C:\\Users\\12116\\Desktop\\img_0_rotate.jpg', roi_img_)
        cv2.waitKey()
    
    

    相关文章

      网友评论

          本文标题:薄板样条插值(THIN PLATE SPLINES)的实现与使用

          本文链接:https://www.haomeiwen.com/subject/enqssrtx.html