opencv中的几种图像变换

opencv中的几种图像变换,由于公司内部保密原因,效果图不能贴出来了,可作为代码片段收藏灵活使用,下面代码是把参数给出的坐标点包围的区域变水平:

# coding:utf-8
import cv2
import numpy as np
import math
# 2D旋转 p0,p1为某条直线的坐标;center为旋转中心,默认以图片中心旋转;scale缩放比例
def pic_rotation(img,p0,p1,center=None,scale=1.0):
    x = 1.0 * (p1[1] - p0[1]) / (p1[0] - p0[0]) if p1[0] - p0[0] != 0 else 0
    radians = math.atan(x)
    angle = math.degrees(radians)
    if angle != 0:
        # 获取图像尺寸
        (h, w) = img.shape[:2]
        # 若未指定旋转中心,则将图像中心设为旋转中心
        if center is None:
            center = (w / 2, h / 2)
        # 执行旋转
        M = cv2.getRotationMatrix2D(center, angle, scale)
        rotated = cv2.warpAffine(img, M, (w, h))
        cv2.imshow('rotation',rotated)
        # 返回旋转后的图像
        return rotated
    return None

# 仿射变换 p0:top-left;p1:top-right;p2:bottom-right;p3:bottom-left
def pic_affine(img,p0,p1,p2,p3):
    width = int(np.linalg.norm(np.array(p0) - np.array(p1)))
    height = int(np.linalg.norm(np.array(p0) - np.array(p3)))
    pts1 = np.float32([p0, p1, p2])
    pts2 = np.float32([p0, [p0[0]+width,p0[1]], [p0[0]+width,p0[1]+height]])
    M = cv2.getAffineTransform(pts1, pts2)
    dst = cv2.warpAffine(img, M, (img.shape[1], img.shape[0]))
    cv2.imshow('affine',dst)

# 投影变换 p0:top-left;p1:top-right;p2:bottom-right;p3:bottom-left
def pic_perspective(img,p0,p1,p2,p3):
    width = int(np.linalg.norm(np.array(p0) - np.array(p1)))
    height = int(np.linalg.norm(np.array(p0) - np.array(p3)))
    pts1 = np.float32([p0, p1, p2, p3])
    pts2 = np.float32([p0, [p0[0]+width, p0[1]], [p0[0]+width, p0[1]+height], [p0[0], p0[1]+height]])
    M = cv2.getPerspectiveTransform(pts1, pts2)
    dst = cv2.warpPerspective(img, M, (0, 0))
    cv2.imshow('perspective',dst)
    return dst

if __name__ == '__main__':
    pic_path = r'D:\cp_zw.png'
    img = cv2.imread(pic_path)
    p0 = [231,159]
    p1 = [389, 175]
    p2 = [386, 252]
    p3 = [229, 207]
    cv2.imshow('orgi',img)
    pic_rotation(img,p0,p1)
    pic_affine(img, p0, p1, p2, p3)
    pic_perspective(img, p0, p1, p2, p3)
    cv2.waitKey()

猜你喜欢

转载自blog.csdn.net/otengyue/article/details/79278754