登录
首页 >  Golang >  Go问答

OpenCV 相当于 np.where()

来源:stackoverflow

时间:2024-04-13 17:33:34 482浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《OpenCV 相当于 np.where()》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

当使用 gocv 包时,可以执行图像内模式的模板匹配。该包还提供 minmaxloc 函数来检索矩阵内最小值和最大值的位置。

但是,在下面的 python 示例中,作者使用 numpy.where 对矩阵进行阈值处理并获取多个最大值的位置。 python zip 函数用于将值粘合在一起,因此它们就像一个切片 [][2]int,内部切片是找到的匹配项的 xs 和 ys。

语法 loc[::-1] 反转数组。

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()。顾名思义,它查找图像中的非零元素,这就是 np.where () 在使用单个参数调用时执行此操作,如 the numpy docs 所示。

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

func findnonzero(src mat, idx *mat)

findnonzero 返回非零像素的位置列表。

更多详情请参阅:https://docs.opencv.org/master/d2/de8/group__core__array.html#gaed7df59a3539b4cc0fe5c9c8d7586190

注意:np.where() 按数组顺序返回索引,即 (row, col) 或 (i, j),这与典型的图像索引 (x, y) 相反。这就是为什么 loc 在 python 中是相反的。使用 findnonzero() 时,您不需要这样做,因为 opencv 始终使用 (x, y) 表示点。

对于遇到此问题的任何人,我希望有一个完整的示例,让您不必花几天时间将头撞在墙上,一遍又一遍地阅读相同的谷歌结果,直到有点击为止。

package main

import (
    "fmt"
    "image"
    "image/color"
    "os"

    "gocv.io/x/gocv"
)

func OpenImage(path string) (image.Image, error) {
    f, err := os.Open(path)
    if err != nil {
        return nil, err
    }
    defer f.Close()

    img, _, err := image.Decode(f)
    return img, err
}

func main() {
    src := gocv.IMRead("haystack.png", gocv.IMReadGrayScale)
    tgt := gocv.IMRead("needle.png", gocv.IMReadGrayScale)
    if src.Empty() {
        fmt.Printf("failed to read image")
        os.Exit(1)
    }
    if tgt.Empty() {
        fmt.Printf("failed to read image")
        os.Exit(1)
    }

    // Get image size
    tgtImg, _ := tgt.ToImage()
    iX, iY := tgtImg.Bounds().Size().X, tgtImg.Bounds().Size().Y

    // Perform a match template operation
    res := gocv.NewMat()
    gocv.MatchTemplate(src, tgt, &res, gocv.TmSqdiffNormed, gocv.NewMat())

    // Set a thresh hold. Using the `gocv.TmSqdiffNormed` confidence levels are
    // reversed. Meaning the lowest value is actually the greatest confidence.
    // So here I perform an Inverse Binary Threshold setting all values
    // above 0.16 to 1.
    thresh := gocv.NewMat()
    gocv.Threshold(res, &thresh, 0.16, 1.0, gocv.ThresholdBinaryInv)

    // Filter out all the non-zero values.
    gocv.FindNonZero(thresh, &res)

    // FindNonZero returns a list or vector of locations in the form of a gocv.Mat when using gocv.
    // There may be a better way to do this, but I iterate through each found location getting the int vector in value
    // at each row. I have to convert the returned int32 values into ints. Then draw a rectangle around each point.
    //
    // The result of get res.GetVeciAt(i, 0) is just a slice of x, y integers so each value can be accessed by
    // using slice/array syntax.
    for i := 0; i < res.Rows(); i++ {
        x, y := res.GetVeciAt(i, 0)[0], res.GetVeciAt(i, 0)[1]
        xi, yi := int(x), int(y)
        gocv.Rectangle(&src, image.Rect(xi, yi, xi+iX, yi+iY), color.RGBA{0, 0, 0, 1}, 2)
    }

    w := gocv.NewWindow("Test")
    w.IMShow(src)
    if w.WaitKey(0) > 1 {
        os.Exit(0)
    }
}

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>