(一)
简介
对于不同规则大小的图片,想要在不进行压缩的情况下对其进行裁剪或者填充背景颜色为黑色,在Python图像处理中找了半天,没找到相应的函数。。。后来发现可利用tensorflow中的:
tf.image.resize_image_with_crop_or_pad
示例代码
'''
Created on 2017-8-16
@author: XT
'''
import tensorflow as tf
import scipy.misc
#读取图像可任意大小
filenames = ['E://Parking186//ImgReshape//1Thumbnail25.jpg']
filename_queue = tf.train.string_input_producer(filenames)
reader = tf.WholeFileReader()
key,value = reader.read(filename_queue)
images = tf.image.decode_jpeg(value)#tf.image.decode_png(value)
CP_H = 360
CP_W = 300
# 裁切图片
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
reshapeimg = tf.image.resize_image_with_crop_or_pad(images,CP_H,CP_W)
#reimg1的类型是<class 'numpy.ndarray'>
reimg1 = reshapeimg.eval()
scipy.misc.imsave('E:\\Parking186\\ImgReshape\\crop_or_pad\\crop_or_pad.jpg', reimg1)
coord.request_stop()
coord.join(threads)
print('crop_or_pad successful!')
结果
原图
填充为宽300,高360后
(二)
简介
上一节,介绍了处理一张图片,在不进行压缩的情况下对其进行裁剪或者填充背景颜色为黑色。这节介绍批量读取和保存裁剪、填充的图片。
1、需要在要进行处理的图片,新建InitImages文件夹,把图片放进去,命名格式不需要管;
2、新建文件夹crop_or_pad用于保存处理后的图片,命名规则为“crop_or_pad000”到“crop_or_padxxx”;
示例代码
'''
Created on 2017-4-28
@author: XT
'''
import tensorflow as tf
import scipy.misc
import os.path
file_dir = 'E:\\Parking186\\ImgReshape\\'
save_path = 'E:\\Parking186\\ImgReshape\\crop_or_pad\\'
classes = {'InitImages'}
image_list = []
for index,name in enumerate(classes):
class_path=file_dir+name+'\\'#读取类路径
for img_name in os.listdir(class_path):
filenames=class_path+img_name#获取每一个图片地址
image_list.append(filenames)
filename_queue = tf.train.string_input_producer(image_list)
reader = tf.WholeFileReader()
key,value = reader.read(filename_queue)
images = tf.image.decode_jpeg(value)#tf.image.decode_png(value)
CP_H = 360
CP_W = 300
# 裁切图片
with tf.Session() as sess:
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
reshapeimg = tf.image.resize_image_with_crop_or_pad(images,CP_H,CP_W)
for index in range(len(image_list)):
#reimg1的类型是<class 'numpy.ndarray'>
reimg = reshapeimg.eval()
scipy.misc.imsave(save_path+'crop_or_pad'+"%03d" %index+'.jpg', reimg)
coord.request_stop()
coord.join(threads)
print('crop_or_pad successful!')
结果
【1】
原图:
处理后:
【2】
原图
处理后
【3】
原图
处理后
结果文件