相当于 np.where() 的 OpenCV

OpenCV equivalent of np.where()

当使用 gocv package it is possible, for example, to perform template matching of a pattern within an image. The package also provide the MinMaxLoc 函数检索矩阵中最小值和最大值的位置时。

然而,在下面的 python 示例中,作者使用 numpy.Where to threshold the matrix and get locations of multiple maximums. The python zip 函数将值粘合在一起,因此它们就像一个切片 [][2]int,内部切片是 xs 和 ys找到的匹配项。

语法loc[::-1]reverses数组

zip(*loc..) 中的星号运算符用于解压缩提供给 zip 的切片。

https://docs.opencv.org/master/d4/dc6/tutorial_py_template_matching.html

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

img_rgb = cv.imread('mario.png')
img_gray = cv.cvtColor(img_rgb, cv.COLOR_BGR2GRAY)
template = cv.imread('mario_coin.png',0)
w, h = template.shape[::-1]
res = cv.matchTemplate(img_gray,template,cv.TM_CCOEFF_NORMED)
threshold = 0.8
loc = np.where( res >= threshold)

for pt in zip(*loc[::-1]):
    cv.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0,0,255), 2)
cv.imwrite('res.png',img_rgb)

如何在 Go 中实现相同的 np.where 算法以在应用阈值后获取多个位置?

OpenCV 有一个内置的(半)等价于 np.where() 的函数,即 findNonZero(). As implied by the name, it finds the non-zero elements in an image, which is what np.where() does when called with a single argument, as the numpy docs 状态。

这在 golang 绑定中也可用。来自 gocv docs on FindNonZero:

func FindNonZero(src Mat, idx *Mat)

FindNonZero returns the list of locations of non-zero pixels.

For further details, please see: https://docs.opencv.org/master/d2/de8/group__core__array.html#gaed7df59a3539b4cc0fe5c9c8d7586190

注意:np.where() returns 数组顺序索引,即(行,列)或(i,j),这与典型的图像索引(x,y)相反。这就是 loc 在 Python 中反转的原因。使用 findNonZero() 时,您不需要这样做,因为 OpenCV 始终使用 (x, y) 作为点。