gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:05:19 25 4
gpt4 key购买 nike

我有一个 RGB 图像。我想将其另存为新图像,其中 Grayscale , SobelX and SobelY将保存在新图像的 R、G 和 B channel 中。如何在 OpenCV 中做这样的事情?

换句话说,假设我们有 RBG image,我们想要创建一个新的 RGB(或 BGR 无关紧要)图像,该图像将在其 channel 中包含灰度值(在 B 中)、sobelX ( R)sobelY(G)。主要问题是我们需要以某种方式将 Sobel 量化\归一化为 0-256 值...如何做这样的事情?

感谢@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)

最佳答案

将图像加载为灰度图像(IMREAD_GRAYSCALE):

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

分别创建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)))

使用源图像的大小创建一个空的numpy数组,并将灰度、sobel-X和sobel-Y分配给目标图像的 channel :

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

或者merge图像:

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

分别使用numpy.dstack :

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

一起:

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)

关于python - 如何使用 OpenCV 在一张 RGB 图像中编码灰度、SobelX 和 SobelY?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62742031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com