LoginSignup
33
13

More than 3 years have passed since last update.

[OpenCV] ValueError: not enough values to unpack (expected 3, got 2)

Posted at

問題

OpenCVfindContoursを使って以下のようにコードを書いたところ、

wrong

import numpy as np
import cv2

im = cv2.imread('test.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #この行

ValueError: not enough values to unpack (expected 3, got 2)と出て怒られた。

解決策

opencvの最新版であるOpenCV4では、findContoursの返り値は、contourshierarchyの2つになっているため、以下のように書けば期待通りの動作をする。

good

import numpy as np
import cv2

im = cv2.imread('test.jpg')
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) #この行

引っかかったこと

上記のコードは
http://labs.eecs.tottori-u.ac.jp/sd/Member/oyamada/OpenCV/html/py_tutorials/py_imgproc/py_contours/py_contours_begin/py_contours_begin.html
を参考にしている。
ところがこのコードはOpenCV3に準拠しているため、現行の最新版であるOpenCV4とは一部仕様が異なっている。
その例の一つがこのfindContoursの返り値だった。

間の悪いことに、同じHP内には
http://lang.sist.chukyo-u.ac.jp/classes/OpenCV/py_tutorials/py_imgproc/py_contours/py_contours_more_functions/py_contours_more_functions.html
というのがあって、ここには、

OpenCV3ではOpenCV2と異なり cv2.findContours()は2つではなく3つの値を返す

という記述がある。ここで自分の使っているOpenCVのバージョンに対して大きな混乱を招いた。

なんで import cv2 なん?

OpenCV4なら、import cv4ってしてください。
私は今日まで自分がOpenCV2を使っているのだと思いこんできました。

33
13
0

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
33
13