1. 程式人生 > 實用技巧 >影象處理中最常見的三種影象讀取方式

影象處理中最常見的三種影象讀取方式

背景

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