python - 尝试得到凸性缺陷但得到错误
问题描述
目前我正在做一个最终项目。我正在使用 opencv 库和 python 语言。用python研究opencv,为了了解如何使用它,我正在制作小项目。在这张照片中,我试图在一张手照片上找到轮廓、船体和凸面缺陷。但是当我运行我的代码时,我得到了这个错误:
Traceback (most recent call last):
line 21, in <module>
defects = cv.convexityDefects(cnt, hull)
TypeError: Expected Ptr<cv::UMat> for argument 'convexhull'
我正在研究 opencv 的一些文档,并从那里获取了一行代码。我发现了轮廓和船体,但是每次我遇到错误时都会遇到凸面缺陷。我已经在互联网上尝试了其他人的代码并将其实施到我的中,给了我同样的错误。我是 python 编程的新手,无法解决这个问题。谁能帮我?感谢和抱歉我的英语不好。
import cv2 as cv
import numpy as np
img = cv.resize(cv.imread("hand.jpg"), (350, 700))
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 230, 255, cv.THRESH_BINARY_INV)
contours, hierarchy = cv.findContours(thresh.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
hull = []
for i in range(len(contours)):
hull.append(cv.convexHull(contours[i], False))
cv.drawContours(img, hull, i, (0, 0, 255), 2, 8)
if len(hull) > 0:
defects = cv.convexityDefects(cnt, hull)
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv.circle(img, far, 5, [0, 0, 255], -1)
cv.drawContours(img, contours, -1, (0, 255, 0), 3)
cv.imshow('Image', img)
cv.imshow('Thresh', thresh)
cv.waitKey(0)
解决方案
该函数cv.convexityDefects
需要类型的输入Ptr<cv::UMat>
。但是你显然传递了一个列表(hull
)。
if len(hull) > 0:
我相信您可能需要遍历船体中的每个元素,而不是检查。
检查下面的代码以获取提到的更改。
import cv2 as cv
import numpy as np
img = cv.resize(cv.imread("hand.jpg"), (350, 700))
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
ret, thresh = cv.threshold(gray, 230, 255, cv.THRESH_BINARY_INV)
contours, hierarchy = cv.findContours(
thresh.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cnt = contours[0]
hull = []
for i in range(len(contours)):
hull.append(cv.convexHull(contours[i], False))
cv.drawContours(img, hull, i, (0, 0, 255), 2, 8)
for each in hull:
defects = cv.convexityDefects(cnt, each)
if not defects:
continue
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv.circle(img, far, 5, [0, 0, 255], -1)
cv.drawContours(img, contours, -1, (0, 255, 0), 3)
cv.imshow('Image', img)
cv.imshow('Thresh', thresh)
cv.waitKey(0)
推荐阅读
- c# - C# 程序的 C++ 包装器(外壳)
- outlook - 尝试使用 JXA AppleScripting 在 Outlook 2016 Mac 上列出帐户
- scala - spark中的预分区数据,以便每个分区在我们正在分区的列中具有不重叠的值
- c++ - valgrind 在主机名命令输出中显示内存泄漏
- amazon-web-services - 未找到资源的 Terraform
- sql - 用于插入和更新的 SQL 查询
- sparql - Sparql 按主题多次删除
- android - 为什么Android Pie最近将横向活动的任务缩略图空白?
- angular - 适用于 Angular 2 的 AWS Ubuntu 虚拟目录
- java - 递归缺失值无法弄清楚如何修复测试仪