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

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

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

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

Python

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

Q&A

解決済

1回答

2480閲覧

Python InvalidArgumentError: Can not squeeze dim[0], expected a dimension of 1, got 0 [Op:Squeeze]

SuzuAya

総合スコア71

Python 3.x

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

Python

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

0グッド

0クリップ

投稿2021/02/08 11:33

編集2021/02/08 11:35

前提・実現したいこと

train画像を4つのフォルダに等分し、フォルダごとにjpeg画像に変換する作業を行ったところ、フォルダ①のみ以下のようなエラーが発生してしまいました(フォルダ②〜④は問題なく実行できました)。
また、それぞれのフォルダには画像が3,750枚ずつ入っているのですが、なぜかフォルダ①だけは3,751枚入っていると認識されてしまいます。
フォルダ①にのみ何か不具合のある画像が入っているのではと推測しているのですが、その画像を特定することは可能でしょうか。
また、もしも上記以外に思い当たる解決策などありましたらぜひご教示いただけますと幸いです。
どうぞよろしくお願いいたします。

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

InvalidArgumentError Traceback (most recent call last) <ipython-input-3-18afe903bdf5> in <module> 9 10 for name in tqdm(sorted(os.listdir(source))[:]):#[:100]): ---> 11 image = read_dicom(os.path.join(source, name)) 12 image = tf.io.encode_jpeg( 13 image, <ipython-input-2-5607b4c75658> in read_dicom(path) 8 ) 9 ---> 10 image = tf.squeeze(image, axis = 0) 11 12 image = tf.image.resize( ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs) 199 """Call target, and fall back on dispatchers if there is a TypeError.""" 200 try: --> 201 return target(*args, **kwargs) 202 except (TypeError, ValueError): 203 # Note: convert_to_eager_tensor currently raises a ValueError, not a ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py in squeeze_v2(input, axis, name) 4429 """ 4430 # pylint: disable=redefined-builtin -> 4431 return squeeze(input, axis, name) 4432 4433 ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py in wrapper(*args, **kwargs) 199 """Call target, and fall back on dispatchers if there is a TypeError.""" 200 try: --> 201 return target(*args, **kwargs) 202 except (TypeError, ValueError): 203 # Note: convert_to_eager_tensor currently raises a ValueError, not a ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py in new_func(*args, **kwargs) 536 'in a future version' if date is None else ('after %s' % date), 537 instructions) --> 538 return func(*args, **kwargs) 539 540 doc = _add_deprecated_arg_notice_to_docstring( ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py in squeeze(input, axis, name, squeeze_dims) 4377 if np.isscalar(axis): 4378 axis = [axis] -> 4379 return gen_array_ops.squeeze(input, axis, name) 4380 4381 ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py in squeeze(input, axis, name) 10154 return _result 10155 except _core._NotOkStatusException as e: > 10156 _ops.raise_from_not_ok_status(e, name) 10157 except _core._FallbackException: 10158 pass ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in raise_from_not_ok_status(e, name) 6860 message = e.message + (" name: " + name if name is not None else "") 6861 # pylint: disable=protected-access -> 6862 six.raise_from(core._status_to_exception(e.code, message), None) 6863 # pylint: enable=protected-access 6864 ~/home/user/libraries/Miniconda3/envs/test/lib/python3.6/site-packages/six.py in raise_from(value, from_value) InvalidArgumentError: Can not squeeze dim[0], expected a dimension of 1, got 0 [Op:Squeeze]

該当のソースコード

Python

1import os 2import tensorflow as tf 3import tensorflow_io as tfio 4from tqdm.notebook import tqdm 5 6os.environ["CUDA_VISIBLE_DEVICES"]="0" #specify GPU 7 8# Reading DICOM images 9 10def read_dicom(path): 11 image_bytes = tf.io.read_file(path) 12 image = tfio.image.decode_dicom_image( 13 image_bytes, 14 dtype = tf.uint16 15 ) 16 17 image = tf.squeeze(image, axis = 0) 18 19 image = tf.image.resize( 20 image, 21 (500, 500), 22 preserve_aspect_ratio = True 23 ) 24 25 image = image - tf.reduce_min(image) 26 image = image / tf.reduce_max(image) 27 image = tf.cast(image * 255, tf.uint8) 28 29 return image 30 31# Destination folder 32destination = "train_1_jpeg" 33os.makedirs(destination, exist_ok = True) 34 35# Source folder 36source = "./train_1" 37 38for name in tqdm(sorted(os.listdir(source))[:]):#[:100]): 39 image = read_dicom(os.path.join(source, name)) 40 image = tf.io.encode_jpeg( 41 image, 42 quality = 100, 43 format = 'grayscale' 44 ) 45 46 name = name.replace(".dicom", ".jpeg") 47 tf.io.write_file(os.path.join(destination, name), image)

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

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

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

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

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

jbpb0

2021/02/08 13:07

def read_dicom(path): の次に print(path) を追加したら、read_dicom()が実行される度に引数「path」の内容が表示されるので、エラーが出た直前に表示された「path」から、怪しい画像ファイルが分かると思います ただし、エラーが出るまでに、「path」が数千回表示されるかもしれません あと、追加する行のインデントは、次の行(image_bytes =...)に合わせてください
SuzuAya

2021/02/08 23:42

>jbpb0様 コメントありがとうございます!1枚目からエラーが出てしまい途方に暮れていたのですが、無事解決いたしました。ご丁寧にありがとうございました!
guest

回答1

0

ベストアンサー

とりあえず

python

1for name in tqdm(sorted(os.listdir(source))[:]):#[:100]): 2 try: 3 image = read_dicom(os.path.join(source, name)) 4 except: 5 print(name) 6 continue 7 # 以下略

とかで走らせてみるといいのかもしれません。

投稿2021/02/08 17:35

hayataka2049

総合スコア30933

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

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

SuzuAya

2021/02/08 23:40

>hayataka2049様 ご回答ありがとうございます!1枚、よくわからないファイル名がprint出力され、その他のファイルは無事jpeg変換することができました!本当に助かりました。ありがとうございました。
jbpb0

2021/02/09 00:21

質問者さんへ 「よくわからないファイル名」が、もしかしたらOSが勝手に作るファイルかもしれないので、そのディレクトリ内の全ファイルを読むのではなく、ファイル名の拡張子で画像ファイルだけ選んで読むようにした方がいいかもしれません
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.46%

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

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

質問する

関連した質問