実現したいこと
グラフの画像ファイルからデータを抽出するプログラムを作成してます。
当方Pythonは素人で、AIに書いてもらったコードを検証しております。
どうぞよろしくお願いいたします。
発生している問題・分からないこと
エディタ上では問題ないはずですが、実行するとなぜかインデントエラーが発生してしまいます。
エラーメッセージ
error
1>>> import cv2 2>>> import pytesseract 3>>> 4 5 6 7 8 9 10 11 12 13 14 15>>> import matplotlib.pyplot as plt 16>>> # Tesseractのパス(Windowsユーザー向け) 17>>> 18>>> pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' 19... # 画像読み込み 20... \ img = cv2.imread(image_path) 21... # テキスト抽出(位置情報付き、カラー画像で実施) 22... # テキスト抽出(位置... 23 data = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT) 24... \ val = float(text) 25... \ta['top'][i] # Y位置を強度の代理とみなす y = data['top'][i] # Y位置を強度の代理 26 # 重複除去(m/zを丸めてキーにする)+強度としてY位置を使う 27 unique_peaks = list({round(mz, 1): intensity for mz, intensity in peaks}.items()) 28 unique_peaks = list({round(mz, 1): intensity for mz, intensity in peaks}.items()) 29 30 31 unique_peaks.sort() 32 33 34 35 return unique_peaks 36 37 38 39 40 File "<python-input-238>", line 5 41 custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.' 42IndentationError: unexpected indent 43>>> img_path = r'E:\python\your_image_path.jpg' # 適切なファイルパスに書き換えてください 44>>> peaks = extract_peaks_from_image(img_path) 45Traceback (most recent call last): 46 File "<python-input-240>", line 1, in <module> 47 peaks = extract_peaks_from_image(img_path) 48 ^^^^^^^^^^^^^^^^^^^^^^^^ 49NameError: name 'extract_peaks_from_image' is not defined 50>>> mz, y_pos = zip(*peaks) 51Traceback (most recent call last): 52 File "<python-input-241>", line 1, in <module> 53 mz, y_pos = zip(*peaks) 54 ^^^^^ 55NameError: name 'peaks' is not defined 56>>> intensity = [max(y_pos) - y for y in y_pos] 57Traceback (most recent call last): 58 File "<python-input-242>", line 1, in <module> 59 intensity = [max(y_pos) - y for y in y_pos] 60 ^^^^^ 61NameError: name 'y_pos' is not defined 62>>> plt.figure(figsize=(10, 4)) 63<Figure size 1000x400 with 0 Axes> 64>>> plt.stem(mz, intensity, use_line_collection=True) 65Traceback (most recent call last): 66 File "<python-input-244>", line 1, in <module> 67 plt.stem(mz, intensity, use_line_collection=True) 68 ^^ 69NameError: name 'mz' is not defined 70>>> plt.xlabel("m/z") 71Text(0.5, 0, 'm/z') 72>>> plt.ylabel("Relative intensity (estimated)") 73Text(0, 0.5, 'Relative intensity (estimated)') 74>>> plt.title("Extracted Peaks") 75Text(0.5, 1.0, 'Extracted Peaks') 76>>> plt.show() 77>>> # テキスト出力 78>>> 79>>> for m, i in zip(mz, intensity): 80... print(f"m/z: {m}, intensity (relative): {i}") 81... 82Traceback (most recent call last): 83 File "<python-input-251>", line 1, in <module> 84 for m, i in zip(mz, intensity): 85 ^^ 86NameError: name 'mz' is not defined
該当のソースコード
Python
1import cv2 2import pytesseract 3import matplotlib.pyplot as plt 4# Tesseractのパス(Windowsユーザー向け) 5pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' 6def extract_peaks_from_image(image_path): 7 # 画像読み込み 8 img = cv2.imread(image_path) 9 # OCR設定(数字と小数点に限定) 10 custom_config = r'--oem 3 --psm 6 -c tessedit_char_whitelist=0123456789.' 11 # テキスト抽出(位置情報付き、カラー画像で実施) 12 data = pytesseract.image_to_data(img, config=custom_config, output_type=pytesseract.Output.DICT) 13 peaks = [] 14 for i in range(len(data['text'])): 15 text = data['text'][i] 16 try: 17 val = float(text) 18 y = data['top'][i] # Y位置を強度の代理とみなす 19 peaks.append((val, y)) 20 except ValueError: 21 continue 22 # 重複除去(m/zを丸めてキーにする)+強度としてY位置を使う 23 unique_peaks = list({round(mz, 1): intensity for mz, intensity in peaks}.items()) 24 unique_peaks.sort() 25 return unique_peaks 26 27img_path = r'E:\python\your_image_path.jpg' # 適切なファイルパスに書き換えてください 28peaks = extract_peaks_from_image(img_path) 29 30mz, y_pos = zip(*peaks) 31intensity = [max(y_pos) - y for y in y_pos] 32 33plt.figure(figsize=(10, 4)) 34plt.stem(mz, intensity, use_line_collection=True) 35plt.xlabel("m/z") 36plt.ylabel("Relative intensity (estimated)") 37plt.title("Extracted Peaks") 38plt.show() 39 40# テキスト出力 41for m, i in zip(mz, intensity): 42 print(f"m/z: {m}, intensity (relative): {i}")
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
indent-rainbow等を導入しましたが、インデントに問題はなさそうです。
補足
特になし
エラーエッセージを見るとインデント以前の問題に見えますが。
一つずつ解釈されたほうが。
すみません。
勉強不足で恐縮ですが、エラーメッセージ40〜42行のインシデントエラーよって関数が動かず、それ以降のエラーを引き起こしていると解釈したのですが、間違っていますか?
「インデントエラー」ではなくで「mz」が定義されていないエラーなのでは?
インタラクティブモードでソースコードをコピー・アンド・ペーストしている様に見受けられます。「該当のソースコード」をファイルに保存して実行してみてください。(手元の環境ではエラーは発生しません)
エディタではインデントの問題がないが、エディタからコードを選択状態にして「選択範囲/行を実行する」とインデントが崩れて実行エラーになる
というような話なのにそういう文脈を **全部書いてない** みたいな雰囲気を感じました
今までVSコードで実行していたのですが、コマンドプロンプト上で走らせるとうまくいきました!

回答1件
あなたの回答
tips
プレビュー