質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

16292閲覧

使用している画像は16ビットなのに8ビットの画像が出力されてしまい、困っています

tukutuku

総合スコア14

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

1クリップ

投稿2019/08/05 06:27

編集2019/08/07 08:10

学習に用いる画像、推論で入力する画像すべてuint16型の画像を使っていますが、出力されてくる結果の画像はuint8型になってしまいます。
出力画像もuint16型で出したいです。以下がコードになります。
解決方法が分かる方いらっしゃいましたら、教えていただきたいです。よろしくお願いします。

from __future__ import division from __future__ import absolute_import import os import cv2 import numpy as np from keras.layers import Input, Conv3D, MaxPooling3D, UpSampling3D, Add, BatchNormalization from keras.models import Model import keras.optimizers as optimizers from tensorflow.python.keras import backend as K import matplotlib.pyplot as plt IMAGE_SIZE = 512 EPOCHS = 100 # ディレクトリ内の画像を読み込む # inputpath: ディレクトリ文字列,imagesize: 画像サイズ, type_color: ColorかGray def load_images(inputpath, imagesize, type_color): imglist = [] for root, dirs, files in os.walk(inputpath): for fn in sorted(files): bn, ext = os.path.splitext(fn) if ext not in [".bmp", ".BMP", ".jpg", ".JPG", ".jpeg", ".JPEG", ".png", ".PNG"]: continue filename = os.path.join(root, fn) if type_color == 'Color': # カラー画像の場合 testimage = cv2.imread(filename, cv2.IMREAD_COLOR) # サイズ変更 height, width = testimage.shape[:2] testimage = cv2.resize(testimage, (imagesize, imagesize), interpolation = cv2.INTER_AREA) #主に縮小するのでINTER_AREA使用 testimage = np.asarray(testimage, dtype=np.float64) # チャンネル,高さ,幅に入れ替え.data_format="channels_first"を使うとき必要 #testimage = testimage.transpose(2, 0, 1) # チャンネルをbgrの順からrgbの順に変更 testimage = testimage[::-1] elif type_color == 'Gray': # グレースケール画像の場合 testimage = cv2.imread(filename, cv2.IMREAD_GRAYSCALE) # サイズ変更 height, width = testimage.shape[:2] #testimage = cv2.resize(testimage, (imagesize, imagesize), interpolation = cv2.INTER_AREA) #主に縮小するのでINTER_AREA使用 #testimage = np.reshape(testimage, (4, 512, 512)) # 2次元配列を3次元配列に変換する testimage = np.asarray([testimage], dtype=np.float64) testimage = np.asarray(testimage, dtype=np.float64).reshape((4, 512, 512)) # チャンネルの次元がないので1次元追加する testimage = np.asarray([testimage], dtype=np.float64) testimage = np.asarray(testimage, dtype=np.float64).reshape((1, 4, 512, 512)) # 高さ,幅,チャンネルに入れ替え.data_format="channels_last"を使うとき必要 testimage = testimage.transpose(1, 2, 3, 0) imglist.append(testimage) imgsdata = np.asarray(imglist, dtype=np.float32) return imgsdata, sorted(files) # 画像リストとファイル名のリストを返す # 指定ディレクトリに画像リストの画像を保存する # savepath: ディレクトリ文字列, filenamelist: ファイル名リスト, imagelist: 画像リスト def save_images(savepath, filenamelist, imagelist): for i, fn in enumerate(filenamelist): filename = os.path.join(savepath, fn) testimage = imagelist[i].reshape(2048,512) #testimage = np.delete(testimage, 2, 1) # グレースケール画像を保存するときだけ使用.チャンネルに相当する3列目削除 #幅を一つ消してしまう!! cv2.imwrite(filename, testimage) #%% # データ準備 # 画像読み込み # training用の低解像度画像と高解像度画像読み込み imagelow_train, imagelow_train_filenames = load_images(".\InputImage_train\", (2048, 512), 'Gray') imagehigh_train, imagehigh_train_filenames = load_images(".\TeachImage_train\", (2048, 512), 'Gray') # test用の低解像度画像と高解像度画像読み込み imagelow_test, imagelow_test_filenames = load_images(".\InputImage_test\", (2048, 512), 'Gray') imagehigh_test, imagehigh_test_filenames = load_images(".\TeachImage_test\", (2048, 512), 'Gray') image_infer, image_infer_filenames = load_images(".\InputImage_inference\", (2048, 512), 'Gray') # 画素値0-1正規化 8bit用 #imagelow_train /= 255 #imagehigh_train /= 255 #imagelow_test /= 255 #imagehigh_test /= 255 #image_infer /= 255 # 画素値0-1正規化 16bit用 imagelow_train += 1000 imagehigh_train += 1000 imagelow_test += 1000 imagehigh_test += 1000 image_infer += 1000 imagelow_train /= 2000 imagehigh_train /= 2000 imagelow_test /= 2000 imagehigh_test /= 2000 image_infer /= 2000 #%% # ネットワークの定義 # Super Resolution CNN def network_srcnn(): input_img = Input(shape=(IMAGE_SIZE, IMAGE_SIZE, IMAGE_SIZE, 1)) x = Conv2D(128, (9, 9), activation="relu", padding='same')(input_img) x = Conv2D(64, (3, 3), activation="relu", padding='same')(x) x = Conv2D(1, (5, 5), padding='same')(x) model = Model(input_img, x) return model # Deep Denoising Super Resolution CNN def network_ddsrcnn2(): #Input(InputImageSize, InputImgageSize, Channel) input_img = Input((4, IMAGE_SIZE, IMAGE_SIZE, 1), dtype='float') enc1 = Conv3D(64, kernel_size=3, activation="relu", padding='same')(input_img) enc1 = Conv3D(64, kernel_size=3, activation="relu", padding='same')(enc1) down1 = MaxPooling3D(pool_size=2)(enc1) enc2 = Conv3D(128, kernel_size=3, activation="relu", padding='same')(down1) enc2 = Conv3D(128, kernel_size=3, activation="relu", padding='same')(enc2) down2 = MaxPooling3D(pool_size=2)(enc2) enc3 = Conv3D(256, kernel_size=3, activation="relu", padding='same')(down2) up3 = UpSampling3D(size=2)(enc3) dec3 = Conv3D(128, kernel_size=3, activation="relu", padding='same')(up3) dec3 = Conv3D(128, kernel_size=3, activation="relu", padding='same')(dec3) add2 = Add()([dec3, enc2]) up2 = UpSampling3D(size=2)(add2) dec2 = Conv3D(64, kernel_size=3, activation="relu", padding='same')(up2) dec2 = Conv3D(64, kernel_size=3, activation="relu", padding='same')(dec2) add1 = Add()([dec2, enc1]) dec1 = Conv3D(1, kernel_size=5, activation="linear", padding='same')(add1) model = Model(input=input_img, output=dec1) return model model = network_ddsrcnn2() # ネットワークを表示 print(model.summary()) #%% def psnr(y_true, y_pred): return -10*K.log(K.mean(K.flatten((y_true - y_pred))**2))/np.log(10) # trainingの設定 from keras.utils import multi_gpu_model #multigpuの設定 adam = optimizers.Adam(lr=1e-3) parallel_model = multi_gpu_model(model, gpus=2) parallel_model.compile(loss='mean_squared_error', optimizer='adam', metrics=[psnr]) from keras.callbacks import ModelCheckpoint #エポックごとにモデル保存 os.makedirs('model', exist_ok=True) model_checkpoint = ModelCheckpoint( filepath=os.path.join('model', 'model_{epoch:02d}_h5'), monitor='val_loss', period=5, verbose=1) # training実行 # training用低解像度画像と高解像度画像でtrainingする.validation用にtest用の低解像度画像と高解像度画像を使用する. training = parallel_model.fit(imagelow_train, imagehigh_train, epochs=EPOCHS, batch_size=6, shuffle=True, validation_data=(imagelow_test, imagehigh_test), callbacks=[model_checkpoint], verbose=1) # 学習履歴グラフ表示 def plot_history(history): plt.plot(history.history['psnr']) plt.plot(history.history['val_psnr']) plt.title('model accuracy') plt.xlabel('epoch') plt.ylabel('accuracy') plt.legend(['psnr', 'val_psnr'], loc='lower right') plt.show() plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('model loss') plt.xlabel('epoch') plt.ylabel('loss') plt.legend(['loss', 'val_loss'], loc='lower right') plt.show() plot_history(training) #%% # test用低解像度画像を用いた推定の実行 results = model.predict(image_infer, batch_size=6, verbose=1) # 推定結果の画像をファイル保存 #results *= 255 # 0-1の範囲の値が出力されるので見やすいように255倍する results *= 2000 results -= 1000 save_images(".\result\", image_infer_filenames, results)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

コードをすべて読んではいませんが、問題となっているのはモデルから出力された float 型の画像を uint16 型の画像に変換する処理がないことだと思います。

以下のステップで float 型の (H, W) の numpy 配列を uint16 型に変換してから保存してください。

  1. [src.min(), src.max()] -> [0, 2000] にスケールする。
  2. uint16 にキャストする。
  3. cv2.imwrite で保存する。

python

1import cv2 2import numpy as np 3 4# float 画像を適当に生成する。 5src = np.random.uniform(0, 1, (100, 100)) 6print(src.dtype, src.shape) # float64 (100, 100) 7 8# [src.min(), src.max()] -> [0, 2000] にスケールする。 9dst = np.interp(src, (src.min(), src.max()), (0, 2000)) 10dst = dst.astype(np.uint16) # float -> uint16 11 12# 保存する。 13cv2.imwrite("result.png", dst) 14 15# 読み込む。 16src = cv2.imread("result.png", cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR) 17print(src.dtype, src.shape) # uint16 (100, 100) 18 19print(dst.min(), dst.max())

投稿2019/08/05 06:55

編集2019/08/07 08:42
tiitoi

総合スコア21954

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

tukutuku

2019/08/07 08:22

回答ありがとうございます。ご指摘いただいたやり方で上手くいくか確認するため、画像を読み込んで新たな画像として保存するという簡単なプログラムをつくりました。しかし入力画像は0~2000の画素値を持っているのですが、画素値が0~64031の値を持ってしまいました。何か解決方法はありますでしょうか。
tiitoi

2019/08/07 08:42

uint16 は [0, 65535] の範囲の値を持てるのでそのようにしました。 [0, 2000] の範囲しか値を持たないようにするように回答を修正しましたが、これでどうでしょうか。
tukutuku

2019/08/08 03:23

すみません私の勘違いで、画像を読み込んだ時にすでに画素値がおかしくなっているようで、 img = cv2.imread(".//InputImage_train//", flags=-1) で今は読み込んでいるのですが、元データの値をそのまま読み込める方法ご存知でしょうか?
tiitoi

2019/08/08 04:02

回答に記載したように cv2.imread("result.png", cv2.IMREAD_ANYDEPTH | cv2.IMREAD_ANYCOLOR) のフラグをつければ、uint16 の画像であればそのまま読み込めませんでしょうか?
tukutuku

2019/08/09 06:52

記載されているフラグでもそのまま読み込めませんでした。 もともと0~2000の画素値だったのに対し、読み込んだ直後には0~64031の画素値になっています。
tiitoi

2019/08/09 06:54 編集

その画像をどこかにアップロードしていただくことはできないでしょうか? 実際にファイルがどのようなものなのか検証できないと、問題について指摘するのは難しいです。
tukutuku

2019/08/09 06:59

すいません、上手くいきました!! 何度も質問してすみませんでした。 本当にありがとうございます!!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問