背景
最近計算圖像殘差時,嘗試了用三種方式讀取圖像,很多時候讀取的圖像往往都是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!")