如何在Python OpenCV中显示彩色Y Cb Cr通道?

tquggr8v  于 2022-11-15  发布在  Python
关注(0)|答案(2)|浏览(360)

我知道如何使用cvtColor()将BGR图像转换为YCrCb格式,并在OpenCV中使用split()分离不同通道。但是,这些通道显示为灰度图像:

imgYCrCB = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
Y, Cr, Cb = cv2.split(imgYCrCB)
cv2.imshow("Y", Y)
cv2.imshow("Cr", Cr)
cv2.imshow("Cb", Cb)
cv2.waitKey(0)

此代码给予以下结果:
灰度图像:

我想显示Cb和Cr通道的颜色,如下图所示:

我该怎么做?

hl0ma9xz

hl0ma9xz1#

获得显示CbCr的假色效果的技巧相对简单:

  • 对于Cb假色:

用值128填充YCr,并转换回BGR。

  • 对于Cr假色:

用值128填充YCb,并转换回BGR。

  • Y保持灰度格式。

值128会将中间灰色套用至Y。
当Cb=128时,没有“蓝色调”(Cb是“中性的”)。
当Cr=128时,没有“红色调”(Cr为“中性”)。
代码示例:

import cv2
import numpy as np

img = cv2.imread('rgb.png')  # Read input image in BGR format

imgYCrCB = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)  # Convert RGB to YCrCb (Cb appiles V, and Cr applies U).

Y, Cr, Cb = cv2.split(imgYCrCB)

# Fill Y and Cb with 128 (Y level is middle gray, and Cb is "neutralized").
onlyCr = imgYCrCB.copy()
onlyCr[:, :, 0] = 128
onlyCr[:, :, 2] = 128
onlyCr_as_bgr = cv2.cvtColor(onlyCr, cv2.COLOR_YCrCb2BGR)  # Convert to BGR - used for display as false color

# Fill Y and Cr with 128 (Y level is middle gray, and Cr is "neutralized").
onlyCb = imgYCrCB.copy()
onlyCb[:, :, 0] = 128
onlyCb[:, :, 1] = 128
onlyCb_as_bgr = cv2.cvtColor(onlyCb, cv2.COLOR_YCrCb2BGR)  # Convert to BGR - used for display as false color

cv2.imshow('img', img)
cv2.imshow('Y', Y)
cv2.imshow('onlyCb_as_bgr', onlyCb_as_bgr)
cv2.imshow('onlyCr_as_bgr', onlyCr_as_bgr)
cv2.waitKey()
cv2.destroyAllWindows()

cv2.imwrite('Y.png', Y)
cv2.imwrite('onlyCb_as_bgr.png', onlyCb_as_bgr)
cv2.imwrite('onlyCr_as_bgr.png', onlyCr_as_bgr)

Y

onlyCb_as_bgr

onlyCr_as_bgr

s5a0g9ez

s5a0g9ez2#

这里有一个简单的方法,通过使用通道、反转通道和Python/OpenCV中的中灰度图像来组合通道。
输入:

import cv2
import numpy as np 

# read image
img = cv2.imread('barn.jpg')
hh, ww = img.shape[:2]

# convert to YCbCr
YCrCb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)

# separate channels
Y, Cr, Cb = cv2.split(YCrCb)

# create a mid-gray constant image
gray = np.full((hh,ww), 128, dtype=np.uint8)

# invert Cr and Cb
Cr_inv = cv2.bitwise_not(Cr)
Cb_inv = cv2.bitwise_not(Cb)

# combine channels to get the Cr and Cb colorized images as if BGR
Cr_colored = cv2.merge([gray, Cr_inv, Cr])
Cb_colored = cv2.merge([Cb, Cb_inv, gray])
Y_colored = cv2.merge([Y, Y, Y])

# save results
cv2.imwrite('Y_colored.png', Y_colored)
cv2.imwrite('Cr_colored.png', Cr_colored)
cv2.imwrite('Cb_colored.png', Cb_colored)

# show results
cv2.imshow('Y_colored', Y_colored)
cv2.imshow('Cr_colored', Cr_colored)
cv2.imshow('Cb_colored', Cb_colored)
cv2.waitKey()

Y:

铬:

Cb:

相关问题