@Sora74sw (空 田中)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

OpenCVエラーについて

実行環境

Jupter Notebook

解決したいこと

入門書を参考に動画から魚が移った場面を抽出しようとしていますがエラーがでてしまいます。

実行しようとしているコード

import cv2
import os, glob, pickle
from sklearn.model_selection import train_test_split
from sklearn import datasets, metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# 画像の学習サイズやパスを指定
image_size = (64, 32)
path = os.path.dirname(os.path.abspath('.../'))
path_fish = path + '/fish'
path_nofish = path + 'nofish'
x = [] # 画像データ
y = [] # ラベルデータ

# 画像データを読み込んで配列に追加 --- (*1)
def read_dir(path, label):
    files = glob.glob(path + "/*.jpg")
    for f in files:
        img = cv2.imread(f)
        #assert comparing_img is not None, "読み込みに失敗しました。"
        #assert img.size > 0, "画像が空っぽです。"
        img = cv2.resize(img, image_size)
        img_data = img.reshape(-1, ) # 一次元に展開
        x.append(img_data)
        y.append(label)
        
# 画像データを読み込む
read_dir(path_nofish, 0)
read_dir(path_fish, 1)

# データを学習用とテスト用に分割する --- (*2)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

# データを学習 --- (*3)
clf = RandomForestClassifier()
clf.fit(x_train, y_train)

# 精度の確認 --- (*4)
y_pred = clf.predict(x_test)
print(accuracy_score(y_test, y_pred))

# データを保存 --- (*5)
with open("fish.pkl", "wb") as fp:
  pickle.dump(clf, fp)

発生している問題・エラー

error: OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgproc\src\resize.cpp:3720: 
error: (-215:Assertion failed) !ssize.empty() in function 'cv::resize'

該当するソースコード

error                                     Traceback (most recent call last)
<ipython-input-71-3191039fcd97> in <module>
     28 # 画像データを読み込む
     29 read_dir(path_nofish, 0)
---> 30 read_dir(path_fish, 1)
     31 
     32 # データを学習用とテスト用に分割する --- (*2)

<ipython-input-71-3191039fcd97> in read_dir(path, label)
     21         #assert comparing_img is not None, "読み込みに失敗しました。"
     22         #assert img.size > 0, "画像が空っぽです。"
---> 23         img = cv2.resize(img, image_size)
     24         img_data = img.reshape(-1, ) # 一次元に展開
     25         x.append(img_data)

自分で試したこと

入門書では10行目が

path = os.path.dirname(os.path.abspath('__file__'))

となっていますが

path = os.path.dirname(os.path.abspath('.../'))

と変更しました
授業ではjupyter Notebookを使用しているため__file__が使えないとのことで先生の指示に従い変更しました

また、実行環境をIDLEに変更すると、同一のプログラムで動作しますが、学習結果が学習用データの中身に関わらず1.0となってしまいます

0 likes

2Answer

img = cv2.resize(img, image_size)の前にprint(img.size)等して出力を確認したり、
ファイルやパス(コード見た感じpath_fish側にだけ/が付いている?)に問題がないか、
確認すると解決するかもしれません。

1Like

解決いたしました
相対パスから絶対パスにすることで解決したので、パスが繋がっていなかったのが原因と分かりました

0Like

Your answer might help someone💌