Python图片数据增强crop、rotate、environment factor

简介

利用Python的CV模块,实现图片数据的增强操作:随机裁剪、旋转角度、增强光照噪声。

结果

这里写图片描述

代码

'''
Created on 2017年9月14日

@author: XT
'''
import cv2
import numpy as np
import os.path
import random
import math

def rotate(  
    img,  #image matrix  
    angle #angle of rotation  
    ):  

    height = img.shape[0]  
    width = img.shape[1]  

    if angle%180 == 0:  
        scale = 1  
    elif angle%90 == 0:  
        scale = float(max(height, width))/min(height, width)  
    else:  
        scale = math.sqrt(pow(height,2)+pow(width,2))/min(height, width)  

    #print 'scale %f\n' %scale  

    rotateMat = cv2.getRotationMatrix2D((width/2, height/2), angle, scale)  
    rotateImg = cv2.warpAffine(img, rotateMat, (width, height))  
    return rotateImg

def tfactor(img):
    hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV);#增加饱和度光照的噪声
    hsv[:,:,0] = hsv[:,:,0]*(0.8+ np.random.random()*0.2);
    hsv[:,:,1] = hsv[:,:,1]*(0.3+ np.random.random()*0.7);
    hsv[:,:,2] = hsv[:,:,2]*(0.2+ np.random.random()*0.8);
    img = cv2.cvtColor(hsv,cv2.COLOR_HSV2BGR);
    return img       

file_dir = "F:\\BaiduYunDownload\\ImagesBmp\\"
classes = {"0"}
i = 0
for index,name in enumerate(classes):
    class_path = file_dir+name+"\\"
    for img_name in os.listdir(class_path):
        img_path = class_path+img_name#读取每一个图片路径
        image = cv2.imread(img_path)
        tfimg = tfactor(image)  
        rotateAngle = random.randrange(0,10)
        rotateImg = rotate(tfimg,rotateAngle)
        H,W,Channels = tfimg.shape
        y = H/2+20
        x = W/2+60
        winW = random.randrange(160,x-60)
        winH = random.randrange(80,y-20)
#         cv2.rectangle(rotateImg, (int(x-winW), int(y-winH)), (int(x + winW), int(y + winH)), (0, 255, 0), 2)
#         cv2.imshow('tfimg',rotateImg)
#         cv2.waitKey(0)    
#        cropImg_clone = rotateImg.copy()
        cropImg = rotateImg[int(y-winH):int(y + winH),int(x-winW):int(x + winW)]
        #cv2.imshow('cropImg',cropImg)
        #cv2.waitKey(0)
        cv2.imwrite('F:\\BaiduYunDownload\\InitialImages\\0\\cropRotatetf_{:04d}.jpg'.format(i),cropImg)
        i +=1

参考

【1】使用Python和OpenCV检测图像中的物体并将物体裁剪下来 - liqiancao的专栏 - CSDN博客
http://blog.csdn.net/liqiancao/article/details/55670749
【2】关于python使用cv画矩形并填充颜色同时填充文字 - 龚细军 - 博客园
http://www.cnblogs.com/gongxijun/p/6824494.html
【3】Cropman:识别人脸的图片裁剪Python程序 - 资讯 - 伯乐在线
http://top.jobbole.com/3948/

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

何以问天涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值