您的位置:首页 > 编程语言 > Python开发

OpenCv-python之图像的缩放和旋转

2017-03-19 19:26 471 查看
说明:在今后的机器学习中如果出现训练样本有限的情况下需要通过opencv来缩放旋转图像,以达到增加训练样本的作用。好好学习。

首先来看个例子

import cv2
import os

def read_img(source_imgpath):
img = cv2.imread(source_imgpath, 1)
return img

'''缩放'''
def crop_img(img, new_x, new_y):
res = cv2.resize(img, (new_x, new_y), interpolation=cv2.INTER_AREA) #见下
cv2.imwrite("./" + str(new_x) + '_' + str(new_y) +
'.jpg', res)

'''旋转'''
def rotate_img(img, rotate_angle, outputdir):

if not os.path.exists(outputdir) and not os.path.isdir(outputdir):  #a判断当前路径是否为绝对路径或者是否为路径
os.mkdir(outputdir)  #生成单级路径

rows, cols = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY).shape    #cvtcolor 是颜色转换参数

M = cv2.getRotationMatrix2D((cols / 2, rows / 2), rotate_angle, 1)
dst = cv2.warpAffine(img, M, (cols, rows))

cv2.imwrite(outputdir + os.path.sep + 'pic_' + str(rotate_angle) + '.jpg', dst)

if __name__ == '__main__':
img = read_img("./bd.jpg")
print(img.shape)
crop_img(img, 64, 64)

curr_angle = 0
while curr_angle < 360:
rotate_img(img, curr_angle, "./bd1")
curr_angle +=15
















1. res = cv2.resize(img, (new_x, new_y), interpolation=cv2.INTER_AREA)

dst = cv2.resize(src, dsize[, dst[, fx[, fy[, interpolation]]]])
目标:你可以对图像进行倍数的放大和缩小  也可以直接的输入尺寸大小

非关键字参数组有2个:src,dsize,分别是源图像与缩放后图像的尺寸
关键字参数为dst,fx,fy,interpolation

dst为缩放后的图像,fx,fy为图像x,y方向的缩放比
interplolation为缩放时的插值方式,有三种插值方式:
CV_INTER_NN - 最近邻插值,
CV_INTER_LINEAR - 双线性插值 (缺省使用)
CV_INTER_AREA - 使用象素关系重采样。当图像缩小时候,该方法可以避免波纹出现。当图像放大时,类似于 CV_INTER_NN 方法..
CV_INTER_CUBIC - 立方插值.


2. dst = cv2.warpAffine(img, M, (cols, rows))

dst = cv2.warpAffine(src, M, dsize[, dst[, flags[, borderMode[,          borderValue]]]])
仿射变换cv2.warpAffine()


非关键字参数有src, M, dsize,分别表示源图像,变换矩阵,变换后的图像的长宽

这里说一下放射变换的变换矩阵

位移变换矩阵为:2×3

[1001txty]

旋转变换矩阵:

a.标准旋转变换矩阵为


[cossin−sin−cos]

但该矩阵没有考虑旋转变换时进行位移以及缩放操作,

b.OpenCV中的旋转变换如下:


[a−bba(1−a)center.x−b.center.yb.center.x+(1−a).center.y]

其中,
a=scale.cos
b=scale.sin


OpenCV中提供了一个函数获得这样一个矩阵

M=cv2.getRotationMatrix2D(rotate_center, degree, scale)

rotate_center为一个2元的元组,表示旋转中心坐标,degree表示逆时针旋转的角度,scale表示缩放的比例

说明:在今后的机器学习中如果出现训练样本有限的情况下需要通过opencv来缩放旋转图像,以达到增加训练样本的作用。好好学习。仅此。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opencv