对图片进行边缘检测和轮廓检测,并对检测轮廓进行排序,但是运行出错,出现Traceback的问题
import numpy as np
import argparse
import cv2
image = cv2.imread(args["image"])
#坐标也会相同变化
ratio = image.shape[0] / 500.0
orig = image.copy()
image = resize(orig, height = 500)
# 预处理
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)
# 展示预处理结果
print("STEP 1: 边缘检测")
cv2.imshow("Image", image)
cv2.imshow("Edged", edged)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 轮廓检测
cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[1]
# 对检测到的轮廓进行了一个面积的排序,去排序轮廓的前5个
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
# 遍历轮廓
for c in cnts:
# 计算轮廓近似
peri = cv2.arcLength(c, True)
# C表示输入的点集
# epsilon表示从原始轮廓到近似轮廓的最大距离,它是一个准确度参数,0.02 * peri一个指定的精度,值越小其轮廓越精确,值越大轮廓粗糙
# True表示封闭的
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# 4个点的时候就拿出来
if len(approx) == 4:
screenCnt = approx
break
# 展示结果
print("STEP 2: 获取轮廓")
cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
cv2.imshow("Outline", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果及报错内容
E:\Programdata\envs\study\python.exe D:/Scan/scan.py --image ./images/receipt.jpg
STEP 1: 边缘检测
Traceback (most recent call last):
File "D:\Scan\scan.py", line 95, in
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]
cv2.error: OpenCV(4.6.0) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\shapedescr.cpp:315: error: (-215:Assertion failed) npoints >= 0 && (depth == CV_32F || depth == CV_32S) in function 'cv::contourArea'
对代码进行了调试,并检查了语法问题,没有错误,也怀疑是否是路径问题,但是修改了还是出错。
我想要达到的结果
先请问是 cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]代码的问题,还是电脑环境配置的问题等。想请教出错的原因和怎么解决?