loc = cv2.findNonZero(res > threshold) cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'findNonZero' > Overload resolution failed: > - src data type = 0 is not supported > - Expected Ptr<cv::UMat> for argument 'src'
时间: 2023-08-28 18:17:37 浏览: 52
这个错误可能是由于输入的数组`res > threshold`不是一个NumPy数组而是一个OpenCV的矩阵或图像,导致了`cv2.findNonZero()`函数的错误。
为了解决这个问题,可以将`res > threshold`转换为NumPy数组,然后再传给`cv2.findNonZero()`函数。可以使用`np.array()`函数将OpenCV矩阵或图像转换为NumPy数组,示例如下:
```python
import numpy as np
# 将OpenCV矩阵或图像转换为NumPy数组
res_np = np.array(res > threshold, dtype=np.uint8)
# 在NumPy数组中查找非零像素的位置
loc = cv2.findNonZero(res_np)
```
在上述代码中,我们使用`np.array()`函数将`res > threshold`转换为了一个NumPy数组,并指定了数据类型为`np.uint8`,即无符号8位整型。然后,我们将该数组传给了`cv2.findNonZero()`函数,成功地找到了非零像素的位置。
需要注意的是,如果输入的数组是一个OpenCV的图像,可以使用`cv2.cvtColor()`函数将其转换为灰度图像或者其他格式的图像,然后再将其转换为NumPy数组。
相关问题
loc = np.where(res >= threshold)
这行代码使用了NumPy的np.where函数来找到满足条件(res大于等于阈值)的元素的索引位置。np.where返回一个包含满足条件的元素索引的元组,其中第一个元素是满足条件的行索引数组,第二个元素是满足条件的列索引数组(如果是多维数组的话)。这样,通过loc = np.where(res >= threshold)可以获取到res中大于等于阈值的元素的位置信息。
# 获取匹配程度大于阈值的所有位置 loc = np.where(res >= threshold) 错误
如果你遇到了`TypeError: '>=' not supported between instances of 'NoneType' and 'float'`错误,可能是因为在使用`cv2.matchTemplate()`函数时,没有正确地返回结果导致的。
`cv2.matchTemplate()`函数返回一个包含匹配结果的矩阵,你需要使用这个矩阵来查找匹配程度大于阈值的位置。如果匹配程度小于阈值,`cv2.matchTemplate()`函数会返回一个空矩阵,导致在使用`np.where()`函数时出错。
你可以在使用`cv2.matchTemplate()`函数之后,添加以下代码来检查是否成功返回了匹配结果矩阵:
```python
# 使用cv2.matchTemplate()函数进行模板匹配
res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
# 检查是否成功返回了匹配结果矩阵
if res is None:
print("Failed to find template in image!")
return
# 查找匹配程度大于阈值的位置
loc = np.where(res >= threshold)
```
在这个示例中,如果`res`为空矩阵,就会输出一条错误信息并退出函数。如果`res`不为空,就会继续执行查找匹配位置的代码。