Opencv, PIL.Image和TensorFlow对图像进行resize(缩放)基于Python

一、基于OpenCV的方法

def Resize_Image_cv2(img_name, height, width, method):
    '''
    :param img_name: the name of image
    :param height, width: the resized heigth, width
    '''
    img = cv2.imread(img_name, cv2.IMREAD_UNCHANGED)
    size =(width, height)
    shrink = cv2.resize(img,size, interpolation=method)
    cv2.imshow("shrink", shrink) 
    return shrink

interpolation:这个是指定插值的方式,图像缩放之后,肯定像素要进行重新计算的,就靠这个参数来指定重新计算像素的方式,有以下几种:

INTER_NEAREST - 最邻近插值
INTER_LINEAR - 双线性插值,如果最后一个参数你不指定,默认使用这种方法
INTER_AREA - resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire’-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method.
INTER_CUBIC - 4x4像素邻域内的双立方插值
INTER_LANCZOS4 - 8x8像素邻域内的Lanczos插值

二、基于PIL.Image的方法

 

def Resize_Image(image_input, image_output, height, 
                 width, image_dtype, method):
    '''
    :param image_input: the name of image
    :param image_output: the name of image
    :param height, width: the size of image is resize
    :param image_dtype: the dtype of image output
    :param method : the choice to select proper quantization method
    '''
    img = Image.open(image_input)
    out = img.resize((width, height), method)
    out.save(image_output, image_dtype)

 method

Image.NEAREST :低质量
Image.BILINEAR:双线性
Image.BICUBIC :三次样条插值
Image.ANTIALIAS:高质量

三、基于TensorFlow的方法

def TF_image_Resize(path_to_images, method = 0, height =224, width =224):
    """
    using tensorflow to preprocess image data
    params: method 0:  Bilinear interpolation
            method 1: Nearset neighbor interploation
            method 2: Bicubic interpolation
            method 3: Area interpolation
    """
    if not tf.gfile.Exists(path_to_images):
        print("path to images does not exist")
    else:
        #search all jpeg files
        path_img_list = files = os.listdir(path_to_images)
        #path_img_list = tf.gfile.Glob(os.path.join(path_to_images, '*.jpg'))
        print(path_img_list)
        total_img = []
        for file in path_img_list:
            print("the name of jpeg file:", file)
            img_jpg = tf.gfile.FastGFile(path_to_images +'/' +file,'rb').read() 
            img_decode = tf.image.decode_jpeg(img_jpg)
            img_data = tf.image.convert_image_dtype(img_decode, dtype = tf.float32)
            img_data = tf.image.resize_images(img_data, height, width, method)
            total_img.append(img_data)
        print(len(total_img))
        return total_img 

 Opencv, PIL.Image和TensorFlow对图像进行resize(缩放)基于Python_第1张图片

你可能感兴趣的:(机器学习,数据预处理)