如何使用 OpenCV 将梯度/幅度应用于图像?

问题描述

我目前正在关注 this tutorial 作为大学作业的一部分,我们应该自己实现精明的边缘检测。应用高斯模糊没有任何问题,但现在我正在尝试显示网站上显示的幅度强度。

我实现了在提到的网站上看到的功能,并创建了一个运行精明边缘检测的功能。目前这是该功能的样子:

def canny_edge(img):
    noise_reduction = cv.filter2D(img,-1,gaussian_kernel(5))
    cv.imshow('Blur',noise_reduction)
    magnitude,gradient = sobel_filters(img)
    magnitude = magnitude.astype(np.uint8)
    sobel = magnitude * gradient
    sobel = sobel.astype(np.uint8)
    test = img + (255 - gradient * noise_reduction)
    plt.imshow(gradient,cmap='gray')
    plt.show()
    cv.imshow('Gradient',magnitude)
    cv.imshow('Original Image',img)

我必须将幅度和 sobel 数组转换为 np.uint8,否则它们会包含 float 值,这会导致显示图像时出错。目前,我正在使用变量 test 来尝试各种事情,例如 gradient - noise_reduction、您在上面看到的行等。问题是我总是得到与这些相似的图像(图像在左侧显示 test,右侧图像显示 gradient底部图像显示 magnitude):

enter image description here

enter image description here

enter image description here

我不太熟悉所有可用的 OpenCV 函数,但我想也许为此目的使用一些我不知道的函数可能很重要。不幸的是,我无法在上面链接的教程中找到有关如何将 sobel_filters 函数返回的幅度应用于图像的任何信息。预先感谢您提供有关如何解决此问题的任何意见。

解决方法

我认为 ndimage.filters.convolve 可能存在问题。我得到了和你类似的结果。但以下似乎使用 Python/OpenCV 可以正常工作

输入:

enter image description here

import cv2
import numpy as np
import skimage.exposure

img = cv2.imread('black_dress.png',cv2.IMREAD_GRAYSCALE)

img = cv2.GaussianBlur(img,(0,0),sigmaX=1.5,sigmaY=1.5)

Kx = np.array([[-1,1],[-2,2],[-1,1]])
Ky = np.array([[1,2,[0,0],-2,-1]])

Ix = cv2.filter2D(img,-1,Kx)
Iy = cv2.filter2D(img,Ky)

G = np.hypot(Ix,Iy)
G = skimage.exposure.rescale_intensity(G,in_range='image',out_range=(0,255)).astype(np.uint8)

theta = np.arctan2(Iy,Ix)
theta = skimage.exposure.rescale_intensity(theta,255)).astype(np.uint8)
   
cv2.imwrite('black_dress_gradient_magnitude.png',G)
cv2.imwrite('black_dress_gradient_direction.png',theta)

cv2.imshow("magnitude",G)
cv2.imshow("direction",theta)
cv2.waitKey(0)

幅度:

enter image description here

方向:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...