简体   繁体   English

如何使用 OpenCV 在一张 RGB 图像中编码灰度、SobelX 和 SobelY?

[英]How to encode Grayscale, SobelX and SobelY in one RGB image using OpenCV?

I have an RGB image.我有一个 RGB 图像。 I want to save it as a new image where Grayscale , SobelX and SobelY would be saved in R, G and B channels of a new image.我想将其保存为新图像,其中GrayscaleSobelX 和 SobelY将保存在新图像的 R、G 和 B 通道中。 How to do such thing in OpenCV?如何在 OpenCV 中做这样的事情?

In other words, say we had RBG image , we wanted to create a new RGB (or BGR does not matter) image which would contain in its channels Grayscale values (in B), sobelX (in R) sobelY (in G).换句话说,假设我们有 RBG image ,我们想要创建一个新的 RGB(或 BGR 无关紧要)图像,该图像将在其通道中包含灰度值(在 B 中)、sobelX(在 R 中)sobelY(在 G 中)。 Main problem is that we need to somehow quantize\normalise Sobel to 0-256 values... How to do such thing?主要问题是我们需要以某种方式将 Sobel 量化\标准化为 0-256 值......如何做这样的事情?

Thanks to @Rabbid79 ended up with:感谢@Rabbid79 最终得到:

%matplotlib inline
from matplotlib import pyplot as plt
import cv2
import numpy as np
!wget "https://helpx.adobe.com/content/dam/help/en/stock/how-to/visual-reverse-image-search/jcr_content/main-pars/image/visual-reverse-image-search-v2_intro.jpg" -O dt.jpg

src = cv2.imread('./dt.jpg', cv2.IMREAD_GRAYSCALE)
def show(im):
  plt.imshow(im)
  plt.show()

show(src)
sobelx = cv2.Sobel(src, cv2.CV_64F, 1, 0)
sobely = cv2.Sobel(src, cv2.CV_64F, 0, 1)

abs_grad_x = cv2.convertScaleAbs(sobelx)
abs_grad_y = cv2.convertScaleAbs(sobely)
grad = cv2.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)
show(grad)
b = cv2.GaussianBlur(src,(3,3),0)
laplacian = cv2.Laplacian(b,cv2.CV_64F)
l_dst = cv2.convertScaleAbs( laplacian  );
show(l_dst)
dest = np.dstack([src, l_dst, grad]).astype(np.uint8)
show(dest)

Load the image as gray scale image ( IMREAD_GRAYSCALE ):将图像加载为灰度图像( IMREAD_GRAYSCALE ):

gray = cv2.imread(image_name, cv2.IMREAD_GRAYSCALE)

Create a sobel-X respectively sobel-Y分别创建一个 sobel-X 和 sobel-Y

sobelx = cv2.convertScaleAbs((cv2.Sobel(gray, cv2.CV_64F, 1, 0)))
sobely = cv2.convertScaleAbs((cv2.Sobel(gray, cv2.CV_64F, 0, 1)))

Create an empty numpy array with the size of the source image and assign the gray scale, sobel-X and sobel-Y to the channels of the target image:使用源图像的大小创建一个空的numpy数组,并将灰度、sobel-X 和 sobel-Y 分配给目标图像的通道:

dest = np.empty((gray.shape[0], gray.shape[1], 3), np.uint8)
dest[:,:,0] = gray
dest[:,:,1] = sobelx
dest[:,:,2] = sobely

Or merge the images:merge图像:

dest = cv2.merge((gray, sobelx, sobely))

Respectively use numpy.dstack :分别使用numpy.dstack

dest = np.dstack([gray, sobelx, sobely]).astype(np.uint8)

All together:全部一起:

gray   = cv2.imread(image_name, cv2.IMREAD_GRAYSCALE)
sobelx = cv2.convertScaleAbs((cv2.Sobel(gray, cv2.CV_64F, 1, 0)))
sobely = cv2.convertScaleAbs((cv2.Sobel(gray, cv2.CV_64F, 0, 1)))
dest   = np.dstack([gray, sobelx, sobely]).astype(np.uint8)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM