首页 > 解决方案 > 尝试得到凸性缺陷但得到错误

问题描述

目前我正在做一个最终项目。我正在使用 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)



标签: pythonopencvtypeerror

解决方案


该函数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)

推荐阅读