提问者:小点点

如何使用OpenCV对一幅RGB图像中的灰度,SobelX和SobelY进行编码?


我有一张RGB图像。 我想将它保存为一个新的图像,其中灰度,SobelX和SobelY将保存在一个新图像的R,G和B通道中。 如何在OpenCV中做这样的事情?

换句话说,假设我们有RBGimage,我们想要创建一个新的RGB(或者BGR不重要)图像,它将在其通道中包含灰度值(在B中),sobelX(在R中)sobelY(在G中)。 主要的问题是我们需要将Sobel量化到0-256的值。。。 怎么做这种事?


共1个答案

匿名用户

这将是一种方法。 CV2.split将分隔三个通道(b,g,r)。 Rest只是循环和计算sobel输出。

import cv2
import numpy as np
import os
###reading image
image_name='tmp1.jpg'
image=cv2.imread(image_name)
###splitting b,g,r channels
gray_images=cv2.split(image)
channels={0:'B',1:'G',2:'R'}
###defining output paths
out_path='out_bgr'
os.makedirs(out_path,exist_ok=True)
for i,gray in enumerate(gray_images):
    cv2.imwrite(os.path.join(out_path,"gray_{}_{}".format(channels[i],image_name)),gray)
    ###writing each channel grayscale,sobelx,sobelY and writing to system 
    sobelx = cv2.Sobel(gray,cv2.CV_64F,1,0,ksize=5)
    sobely = cv2.Sobel(gray,cv2.CV_64F,0,1,ksize=5)
    cv2.imwrite(os.path.join(out_path,"sobelX_{}_{}".format(channels[i],image_name)),sobelx)
    cv2.imwrite(os.path.join(out_path,"sobelY_{}_{}".format(channels[i],image_name)),sobely)