背景
最近计算图像残差时,尝试了用三种方式读取图像,很多时候读取的图像往往都是unit8
类型,这样便导致残差的计算全为正数的情况,需要通过numpy类型转换函数进行转换
opencv
type
查看python中元素的类型(list、dict、string、float、int)dtype
查看numpy ndrray的数据类型(float、int)numpy
中使用astype
,及直接指定dtype = 'float32'
进行转换,其中dtype
可以省略
import cv2 import numpy as np s1 = cv2.imread('1.png') print (type(s1)) # <type 'numpy.ndarray'> print (s1.dtype) # uint8 # 通过下面的函数进行数据类型转换,再进行残差计算 s1 = s1.astype(int16) s1 = s1.astype(float32) s1 = np.array(s1, 'int16') s1 = np.array(s1, dtype='int16') # 保存图片前先Scale到[0, 255]之间 s1 = np.maximum(ss, 0) # < 0 = 0 s1 = np.minimum(ss, 255) # > 255 = 255 cv2.imwrite("Recon.png", s1
PIL
采用PIL模块的Image.fromarray(image).save
方式存取的是无损图像,一般的图像差值处理顺序是:float32, clip(0,1)*255, round, cast uin8
import numpy as np from PIL import Image import scipy.misc s1 = Image.open('1.png') image_1 = np.array(s1) print (image_1.dtype) # uint8 image1 = np.array(img1, dtype='float32') print (image_1.dtype) # float32 Image.fromarray(image).save(test_set_dir + str(i)+'.png')
Tensorflow
用tensorflow直接保存图像的情况使用较少,可以预先产生一个tf.gfile.FastGFile
文件,接着将图片信息写入即可,注意这里又多出了两种类型转换函数:tf.image.convert_image_dtype
,tf.cast
import tensorflow as tf img_name = ["1.jpg"] filename_queue = tf.train.string_input_producer(img_name) img_reader = tf.WholeFileReader() _,image_jpg = img_reader.read(filename_queue) image_decode_jpeg = tf.image.decode_jpeg(image_jpg) # 两种类型转换函数 image_decode_jpeg = tf.image.convert_image_dtype(image_decode_jpeg, dtype=tf.float32) # image_decode_jpeg = tf.cast(image_decode_jpeg, tf.float32) sess = tf.Session() coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) image_flip_up_down = tf.image.flip_up_down(image_decode_jpeg) image_flip_up_down = tf.image.convert_image_dtype(image_flip_up_down, dtype=tf.uint8) image_flip_up_down = tf.image.encode_jpeg(image_flip_up_down) img_up_down = sess.run(image_flip_up_down) hd = tf.gfile.FastGFile("ud.png", "w") hd.write(img_up_down) hd.close() coord.request_stop() sess.close() print("test end!")