在Sobel算子中实现角度约束

时间:2016-11-08 14:09:57

标签: python opencv image-processing computer-vision

在这个问题上,我有一些与边缘检测相关的疑问。

1)我在下面写的代码试图只显示那些服从某种大小和方向约束的边。 当我使用numpy方法时,显示图像的opencv函数仅显示黑色。 在show_angle函数中,当我使用for循环实现它并使用cv2.imshow显示图像时。

然后我使用numpy方法检查了输出,使用返回np.array_equal的{​​{1}}检查了我的for循环。 这背后可能是什么原因?

2)我无法处理角度约束,我会针对不同的角度约束发布一些图像。

True

输入图片:

hexagon image

图像直方图:

Image histogram for the hexagon.

某些约束的输出:

0到90度

0 to 90 degrees

90到180度

90 to 180 degrees

感谢。

1 个答案:

答案 0 :(得分:0)

好吧,我发现了错误。

我的代码有三个问题:

1)在show_angle函数中,numpy运算符应该大于等于或小于或等于比较。

2)在用于将rads转换为度数的公式中,我没有除以pi

3)我应该将numpy矩阵转换为uint8类型。

更正的代码:

import cv2

import numpy as np

import matplotlib.pyplot as plt

import math

def show_image(name, img, waitkey=0):
    cv2.namedWindow(name, 0)
    cv2.imshow(name, img)
    cv2.waitKey(waitkey)
    cv2.destroyWindow(name)

img = cv2.imread('hex2.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

shape = img.shape

out_x = cv2.Sobel(img, cv2.CV_16S, 1, 0)    # x gradient
out_y = cv2.Sobel(img, cv2.CV_16S, 0, 1)    # y gradient


out_x = cv2.convertScaleAbs(out_x)
out_y = cv2.convertScaleAbs(out_y)

out_weight = cv2.addWeighted(out_x, 0.5, out_y, 0.5,0)  # x and y weighted


def show_angle(out_weight, mag_final, dir_final, min_mag, theta_min, theta_max):
    """
        Return points based on magnitude and angle constraints
    """


    out_img = np.multiply(
        (
            # (mag_final > min_mag) &
            (dir_final >= theta_min) &
            (dir_final <= theta_max)
        ).astype(int),

        out_weight
    ).astype('uint8')

    return out_img

def mag_dir():
    """
    Calculate gradient magnitude and direction matrix
    """

    mag = np.sqrt(
                np.add
                     (
                    np.square(out_x) , np.square(out_y)
                      )
                 )

    dir = np.arctan2(out_y, out_x)

    dir = np.multiply(dir, 180/math.pi)

    print np.min(dir)   # 0
    print np.max(dir)   # 89

    # plt.hist(mag,8)
    # plt.show()

    return mag, dir

mag, dir = mag_dir()


out_final = show_angle(out_weight, mag, dir, 1, 60, 90)
show_image("angle", out_final, 0)