写写代码,跑跑程序,出现两个小错误,解决之。
(1)cv2.morphologyEx
mask=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,kernalC1)
TypeError: Expected cv::UMat for argument 'kernel'
(2)cv2.findContours
_,countours0,hierarchy=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
ValueError: not enough values to unpack (expected 3, got 2)
两个小错误,查了下OpenCV版本为4.0.0
import cv2
print(cv2.__version__)
4.0.0
查看OpenCV4.0.0documents
https://docs.opencv.org/4.0.0-rc/d4/d73/tutorial_py_contours_begin.html
代码为:
import numpy as np
import cv2 as cv
im = cv.imread('test.jpg')
imgray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(imgray, 127, 255, 0)
contours, hierarchy = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
修改网页上方版本为3.2,自动跳转到3.2的documents
https://docs.opencv.org/3.2.0/d4/d73/tutorial_py_contours_begin.html
代码为
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)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
同样查找cv2.morphologyEx
https://docs.opencv.org/4.0.0-rc/d9/d61/tutorial_py_morphological_ops.html
代码为
import cv2 as cv
import numpy as np
img = cv.imread('j.png',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv.erode(img,kernel,iterations = 1)
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
kernel类型为应该np.unit8。其他版本同上。
应该是版本问题,内置函数参数和返回值有修改,修改kernalC1类型,cv2.findContours和返回值,如下
(1)kernalC1类型
kernalCl = np.ones((11,11),np.uint)
改为
kernalCl = np.ones((11,11),np.uint8)
(2)cv2.findContours返回值
_,countours0,hierarchy=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
改为
countours0,hierarchy=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)