1. 图像处理案例
1.1 逆时针旋转90度
import tensorflow as tf
import matplotlib. pyplot as plt
import matplotlib. cm as cm
import numpy
import os
def show_pic ( pic, name, cmap= None ) :
'''显示图像'''
plt. imshow( pic, cmap= cmap)
plt. axis( 'off' )
plt. title( '%s' % ( name) )
plt. show( )
img_path = './images/219.jpg'
img = tf. io. read_file( img_path)
img = tf. image. decode_jpeg( img)
print ( img. shape, img. dtype)
show_pic( img, 'img' )
rotated_img = tf. image. rot90( img)
show_pic( rotated_img, 'rotated_img' )
(375, 500, 3) <dtype: 'uint8'>
1.2 中心裁剪
cropped_img1 = tf. image. central_crop( img, central_fraction= 0.6 )
show_pic( cropped_img1, 'cropped_img1' )
cropped_img2 = tf. image. resize_with_crop_or_pad( img, 200 , 200 )
show_pic( cropped_img2, 'cropped_img2' )
1.3 图像调整大小
float_img = tf. image. convert_image_dtype( img, tf. float32)
resized_image = tf. image. resize( float_img, [ 300 , 300 ] )
show_pic( resized_image, 'resized_image' )
1.4 改变图像底色
gray_img = tf. image. rgb_to_grayscale( img)
gray_img = tf. squeeze( gray_img)
show_pic( gray_img, 'img' , 'gray' )
1.5 图像数据类型转换
float_img = tf. image. convert_image_dtype( img, tf. float32)
hsv_img = tf. image. rgb_to_hsv( float_img)
show_pic( hsv_img, 'hsv_img' , 'hsv' )
1.6 改变图像亮度
bright_img = tf. image. adjust_brightness( img, 0.5 )
show_pic( bright_img, 'bright_img' )
1.7 改变图像饱和度
saturated_img= tf. image. adjust_saturation( img, 8 )
show_pic( saturated_img, 'saturated_img' )
1.8 改变对比度
contrasted_img = tf. image. adjust_contrast( img, 5 )
show_pic( contrasted_img, 'contrasted_img' )
encoded_image = tf. image. encode_jpeg( contrasted_img)
with tf. io. gfile. GFile( './images/0001.jpg' , 'wb' ) as file :
file . write( encoded_image. numpy( ) )
1.9 水平翻转图像
flipped_img1 = tf. image. flip_left_right( img)
show_pic( flipped_img1, 'flipped_h' )
flipped_img2 = tf. image. flip_up_down( img)
show_pic( flipped_img2, 'flipped_v' )
1.10 改变图像透明度
Alpha_channel = tf. fill( [ img. shape[ 0 ] , img. shape[ 1 ] , 1 ] , 128.0 )
Alpha_channel = Alpha_channel/ 255.0
four_channel_img = tf. concat( [ float_img, Alpha_channel] , 2 )
print ( four_channel_img. shape)
show_pic( four_channel_img, 'four_channel_img' )
(375, 500, 4)