本文主要是介绍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 mathdef 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 rotateImgdef 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.shapey = H/2+20x = W/2+60winW = 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/
这篇关于Python图片数据增强crop、rotate、environment factor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!