我正在写一个opencv程序,我发现了这个错误 当我运行代码时,这就是我得到的答案
Traceback (most recent call last):`File "Imagesegmentation.py", line 29, in <module>
image,contours,hierarchy = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
ValueError: need more than 2 values to unpack
我的代码是
import cv2
from sklearn.externals import joblib
from skimage.feature import hog
import numpy as np
import argparse as ap
parser = ap.ArgumentParser()
#parser.add_argument("-c", "--classiferPath", help="Path to Classifier File", required="True")
parser.add_argument("-i", "--image", help="Path to Image")
args = vars(parser.parse_args())
im = cv2.imread("/home/user/Desktop/python/New Doc 2018-02-12_1.jpg")
im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
im_gray = cv2.GaussianBlur(im_gray, (15, 15), 0)
ret, im_th = cv2.threshold(im_gray, 100, 255, cv2.THRESH_BINARY_INV)
cv2.namedWindow("Image grayscale", cv2.WINDOW_NORMAL)
cv2.imshow("Image grayscale", im_th)
cv2.waitKey()
_,ctrs, hier = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
rects = [None]*100
ctrCount=0
for ctr in ctrs:
if cv2.contourArea(ctr) >= 500:
rects[ctrCount] = cv2.boundingRect(ctr)
ctrCount=ctrCount+1
print 'ctrCount = ', ctrCount
newImageCount = 0
for rect in rects:
cv2.rectangle(im, (rect[0], rect[1]), (rect[0] + rect[2], rect[1] + rect[3]), (0, 255, 0), 3)
leng = int(rect[3] * 1.6)
pt1 = int(rect[1] + rect[3] // 2 - leng // 2)
pt2 = int(rect[0] + rect[2] // 2 - leng // 2)
roi = im_th[pt1:pt1+leng, pt2:pt2+leng]
try:
roi = cv2.resize(roi, (28, 28), interpolation=cv2.INTER_AREA)
#roi = cv2.dilate(roi, (3, 3))
name = 'image'+str(newImageCount)+'.jpg'
cv2.imwrite(name, roi)
newImageCount = newImageCount+1
#cv2.namedWindow("ROIs", cv2.WINDOW_NORMAL)
#cv2.imshow("ROIs", roi)
#cv2.waitKey()
except:
print 'Error'
cv2.namedWindow("Resulting Image with Rectangular ROIs", cv2.WINDOW_NORMAL)
cv2.imshow("Resulting Image with Rectangular ROIs", im)
cv2.waitKey()
任何帮助?
答案 0 :(得分:1)
使用Opencv 2.4.13.5
时,
cv2.findContours
仅返回2个值。所以你需要改变这样。
contours,hierarchy = cv2.findContours(im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
或者您可以升级到Opencv 3.x
,