1、随机裁剪
if __name__ == "__main__":
img = cv2.imread("img/img.jpg")
#将图片进行随机裁剪为280×280
crop_img = tf.random_crop(img,[280,280,3])
sess = tf.InteractiveSession()
#显示图片
cv2.imwrite("img/crop.jpg",crop_img.eval())
plt.figure(1)
plt.subplot(121)
#将图片由BGR转成RGB
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(img)
plt.title("原始图片")
plt.subplot(122)
crop_img = cv2.cvtColor(crop_img.eval(),cv2.COLOR_BGR2RGB)
plt.title("裁剪后的图片")
plt.imshow(crop_img)
plt.show()
sess.close()
2、随机翻转
img = cv2.imread("img/img.jpg")
#将图片随机进行水平翻转
h_flip_img = tf.image.random_flip_left_right(img)
#将图片随机进行垂直翻转
v_flip_img = tf.image.random_flip_up_down(img)
sess = tf.InteractiveSession()
#通道转换
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
h_flip_img = cv2.cvtColor(h_flip_img.eval(),cv2.COLOR_BGR2RGB)
v_flip_img = cv2.cvtColor(v_flip_img.eval(),cv2.COLOR_BGR2RGB)
#显示图片
plt.figure(1)
plt.subplot(131)
plt.title("水平翻转")
plt.imshow(h_flip_img)
plt.subplot(132)
plt.title("垂直翻转")
plt.imshow(v_flip_img)
plt.subplot(133)
plt.title("原始图片")
plt.imshow(img)
plt.show()
3、随机亮度
import cv2
import numpy as np
import matplotlib.pyplot as plt
def augment_brightness_camera_images(image):
#HLS HUE 色度 ,lightness 亮度, Saturation 饱和度
image1 = cv2.cvtColor(image,cv2.COLOR_BGR2HLS)
image1 = np.array(image1,np.float32)
random_bright = 2
# 1 为 L 的通道数
image1[:,:,1] = image1[:,:,1] * random_bright
image1[:, :, 1][image1[:,:,1]>255] = 255
image1 = np.array(image1 ,dtype=np.uint8)
image1 = cv2.cvtColor(image1,cv2.COLOR_HLS2RGB)
return image1
img1 = cv2.imread(r"C:\Users\ADMIN\Desktop\heise.jpg")
img2 = augment_brightness_camera_images(img1)
plt.figure(figsize=(1,1))
fig = plt.figure()
a = fig.add_subplot(121)
plt.imshow(cv2.cvtColor(img1,cv2.COLOR_BGR2RGB))
a.set_title("past")
b = fig.add_subplot(122)
plt.imshow(img2)
a.set_title("now")
plt.show()
随机仿射
import cv2
import numpy as np
import matplotlib.pyplot as plt
def trans_image(image,hori_range,verti_range):
rows , cols , channels = image.shape
# tr_x 水平平移 tr_y 垂直平移
tr_x = hori_range * np.random.uniform() - hori_range / 2
tr_y = hori_range * np.random.uniform() - verti_range / 2
#仿射变换矩阵dst(输出图片)(x,y) = src(输入图片)(m11*x,m12*y,m13,m21*x,m22*y,m23)
trans_m = np.float32([[1,0,tr_x],[0,1,tr_y]])
#仿射平移函数
image_tr = cv2.warpAffine(image , trans_m,(cols,rows),borderValue=[255,255,255])
image1 = np.array(image_tr,dtype=np.uint8)
return image1
img1 = cv2.imread(r"C:\Users\ADMIN\Desktop\heise.jpg")
img2 = trans_image(img1,500,600)
plt.figure(figsize=(1,1))
fig = plt.figure()
a = fig.add_subplot(121)
plt.imshow(cv2.cvtColor(img1,cv2.COLOR_BGR2RGB))
a.set_title("past")
b = fig.add_subplot(122)
plt.imshow(cv2.cvtColor(img2,cv2.COLOR_BGR2RGB))
a.set_title("now")
plt.show()
4、图片的标准化
img = cv2.imread("img/img.jpg")
#将图片进行标准化
std_img = tf.image.per_image_standardization(img)
sess = tf.InteractiveSession()
print(std_img.eval())