python - 对 RGB 颜色分量执行 Sobel 滤镜

标签 python image-processing colors scikit-image

我正在尝试将图像分离为其 RGB 颜色分量,然后尝试对每个颜色分量图像执行 sobel h 和 v 过滤器。我不太确定问题是什么,但我收到以下除以 0 错误。我想这可能是因为我的 u 和 v 是完全相同的数组。

错误

/Users/Sam/PycharmProjects/temp/A2.py:51: RuntimeWarning: divide by zero encountered in true_divide
  theta = 0.5 * np.arctan(2 * gxy / (gxx - gyy))
/Users/Sam/PycharmProjects/temp/A2.py:51: RuntimeWarning: invalid value encountered in true_divide
  theta = 0.5 * np.arctan(2 * gxy / (gxx - gyy))
/Users/Sam/PycharmProjects/temp/A2.py:54: RuntimeWarning: invalid value encountered in sqrt
  fTheta = np.sqrt(0.5 * ((gxx + gyy) + (gxx - gyy) * np.cos(2 * theta) + (2 * gxy * np.sin(2 * theta))))
Traceback (most recent call last):
  File "/Users/Sam/PycharmProjects/A1/venv/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 51, in _wrapfunc
    return getattr(obj, method)(*args, **kwds)

代码

import skimage.filters as filt
import numpy as np
def color_dot_product(A, B):
    return np.sum(A.conj() * B, axis=2)


mushroom = io.imread('mushroom.jpg')
I = util.img_as_float(mushroom)
  red = I[:, :, 0]  # Zero out contribution from green
  blue = I[:,:,1]
  green = I[:,:,2]

  # Compute horizontal and vertical derivatives of red, blue and green channels through applying sobel filters
  u = I.copy()
  u[:, :, 0] = filt.sobel_h(red)
  u[:, :, 1] = filt.sobel_h(green)
  u[:, :, 2] = filt.sobel_h(blue)
  v = I.copy()
  v[:, :, 0] = filt.sobel_v(red)
  v[:, :, 1] = filt.sobel_v(green)
  v[:, :, 2] = filt.sobel_v(blue)
  gxx = color_dot_product(u, u)
  gyy = color_dot_product(v, v)
  gxy = color_dot_product(u, v)

  # Calculate gradient direction (direction of the largest colour change)
  theta = 0.5 * np.arctan(2 * gxy / (gxx - gyy))

  # Calculate the magnitude of the rate of change
  fTheta = np.sqrt(0.5 * ((gxx + gyy) + (gxx - gyy) * np.cos(2 * theta) + (2 * gxy * np.sin(2 * theta))))

最佳答案

当除以这样的图像时,很可能某些像素的值为零,因此您会得到除以零的结果。

通常可以通过在除法之前显式测试每个像素是否为零来避免这种情况,或者如果除数为非负数,则添加一个非常小的值。

但在这种情况下你根本不需要划分。函数atan2接受两个输入参数,因此 atan2(y,x) 相当于 atan(y/x)。除了它返回 (-π,π] 范围内的角度(即,它为您提供完整的 360 度角度范围)。我链接到上面的维基百科,因为 atan2 是一个通用函数,存在于所有语言。除了在 NumPy 中,它被称为 arctan2 (我猜想与众不同?这很奇怪?)。所以替换:

theta = 0.5 * np.arctan(2 * gxy / (gxx - gyy))

与:

theta = 0.5 * np.arctan2(2 * gxy, gxx - gyy)

您计算的 gxxgyygxy 三元组看起来很像结构张量。如果这就是您想要计算的内容,则需要为这三个组件中的每一个组件添加额外的模糊。这会导致梯度信息在本地进行平均,从而产生更少的零梯度位置。

关于python - 对 RGB 颜色分量执行 Sobel 滤镜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52901680/

相关文章:

python - 如果其中一个是字符串,如何对两个十六进制值进行异或?

python - 如何递归读取目录中的所有 html 文件?

python - 将二进制数据打包和解包到列表中的最快方法

matlab - 如何在 MATLAB 中将彩色图像转换为灰度图像?

jquery - 在一页网站的一点更改菜单颜色

python - 使用 ctypes 从共享库映射全局变量

php - 我的双线性插值算法有什么问题?

python - 在图像文件中将特定 RGB 颜色像素更改为另一种颜色

colors - xfce 终端配置中的 12 个十六进制数字颜色代码意味着什么?