【问题标题】:How to get the same output of rgb2ycbcr() matlab function in python-opencv?如何在 python-opencv 中获得 rgb2ycbcr() matlab 函数的相同输出?
【发布时间】:2014-12-16 06:57:25
【问题描述】:

我正在使用此代码从 matlab 中的图像中提取亮度:

I = imread('image.bmp');
I = rgb2ycbcr(I);
I = I[:, :, 1];
save(I, 'ycbcr_image');

图片如下: 这是output mat
我想在 opencv-python 中复制这段代码,这是我的实现:

def to_matlab_ycbcr(image):
  # http://stackoverflow.com/questions/26078281/why-luma-parameter-differs-in-opencv-and-matlab
  return clip(16 + (219 / 255.0) * image, 0, 255)

original = image_open(local_path('image.bmp'))
matlab = scipy.io.loadmat(local_path('ycbcr.mat'))
matlab = matlab['ycbcr_image']
transformed = cv2.cvtColor(original, cv2.COLOR_BGR2YCR_CB)
transformed = transformed[:, :, 0]
result = to_matlab_ycbcr(transformed)
error = np.mean(np.abs(result - matlab))

我的错误平均为 12。你知道如何解决这个问题吗?

附:我正在使用 python 2.7.5opencv 2.4.9

【问题讨论】:

标签: matlab opencv image-processing numpy matrix


【解决方案1】:

使用此代码

def rgb2ycbcr(im_rgb):
 im_rgb = im_rgb.astype(np.float32)
 im_ycrcb = cv2.cvtColor(im_rgb, cv2.COLOR_RGB2YCR_CB)
 im_ycbcr = im_ycrcb[:,:,(0,2,1)].astype(np.float32)
 im_ycbcr[:,:,0] = (im_ycbcr[:,:,0]*(235-16)+16)/255.0 #to [16/255, 235/255]
 im_ycbcr[:,:,1:] = (im_ycbcr[:,:,1:]*(240-16)+16)/255.0 #to [16/255, 240/255]
 return im_ycbcr

也许你会想要这段代码

def ycbcr2rgb(im_ycbcr):
 im_ycbcr = im_ycbcr.astype(np.float32)
 im_ycbcr[:,:,0] = (im_ycbcr[:,:,0]*255.0-16)/(235-16) #to [0, 1]
 im_ycbcr[:,:,1:] = (im_ycbcr[:,:,1:]*255.0-16)/(240-16) #to [0, 1]
 im_ycrcb = im_ycbcr[:,:,(0,2,1)].astype(np.float32)
 im_rgb = cv2.cvtColor(im_ycrcb, cv2.COLOR_YCR_CB2RGB)
 return im_rgb

【讨论】:

  • 提醒:OpenCV 默认为 BGR 而不是 RGB,但此代码采用 RGB(但当你给它 BGR 时,乍一看并没有给出非常明显的错误!)。我知道这就像 OpenCV 101,但愚蠢的我花了两个小时才弄明白。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 2021-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多