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

说明:在今后的机器学习中如果出现训练样本有限的情况下需要通过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,
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值