2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

OpenCVのMat型オブジェクトどうしをテストコードで比較する

2
Last updated at Posted at 2019-07-10

OpenCVでcv2.imread()などを行うと、Mat型のオブジェクトが返ります。
cv::Mat Class Reference

二つのMatオブジェクトをPythonのunittestのテストコードで単純に比較しようとしたらエラーが出てしまいました。

動作確認してません.py
from unittest import TestCase
import cv2

class hogehoge(TestCase):
  def hoge(self):
    mat1 = cv2.imread('hoge1.jpg')
    # mat1を何か処理

    mat2 = cv2.imread('hoge2.jpg')
    # mat2を何か処理

    # mat1とmat2が同じになってるか確かめたい
    self.assertEqual(mat1, mat2)

# ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

エラーメッセージに書いてある通り、Mat型のような中身がたくさんあるオブジェクト(曖昧)は単純な比較ができないようです。
Use a.any() or a.all()と書いてあるように、素直にそれらを使いましょう。

次のようにテストコードを修正することで、いい感じにテストを実行できるようになりました。

動作確認してません.py
from unittest import TestCase
import cv2

class hogehoge(TestCase):
  def hoge(self):
    mat1 = cv2.imread('hoge1.jpg')
    # mat1を何か処理

    mat2 = cv2.imread('hoge2.jpg')
    # mat2を何か処理

    # mat1とmat2が同じになってるか確かめたい
    self.assertTrue((mat1 == mat2).all())

# Ran 1 tests in 0.037s
#
# OK

参考
Python で配列の一致比較 (list, ndarray)

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?