颜色空间将YCbCr映射到RGB [英] Color Space Mapping YCbCr to RGB

查看:160
本文介绍了颜色空间将YCbCr映射到RGB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python进行JPEG压缩.我加载一个tiff图像,并将其存储为numpy uint8 RGB数组.我这样做是为了进行颜色映射.

I am experimenting with JPEG compression using python. I load in a tiff image and store it as numpy uint8 RGB array. I was doing this for color mapping.

def rgb2ycbcr(im):
    cbcr = np.empty_like(im)
    r = im[:,:,0]
    g = im[:,:,1]
    b = im[:,:,2]
    # Y
    cbcr[:,:,0] = .299 * r + .587 * g + .114 * b
    # Cb
    cbcr[:,:,1] = 128 - .169 * r - .331 * g + .5 * b
    # Cr
    cbcr[:,:,2] = 128 + .5 * r - .419 * g - .081 * b
    return np.uint8(cbcr)

def ycbcr2rgb(im):
    rgb = np.empty_like(im)
    y   = im[:,:,0]
    cb  = im[:,:,1] - 128
    cr  = im[:,:,2] - 128
    # R
    rgb[:,:,0] = y + 1.402 * cr
    # G
    rgb[:,:,1] = y - .34414 * cb - .71414 * cr
    # B
    rgb[:,:,2] = y + 1.772 * cb
    return np.uint8(rgb)

我做了一个简单的从RGB到YCbCr的转换,然后进行了逆转换.

I did a simple RGB to YCbCr transformation followed with a inverse transformation.

img = rgb2ycbcr(img)
imshow(img)
img = ycbcr2rgb(img)
imshow(img)

经过色彩空间转换后,我得到了这两个输出图像,分别是YCbCr和RGB输出.

I got these two output image as YCbCr and RGB output after the color space transformation.

看来我的色彩转换出了点问题,我无法弄清楚出什么问题了.我正在使用由提供的JPEG色彩空间转换 维基百科.谢谢您的帮助.

It seems that something is wrong with my color conversion and I cannot figure out what is wrong. I was using the JPEG color space conversion provided by Wikipedia. Thanks you for the help.

推荐答案

您必须在浮点中进行中间计算.后代化应该给您提示.您有很多热"(饱和)像素.

You have to do your intermediate calculations in floating point. The posterization should tip you off; you have a lot of "hot" (saturated) pixels.

def rgb2ycbcr(im):
    xform = np.array([[.299, .587, .114], [-.1687, -.3313, .5], [.5, -.4187, -.0813]])
    ycbcr = im.dot(xform.T)
    ycbcr[:,:,[1,2]] += 128
    return np.uint8(ycbcr)

def ycbcr2rgb(im):
    xform = np.array([[1, 0, 1.402], [1, -0.34414, -.71414], [1, 1.772, 0]])
    rgb = im.astype(np.float)
    rgb[:,:,[1,2]] -= 128
    rgb = rgb.dot(xform.T)
    np.putmask(rgb, rgb > 255, 255)
    np.putmask(rgb, rgb < 0, 0)
    return np.uint8(rgb)

这篇关于颜色空间将YCbCr映射到RGB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆