import cv2 as cv import numpy as np #Y = 0.299*R + 0.587*G + 0.114*B #Cb = 128 + 0.5*B + -0.331264*G + -0.168736*R #Cr = 128 + -0.081312*B + -0.418688*G + 0.5*R def BGR2YCbCr(bgrimg): ycbcrimg = np.empty(bgrimg.shape,dtype=np.float) for r in range(bgrimg.shape[0]): for c in range(bgrimg.shape[1]): #y = 0.299*bgrimg[r,c,2] + 0.587*bgrimg[r,c,1] + 0.114*bgrimg[r,c,0] y = sum(bgrimg[r,c]*np.array([0.114, 0.587, 0.299])) cb = 128 + sum(bgrimg[r,c]*np.array([0.5, -0.331264, -0.168736])) cr = 128 + sum(bgrimg[r,c]*np.array([-0.081312, -0.418688, 0.5])) ycbcrimg[r,c] = np.array([y,cb,cr]) return ycbcrimg #R = Y + 1.402 * (Cr - 128) #G = Y - 0.344136 * (Cb - 128) + -0.714136 * (Cr - 128) #B = Y + 1.772 * (Cb - 128) def YCbCr2BGR(ycbcrimg): bgrimg = np.empty(ycbcrimg.shape,dtype=np.uint8) for r in range(ycbcrimg.shape[0]): for c in range(ycbcrimg.shape[1]): red = int(ycbcrimg[r,c,0] + 1.402 * (ycbcrimg[r,c,2] - 128)) if red < 0: red = 0 else: if red > 255: red = 255 green = int(ycbcrimg[r,c,0] - 0.344136 * (ycbcrimg[r,c,1] - 128)) + -0.714136 * (ycbcrimg[r,c,2] - 128) if green < 0: green = 0 else: if green > 255: green = 255 blue = int(ycbcrimg[r,c,0] + 1.772 * (ycbcrimg[r,c,1] - 128)) if blue < 0: blue = 0 else: if blue > 255: blue = 255 bgrimg[r,c] = np.array([blue, green, red]) return bgrimg inimg = cv.imread('bball.jpg') cv.imshow('Input image', inimg) k = cv.waitKey(0) cv.destroyAllWindows() ycbcrinimg = BGR2YCbCr(inimg) gaussian13sd5 = cv.getGaussianKernel(13, 5) gaussianmask = gaussian13sd5.transpose() * gaussian13sd5 grayblur = cv.filter2D(ycbcrinimg[:,:,0], -1, gaussianmask) ycbcrinimg[:,:,0] = grayblur bgroutimg = YCbCr2BGR(ycbcrinimg) cv.imshow('Original', inimg) cv.imshow('blurred (first converted to YCbCr, then blurred Y)', bgroutimg) cv.waitKey(0) cv.destroyAllWindows() cv.imwrite('blurredimg.jpg', bgroutimg)