OpenCV中的梯度定向

2024-05-19 01:45:09 发布

您现在位置:Python中文网/ 问答频道 /正文

通过Sobel算子,我已经能够确定图像的梯度大小。我在下面展示:

GradMag

现在我想确定梯度方向。为此,我遵循thispost,它使用了函数cv2.phase。然后,根据函数返回的度数,将角度硬编码为特定颜色。我的问题是这个函数返回的值在0到90度之间。因此,我得到的图像只有红色和青色。在

我的代码如下:

# where gray_blur is a grayscale image of dimension 512 by 512

# 3x3 sobel filters for edge detection
sobel_x = np.array([[ -1, 0, 1], 
                   [ -2, 0, 2], 
                   [ -1, 0, 1]])


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


# Filter the blurred grayscale images using filter2D

filtered_blurred_x = cv2.filter2D(gray_blur, -1, sobel_x)  
filtered_blurred_y = cv2.filter2D(gray_blur, -1, sobel_y)

# Compute the orientation of the image
orien = cv2.phase(np.array(filtered_blurred_x, np.float32), np.array(filtered_blurred_y, dtype=np.float32), angleInDegrees=True)

image_map = np.zeros((orien.shape[0], orien.shape[1], 3), dtype=np.int16)

# Define RGB colours
red = np.array([255, 0, 0])
cyan = np.array([0, 255, 255])
green = np.array([0, 255, 0])
yellow = np.array([255, 255, 0])

# Set colours corresponding to angles
for i in range(0, image_map.shape[0]):
    for j in range(0, image_map.shape[1]):
        if orien[i][j] < 90.0:
            image_map[i, j, :] = red
        elif orien[i][j] >= 90.0 and orien[i][j] < 180.0:
            image_map[i, j, :] = cyan
        elif orien[i][j] >= 180.0 and orien[i][j] < 270.0:
            image_map[i, j, :] = green
        elif orien[i][j] >= 270.0 and orien[i][j] < 360.0:
            image_map[i, j, :] = yellow

# Display gradient orientation
f, ax1 = plt.subplots(1, 1, figsize=(20,10))

ax1.set_title('gradient orientation')
ax1.imshow(image_map)

显示图像:

Orien

提前谢谢。在


Tags: 函数图像imagemapfornparraycv2
1条回答
网友
1楼 · 发布于 2024-05-19 01:45:09

cv2.filter2Dddepth参数很重要。将其设置为-1,这意味着过滤后的图像将具有与输入相同的深度。gray_blur似乎是一个无符号整数(可能是uint8),因此过滤器输出也是。在

因为你的过滤器会产生负值,所以它们会在uint8下流动。设置ddepth以接收过滤器的完整值范围:

filtered_blurred_x = cv2.filter2D(gray_blur, cv2.CV_32F, sobel_x)  
filtered_blurred_y = cv2.filter2D(gray_blur, cv2.CV_32F, sobel_y)

有了这个,你的过滤图像现在编码一个方向,这个方向将映射完整的360度。在

相关问题 更多 >

    热门问题