Python中彩色图像的渐变

时间:2019-06-04 12:30:31

标签: python image-processing scikit-image

我正在尝试使用python中的skimage确定彩色图像的渐变图像。

我要遵循的方法是:

1)对于每个RGB波段,计算每个波段的梯度。这将导致6个阵列,每个色带2个。每个色带在x和y方向上都有一个渐变。 (2个方向x 3种颜色= 6个数组)。

2)要确定图像的渐变,请计算每个色带的大小,如下所示:

渐变=((Rx ^ 2 + Ry ^ 2)+(Gx ^ 2 + Gy ^ 2)+(Bx ^ 2 + By ^ 2))^ 0.5

但是结果非常嘈杂,并且梯度不清楚。

import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as nd
import skimage.data as dt

img = dt.astronaut()

def gradient(img, x = True, y = True):

      f1 = np.array([[-1,-2,-1], [0,0,0], [1,2,1]])
      f2 = np.array([[-1,-2,-1], [0,0,0], [1,2,1]]).T

      vert_gradient =nd.correlate(img, f1)
      horz_gradient =nd.correlate(img, f2)

      if x:
          return(horz_gradient)
      else:
          return (vert_gradient)

Rx = gradient(img[:,:,0], y = False)
Ry = gradient(img[:,:,0], x = False)
Gx = gradient(img[:,:,1], y = False)
Gy = gradient(img[:,:,1], x = False)
Bx = gradient(img[:,:,2], y = False)
By = gradient(img[:,:,2], x = False)

grad = np.sqrt(np.square(Rx) + np.square(Ry)) + np.sqrt(np.square(Gx) +        np.square(Gy)) + np.sqrt(np.square(Bx) + np.square(By))
grad = ((grad - grad.min()) / (grad.max() - grad.min())) * 255 # rescale for full dynamic range for 8 bit image
grad = grad.astype(np.uint8)

plt.subplot(1,2,1)
plt.imshow(img)
plt.subplot(1,2,2)
plt.imshow(grad)
plt.show()

在渐变图像中我们可以看到颜色渐变,但是它们不是很清晰,并且有很多噪点。

在计算梯度之前,我还尝试过平滑每个色带上的噪声。

如何在不使用OpenCv的情况下改善此结果?

Original versus gradient image,

1 个答案:

答案 0 :(得分:0)

像这样分别查找每个通道的渐变

gradR = np.sqrt(np.square(Rx) + np.square(Ry))
gradG = np.sqrt(np.square(Gx) + np.square(Gy))
gradB = np.sqrt(np.square(Bx) + np.square(By))

制作新图片

grad = np.dstack((gradR,gradG,gradB))
相关问题