简介
利用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/