在OpenCV中,cv2.filter2D()需要什么数据类型? [英] In OpenCV, what data types does cv2.filter2D() expect?

查看:390
本文介绍了在OpenCV中,cv2.filter2D()需要什么数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自学边缘检测器,并且尝试使用OpenCV的 filter2D 来实现自己的渐变计算器,类似于 cv2 .Sobel()。在OpenCV的Python界面中, cv2.filter2D()允许用户使用自定义滤镜对图像进行卷积。在OpenCV命名法中,此过滤器称为内核。

I'm teaching myself about edge detectors, and I'm trying to use OpenCV's filter2D to implement my own gradient calculator, similar to cv2.Sobel(). In the Python interface to OpenCV, cv2.filter2D() allows users to convolve an image with a custom filter. In OpenCV nomenclature, this filter is called a "kernel."

使用图片( per00001.png )从 MIT行人数据集,我发现 cv2.Sobel()产生了合理的输出。 (下面的代码是输出图像在此处。)

Using an image (per00001.png) from the MIT pedestrian dataset, I find that cv2.Sobel() produces a reasonable looking output. (Code is below, output image is here.)

#OpenCV's Sobel code (outputs nice-looking gradient)
import cv2, numpy
img = cv2.imread("./per00001.png")

gradientX = cv2.Sobel(img, -1, 1, 0)

compression_params = [cv2.cv.CV_IMWRITE_PNG_COMPRESSION, 9]
cv2.imwrite("gradientX.png", gradientX, compression_params)

↑良好

↓破碎

当我尝试实现自己的类似于 Sobel()的代码(如下)时,我得到一个全黑图像。我推测问题出在我传递给 cv2.filter2D()<的内核参数的数据类型( horizo​​ntalSobelMtx ) / code>。但是,我找不到关于 cv2.filter2D()的内核数据类型的任何文档。

When I try to implement my own Sobel()-like code (below), I get an all-black image. I'm speculating that the problem is with the data type of the kernel parameter (horizontalSobelMtx) that I'm passing into cv2.filter2D(). However, I haven't been able to find any documentation about the kernel data type for cv2.filter2D().

#Custom Sobel code (outputs all-black image)
import cv2, numpy
img = cv2.imread("./per00001.png")

horizontalSobelMtx = [[-1,0,1],[-2,0,2],[-1,0,1]]
horizontalSobelMtx = numpy.asanyarray(horizontalSobelMtx) #guessing about appropriate datatype.
gradientX_customSobel = cv2.filter2D(img, -1, horizontalSobelMtx)

compression_params = [cv2.cv.CV_IMWRITE_PNG_COMPRESSION, 9]
cv2.imwrite("gradientX_customSobel.png", gradientX_customSobel, compression_params)

所以,这是我的问题:

1) cv2.filter2D(...,kernel,...)内核期望什么数据类型参数?

2)如果 kernel 的数据类型不是这里的问题,那是什么导致我的自定义Sobel代码输出空白图像?

2) If the data type of kernel isn't the problem here, then what's causing my custom Sobel code to output a blank image?

推荐答案

卷积核的系数应始终为浮点型-
点数。这意味着分配该矩阵时应使用CV_32FC1。
在此特定示例中,尝试:

The coefficients of the convolution kernel should always be floating- point numbers. This means that you should use CV_32FC1 when allocating that matrix. In this particular example, try:

horizontalSobelMtx = [[-1,0,1],[-2,0,2],[-1,0,1]]
horizontalSobelMtx = numpy.asanyarray(horizontalSobelMtx, np.float32)

这篇关于在OpenCV中,cv2.filter2D()需要什么数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆