1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| import matplotlib.pyplot as plt import numpy as np import cv2 import copy
def rgb2ycbcr(rgb): m = np.array([[ 0.299, 0.587, 0.114], [-0.1686, -0.3311, 0.4997], [ 0.4998, -0.4185, -0.0813]]) shape = rgb.shape if len(shape) == 3: rgb = rgb.reshape((shape[0] * shape[1], 3)) ycbcr = np.dot(rgb, m.transpose()) return ycbcr.reshape(shape)
def ycbcr2rgb(ycbcr): m = np.array([[ 1,0, 1.402], [1, -0.344, -0.714], [ 1, 1.772, 0]]) shape = ycbcr.shape if len(shape) == 3: ycbcr = ycbcr.reshape((shape[0] * shape[1], 3)) rgb = copy.deepcopy(ycbcr) rgb = np.dot(ycbcr, m.transpose()) return rgb.reshape(shape)
def main(): img1 = cv2.imread('./yuv.jpg')[:,:,(2,1,0)] img2=rgb2ycbcr(img1) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.subplot(221) plt.imshow(img1) plt.title('RGB原图') plt.axis('off')
plt.subplot(222) img2=rgb2ycbcr(img1) img2[:,:,1]=0 img2[:,:,2]=0 img3=ycbcr2rgb(img2) img3=img3.astype(np.uint8) plt.imshow(img3) plt.title('Y通道') plt.axis('off')
plt.subplot(223) img2=rgb2ycbcr(img1) img2[:,:,0]=0 img2[:,:,2]=0 img4=ycbcr2rgb(img2) img4=img4.astype(np.uint8) plt.imshow(img4) plt.title('Cb通道') plt.axis('off')
plt.subplot(224) img2=rgb2ycbcr(img1) img2[:,:,0]=0 img2[:,:,1]=0 img5=ycbcr2rgb(img2) img5=img5.astype(np.uint8) plt.imshow(img5) plt.title('Cr通道') plt.axis('off')
plt.tight_layout() plt.show()
if __name__ =='__main__': main()
|