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

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

新規登録して質問してみよう
ただいま回答率
85.48%
ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

GitHub

GitHubは、Gitバージョン管理システムを利用したソフトウェア開発向けの共有ウェブサービスです。GitHub商用プランおよびオープンソースプロジェクト向けの無料アカウントを提供しています。

保存

保存(save)とは、特定のファイルを、ハードディスク等の外部記憶装置に記録する行為を指します。

Python

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

Q&A

1回答

1154閲覧

入力ファイル名を用いて出力結果を.txtに保存したい。(「入力ファイル名.txt」のように保存したい。)

Kota1

総合スコア15

ファイル

ファイルとは、文字列に基づいた名前又はパスからアクセスすることができる、任意の情報のブロック又は情報を格納するためのリソースです。

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

GitHub

GitHubは、Gitバージョン管理システムを利用したソフトウェア開発向けの共有ウェブサービスです。GitHub商用プランおよびオープンソースプロジェクト向けの無料アカウントを提供しています。

保存

保存(save)とは、特定のファイルを、ハードディスク等の外部記憶装置に記録する行為を指します。

Python

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

0グッド

0クリップ

投稿2021/10/13 16:39

編集2021/10/14 06:32

前提・実現したいこと

画像を入力としていて、「画像の名前.txt」というファイルに実行結果を保存したいです。保存先はカレントディレクトリです。
複数の画像を入力としたいため、.txtファイルの区別をしたいです。

発生している問題・エラーメッセージ

指定したファイル名に保存することしかできません。

####全体のソースコード

Python

1"""Utils for monoDepth. 2""" 3import sys 4import re 5import numpy as np 6import cv2 7import torch 8 9 10def read_pfm(path): 11 """Read pfm file. 12 13 Args: 14 path (str): path to file 15 16 Returns: 17 tuple: (data, scale) 18 """ 19 with open(path, "rb") as file: 20 21 color = None 22 width = None 23 height = None 24 scale = None 25 endian = None 26 27 header = file.readline().rstrip() 28 if header.decode("ascii") == "PF": 29 color = True 30 elif header.decode("ascii") == "Pf": 31 color = False 32 else: 33 raise Exception("Not a PFM file: " + path) 34 35 dim_match = re.match(r"^(\d+)\s(\d+)\s$", file.readline().decode("ascii")) 36 if dim_match: 37 width, height = list(map(int, dim_match.groups())) 38 else: 39 raise Exception("Malformed PFM header.") 40 41 scale = float(file.readline().decode("ascii").rstrip()) 42 if scale < 0: 43 # little-endian 44 endian = "<" 45 scale = -scale 46 else: 47 # big-endian 48 endian = ">" 49 50 data = np.fromfile(file, endian + "f") 51 shape = (height, width, 3) if color else (height, width) 52 53 data = np.reshape(data, shape) 54 data = np.flipud(data) 55 56 return data, scale 57 58 59def write_pfm(path, image, scale=1): 60 """Write pfm file. 61 62 Args: 63 path (str): pathto file 64 image (array): data 65 scale (int, optional): Scale. Defaults to 1. 66 """ 67 68 with open(path, "wb") as file: 69 color = None 70 71 if image.dtype.name != "float32": 72 raise Exception("Image dtype must be float32.") 73 74 image = np.flipud(image) 75 76 if len(image.shape) == 3 and image.shape[2] == 3: # color image 77 color = True 78 elif ( 79 len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1 80 ): # greyscale 81 color = False 82 else: 83 raise Exception("Image must have H x W x 3, H x W x 1 or H x W dimensions.") 84 85 file.write("PF\n" if color else "Pf\n".encode()) 86 file.write("%d %d\n".encode() % (image.shape[1], image.shape[0])) 87 88 endian = image.dtype.byteorder 89 90 if endian == "<" or endian == "=" and sys.byteorder == "little": 91 scale = -scale 92 93 file.write("%f\n".encode() % scale) 94 95 image.tofile(file) 96 97 98def read_image(path): 99 """Read image and output RGB image (0-1). 100 101 Args: 102 path (str): path to file 103 104 Returns: 105 array: RGB image (0-1) 106 """ 107 img = cv2.imread(path) 108 109 if img.ndim == 2: 110 img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) 111 112 img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) / 255.0 113 114 return img 115 116 117def resize_image(img): 118 """Resize image and make it fit for network. 119 120 Args: 121 img (array): image 122 123 Returns: 124 tensor: data ready for network 125 """ 126 height_orig = img.shape[0] 127 width_orig = img.shape[1] 128 129 if width_orig > height_orig: 130 scale = width_orig / 384 131 else: 132 scale = height_orig / 384 133 134 height = (np.ceil(height_orig / scale / 32) * 32).astype(int) 135 width = (np.ceil(width_orig / scale / 32) * 32).astype(int) 136 137 img_resized = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA) 138 139 img_resized = ( 140 torch.from_numpy(np.transpose(img_resized, (2, 0, 1))).contiguous().float() 141 ) 142 img_resized = img_resized.unsqueeze(0) 143 144 return img_resized 145 146 147def resize_depth(depth, width, height): 148 """Resize depth map and bring to CPU (numpy). 149 150 Args: 151 depth (tensor): depth 152 width (int): image width 153 height (int): image height 154 155 Returns: 156 array: processed depth 157 """ 158 depth = torch.squeeze(depth[0, :, :, :]).to("cpu") 159 160 depth_resized = cv2.resize( 161 depth.numpy(), (width, height), interpolation=cv2.INTER_CUBIC 162 ) 163 164 return depth_resized 165 166def write_depth(path, depth, bits=1 , colored=False): 167 """Write depth map to pfm and png file. 168 169 Args: 170 path (str): filepath without extension 171 depth (array): depth 172 """ 173 # write_pfm(path + ".pfm", depth.astype(np.float32)) 174 if colored == True: 175 bits = 1 176 177 depth_min = depth.min() 178 depth_max = depth.max() 179 180 max_val = (2**(8*bits))-1 #8bit演算で計算するときの最大値 181 # if depth_max>max_val: 182 # print('Warning: Depth being clipped') 183 # 184 # if depth_max - depth_min > np.finfo("float").eps: 185 # out = depth 186 # out [depth > max_val] = max_val 187 # else: 188 # out = 0 189 190 #最大値最小値 191 print(str(depth_min)+","+str(depth_max)) 192 with open('min,max.txt', 'w') as f: 193 print(str(depth_min)+","+str(depth_max), file=f) 194 cv2.imwrite(path+'.txt') 195 196 if depth_max - depth_min > np.finfo("float").eps: 197 out = max_val * (depth - depth_min) / (depth_max - depth_min) 198 else: 199 out = 0 200 201 if bits == 1 or colored: 202 out = out.astype("uint8") 203 if colored: 204 out = cv2.applyColorMap(out,cv2.COLORMAP_INFERNO) 205 cv2.imwrite(path+'.png', out) 206 elif bits == 2: 207 cv2.imwrite(path+'.png', out.astype("uint16")) 208 209 return 210 211

該当のソースコード

Python

1 #最大値最小値 2 print(str(depth_min)+","+str(depth_max)) 3 with open('min,max.txt', 'w') as f: 4 print(str(depth_min)+","+str(depth_max), file=f)

試したこと

調べて出てきたpythonの結果のtxtでの保存方法を試しました。また、直前に「img」という引数があったため、以下のようにしてみましたができませんでした。

Python

1 with open(img+'.txt', 'w') as f: 2 print(str(depth_min)+","+str(depth_max), file=f)

補足情報(FW/ツールのバージョンなど)

このプログラムを動かしており、入力画像の深度情報を.txtに保存したいです。
https://github.com/compphoto/BoostingMonocularDepth

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

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

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

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

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

etherbeg

2021/10/13 23:20 編集

具体的な回答のために必要な正確な情報を得るためには、質問文に記載されている断片的なプログラムでは不十分です。プログラムの全体を質問に追記していただければ何かアドバイスができるかもしれません。
TakaiY

2021/10/14 01:16

追加された情報のソースを調べてみる気にはなれなかったので、質問です。 - 結果を出力しようとしているタイミングで、「画像の名前」が保存されている変数名と内容(変数をprintoしたもの)を教えてください。 - 出力ファイルのパスはカレントパスでいいですか? 他の場所を指定しますか?
Kota1

2021/10/14 06:34

画像はINPUTフォルダに格納されています。
guest

回答1

0

保存先が出力画像の保存先と同じでよければ、以下でできると思います。

python

1#最大値最小値 2print(str(depth_min)+","+str(depth_max)) 3with open(path+'.txt', 'w') as f: 4 print(str(depth_min)+","+str(depth_max), file=f)

どうしてもカレントディレクトリがよければ以下を試してみてください。

python

1import os 2 3#最大値最小値 4print(str(depth_min)+","+str(depth_max)) 5cwd = os.getcwd() 6img_file_name = os.path.basename(path) 7txt_file_path = os.path.join(cwd, img_file_name) 8with open(txt_file_path+'.txt', 'w') as f: 9 print(str(depth_min)+","+str(depth_max), file=f)

うまくいったら import os はファイルの先頭のimport文の先頭に移動しておいてください。

投稿2021/10/14 12:20

etherbeg

総合スコア1195

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問