Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)

本文主要运用用Python代码实现了5种彩色空间之间的转换!

具体而言,包括:

  • 1)RGB → CMY;
  • 2)  CMY → RGB;
  • 3)  RGB → HSI;
  • 4)  HSI → RGB;
  • 5)  RGB → YIQ;
  • 6)  YIQ → RGB;
  • 7)  RGB → YUV;
  • 8)  YUV → RGB;
  • 9)  RGB → YCbCr;
  • 10) YCbCr → RGB;

文末还附有两方面的扩展:

  • 1)对“多图”的处理
  • 2)对“视频”的处理

快来一起交流学习吧!

目录

1 RGB → CMY

1.1 转换公式

1.2 代码实现 

1.3 运行结果 

2 CMY → RGB

2.1 公式转换

2.2 代码实现

2.3 运行效果

3 RGB → HSI

3.1 公式转换

3.2 代码实现

3.3 运行效果

4 HSI → RGB

4.1 公式转换

4.2 代码实现

4.3 运行效果

5 RGB → YIQ

5.1 公式转换

5.2 代码实现

5.3 运行效果

6 YIQ → RGB

6.1 公式转换

6.2 代码实现

6.3 运行效果

7 RGB → YUV

7.1 公式转换

7.2 代码实现

7.3 运行效果

8 YUV → RGB

8.1 公式转换

8.2 代码实现

8.3 运行效果

9 RGB → YCbCr

9.1 公式转换

9.2 代码实现

9.3 运行效果

10 YCbCr → RGB

10.1 公式转换

10.2 代码实现

10.3 运行效果

11 扩展1——多图处理

11.1 代码示例

11.2 运行效果

12 扩展2——视频处理

12.1 附:视频爬取代码

12.2 代码实现

12.3 运行效果


1 RGB → CMY

1.1 转换公式

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第1张图片

1.2 代码实现 

'''-----------------RGB → CMY------------------------'''
import cv2
import imutils

def rgb_cmy(img):
    r, g, b = cv2.split(img)  # split the channels
    # normalization [0,1]
    r = r / 255.0
    g = g / 255.0
    b = b / 255.0
    c = 1 - r
    m = 1 - g
    y = 1 - b
    result = cv2.merge((c, m, y))  # merge the channels
    return result

if __name__ == '__main__':
    img = cv2.imread("E:/1.PNG")
    img_CMY = rgb_cmy(img)
    img_NEW = img_CMY * 255
    cv2.imwrite('F:/img_CMY.PNG', img_NEW)
    cv2.imshow("CMY image", imutils.resize(img_CMY, 666))
    cv2.imshow("original image", imutils.resize(img, 666))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

1.3 运行结果 

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第2张图片


2 CMY → RGB

2.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第3张图片

2.2 代码实现

'''-----------------CMY → RGB------------------------'''
import cv2
import imutils

def cmy_rgb(img):
    c, m, y = cv2.split(img)  # split the channels
    # normalization[0,1]
    c = c / 255.0
    m = m / 255.0
    y = y / 255.0
    r = 1 - c
    g = 1 - m
    b = 1 - y
    result = cv2.merge((r, g, b))  # merge the channels
    print(result)
    return result

if __name__ == '__main__':
    img = cv2.imread("F:/img_CMY.PNG")
    img_CMY = cmy_rgb(img)
    cv2.imshow("RGB image", imutils.resize(img_CMY, 666))
    cv2.imshow("original image", imutils.resize(img, 666))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

2.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第4张图片


3 RGB → HSI

3.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第5张图片

3.2 代码实现

'''-----------------RGB → HSI------------------------'''
import cv2
import math
import imutils
import numpy as np

def rgb_hsi(rgb_Img):
    img_rows = int(rgb_Img.shape[0])
    img_cols = int(rgb_Img.shape[1])
    b, g, r = cv2.split(rgb_Img)
    # normalization[0,1]
    r = r / 255.0
    g = g / 255.0
    b = b / 255.0
    hsi_Img = rgb_Img.copy()
    H, S, I = cv2.split(hsi_Img)
    for i in range(img_rows):
        for j in range(img_cols):
            num = 0.5 * ((r[i, j]-g[i, j])+(r[i, j]-b[i, j]))
            den = np.sqrt((r[i, j]-g[i, j])**2+(r[i, j]-b[i, j])*(g[i, j]-b[i, j]))
            theta = float(np.arccos(num/den))

            if den == 0:
                H = 0
            elif b[i, j] <= g[i, j]:
                H = theta
            else:
                H = math.pi - theta

            min_RGB = min(min(b[i, j], g[i, j]), r[i, j])
            sum = b[i, j]+g[i, j]+r[i, j]
            if sum == 0:
                S = 0
            else:
                S = 1 - 3*min_RGB/sum

            H = H/(math.pi)
            I = sum/3.0
            # 输出HSI图像,扩充到255以方便显示,一般H分量在[0,2pi]之间,S和I在[0,1]之间
            hsi_Img[i, j, 0] = H*255
            hsi_Img[i, j, 1] = S*255
            hsi_Img[i, j, 2] = I*255
    return hsi_Img

if __name__ == '__main__':
    rgb_Img = cv2.imread("E:/1.PNG")
    hsi_Img = rgb_hsi(rgb_Img)

    cv2.imwrite('F:/img_HSI.PNG', hsi_Img)

    cv2.imshow('original image', imutils.resize(rgb_Img, 600))
    cv2.imshow('HSI image', imutils.resize(hsi_Img, 600))

    key = cv2.waitKey(0) & 0xFF
    if key == ord('q'):
        cv2.destroyAllWindows()

3.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第6张图片


4 HSI → RGB

4.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第7张图片

4.2 代码实现

'''-----------------HSI → RGB------------------------'''
import cv2
import math
import imutils

def hsi_rgb(hsi_img):
    img_rows = int(hsi_img.shape[0])
    img_cols = int(hsi_img.shape[1])
    H, S, I = cv2.split(hsi_img)
    # normalization[0,1]
    H = H / 255.0
    S = S / 255.0
    I = I / 255.0
    bgr_img = hsi_img.copy()
    B, G, R = cv2.split(bgr_img)
    for i in range(img_rows):
        for j in range(img_cols):
            if S[i, j] < 1e-6:
                R = I[i, j]
                G = I[i, j]
                B = I[i, j]
            else:
                H[i, j] *= 360
                if H[i, j] > 0 and H[i, j] <= 120:
                    B = I[i, j] * (1 - S[i, j])
                    R = I[i, j] * (1 + (S[i, j] * math.cos(H[i, j] * math.pi / 180)) / math.cos((60 - H[i, j]) * math.pi / 180))
                    G = 3 * I[i, j] - (R + B)
                elif H[i, j] > 120 and H[i, j] <= 240:
                    H[i, j] = H[i, j] - 120
                    R = I[i, j] * (1 - S[i, j])
                    G = I[i, j] * (1 + (S[i, j] * math.cos(H[i, j] * math.pi / 180)) / math.cos((60 - H[i, j]) * math.pi / 180))
                    B = 3 * I[i, j] - (R + G)
                elif H[i, j] > 240 and H[i, j] <= 360:
                    H[i, j] = H[i, j] - 240
                    G = I[i, j] * (1 - S[i, j])
                    B = I[i, j] * (1 + (S[i, j] * math.cos(H[i, j] * math.pi / 180)) / math.cos((60 - H[i, j]) * math.pi / 180))
                    R = 3 * I[i, j] - (G + B)
            bgr_img[i, j, 0] = B * 255
            bgr_img[i, j, 1] = G * 255
            bgr_img[i, j, 2] = R * 255
    return bgr_img

if __name__ == '__main__':
    hsi_Img = cv2.imread("F:/img_HSI.PNG")
    rgb_Img = hsi_rgb(hsi_Img)

    cv2.imshow('original image', imutils.resize(rgb_Img, 600))
    cv2.imshow('RGB image', imutils.resize(hsi_Img, 600))

    key = cv2.waitKey(0) & 0xFF
    if key == ord('q'):
        cv2.destroyAllWindows()

4.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第8张图片


5 RGB → YIQ

5.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第9张图片

5.2 代码实现

Python

'''-----------------RGB → YIQ------------------------'''
import cv2
import imutils
import numpy as np

def rgb_yiq(rgb_Img):
    img_rows = int(rgb_Img.shape[0])
    img_cols = int(rgb_Img.shape[1])
    yiq_image = rgb_Img.copy()
    R, G, B = cv2.split(yiq_image)

    for x in range(img_rows):
        for y in range(img_cols):
            right_matrix = np.array([[R[x,y]],
                                     [G[x,y]],
                                     [B[x,y]]])
            left_matrix = np.array([[0.299,0.587,0.114],
                                    [0.596,-0.275,-0.321],
                                    [0.212,-0.528,0.311]])
            matrix = np.dot(left_matrix,right_matrix)
            r = matrix[0][0]
            g = matrix[1][0]
            b = matrix[2][0]
            yiq_image[x, y] = (r, g, b)
    return yiq_image

if __name__ == '__main__':
    rgb_Img = cv2.imread("E:/1.PNG")
    yiq_Img = rgb_yiq(rgb_Img)
    cv2.imshow('original image', imutils.resize(rgb_Img, 600))
    cv2.imshow('YIQ image', imutils.resize(yiq_Img, 600))

    cv2.imwrite('F:/img_YIQ1.PNG', yiq_Img)

    key = cv2.waitKey(0) & 0xFF
    if key == ord('q'):
        cv2.destroyAllWindows()

MATLAB

% 清变量,关闭窗口
clear;
close all;
% 文件读取
img=imread('E:/1.PNG'); %获得256*256*3数组
imshow(img);title('原始RGB图像');

rgb=im2double(img); %将原图像转换到[0,1]空间
% figure;     %与原图像相同
% imshow(rgb);
r=rgb(:,:,1);
g=rgb(:,:,2);
b=rgb(:,:,3)

% rgb模型到yiq模型
y=0.299*r+0.587*g+0.114*b;
i=0.596*r-0.274*g-0.322*b;
q=0.211*r-0.523*g+0.312*b;

img_YIQ=cat(3,y,i,q);
figure;
imshow(img_YIQ);title('RGB2YIQ图像');

5.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第10张图片


6 YIQ → RGB

6.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第11张图片

6.2 代码实现

Python

'''-----------------YIQ → RGB------------------------'''
import cv2
import imutils
import numpy as np

def yiq_rgb(yiq_Img):
    img_rows = int(yiq_Img.shape[0])
    img_cols = int(yiq_Img.shape[1])
    rgb_image = yiq_Img.copy()
    Y, I, Q = cv2.split(rgb_image)

    for x in range(img_rows):
        for y in range(img_cols):
            right_matrix = np.array([[Y[x,y]],
                                     [I[x,y]],
                                     [Q[x,y]]])
            left_matrix = np.array([[1,0.956,0.620],
                                    [1,-0.272,-0.647],
                                    [1,-1.108,1.705]])
            matrix = np.dot(left_matrix,right_matrix)
            r = matrix[0][0]
            g = matrix[1][0]
            b = matrix[2][0]
            rgb_image[x, y] = (r, g, b)
    return rgb_image

if __name__ == '__main__':
    yiq_Img = cv2.imread("F:/img_YIQ1.PNG")
    rgb_Img = yiq_rgb(yiq_Img)
    cv2.imshow('original image', imutils.resize(yiq_Img, 600))
    cv2.imshow('RGB image', imutils.resize(rgb_Img, 600))

    key = cv2.waitKey(0) & 0xFF
    if key == ord('q'):
        cv2.destroyAllWindows()

MATLAB

% 清变量,关闭窗口
clear;
close all;
% 文件读取
img=imread('F:\img_YIQ.PNG'); %获得256*256*3数组
imshow(img);title('原始YIQ图像');

yiq=im2double(img); %将原图像转换到[0,1]空间
% figure;     %与原图像相同
% imshow(rgb);
y=yiq(:,:,1);
i=yiq(:,:,2);
q=yiq(:,:,3)

% rgb模型到yiq模型
r=1*y+0.956*i+0.620*q;
g=1*y-0.272*i-0.674*q;
b=1*y-1.108*i+1.705*q;

img_YIQ=cat(3,r,g,b);
figure;
imshow(img_YIQ);title('YIQ2RGB图像');

6.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第12张图片


7 RGB → YUV

7.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第13张图片

7.2 代码实现

'''-----------------RGB → YUV------------------------'''
import numpy as np
import cv2 as cv
import imutils


def rgb_yuv(rgb_img):
    W = np.array([
        [0.299, 0.587, 0.114],
        [-0.148, -0.289, 0.437],
        [0.615, -0.515, -0.100]
    ])
    rgb_Img = rgb_img.copy()
    rgb_Img = rgb_Img.astype(np.float)
    h, w, c = rgb_Img.shape
    for i in range(h):
        for j in range(w):
            rgb_Img[i, j] = np.dot(W, rgb_Img[i, j])
    imc = rgb_Img.astype(np.uint8)
    return imc

if __name__ == '__main__':
    img_rgb = cv.imread('E:/1.PNG')
    img_yuv1 = cv.cvtColor(img_rgb, cv.COLOR_RGB2YUV)
    img_yuv2 = rgb_yuv(img_rgb)

    cv.imwrite('F:/img_YUV.PNG', img_yuv1)
    # cv.imwrite('F:/img_YUV_self.PNG', img_yuv2)

    cv.imshow('original image', imutils.resize(img_rgb, 600))
    cv.imshow('OpenCV_YUV image', imutils.resize(img_yuv1, 600))
    cv.imshow('Self_YUV image', imutils.resize(img_yuv2, 600))

    cv.waitKey(0)

7.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第14张图片


8 YUV → RGB

8.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第15张图片

8.2 代码实现

'''-----------------YUV → RGB------------------------'''
import numpy as np
import cv2 as cv
import imutils


def yuv_rgb(yuv_img):
    W = np.array([
        [1, 0., 1.13983],
        [1, -0.39465, -0.58060],
        [1, 2.03211, 0.]
    ])
    rgb_img = yuv_img.copy()
    rgb_img = yuv_img.astype(np.float)
    h, w, c = rgb_img.shape
    for i in range(h):
        for j in range(w):
            rgb_img[i, j][0] -= 16  # Y
            rgb_img[i, j][1] -= 128  # U
            rgb_img[i, j][2] -= 128  # V
            rgb_img[i, j] = np.matmul(W, rgb_img[i, j])
    imc = rgb_img.astype(np.uint8)
    return imc

if __name__ == '__main__':
    img_rgb = cv.imread('F:/img_YUV.PNG')
    img_yuv1 = yuv_rgb(img_rgb)
    img_yuv2 = cv.cvtColor(img_rgb, cv.COLOR_YUV2RGB)

    cv.imshow('original image', imutils.resize(img_rgb, 600))
    cv.imshow('OpenCV_RGB image', imutils.resize(img_yuv2, 600))
    cv.imshow('Self_RGB image', imutils.resize(img_yuv1, 600))

    cv.waitKey(0)

8.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第16张图片


9 RGB → YCbCr

9.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第17张图片

9.2 代码实现

'''-----------------RGB → YCbCr------------------------'''
import numpy as np
import cv2 as cv
import imutils

def rgb2ycbcr(rgb_image):
    """convert rgb into ycbcr"""
    if len(rgb_image.shape)!=3 or rgb_image.shape[2]!=3:
        raise ValueError("input image is not a rgb image")
    rgb_image = rgb_image.astype(np.float32)
    # 1:创建变换矩阵,和偏移量
    transform_matrix = np.array([[0.257, 0.564, 0.098],
                                 [-0.148, -0.291, 0.439],
                                 [0.439, -0.368, -0.071]])
    shift_matrix = np.array([16, 128, 128])
    ycbcr_image = np.zeros(shape=rgb_image.shape)
    w, h, _ = rgb_image.shape
    # 2:遍历每个像素点的三个通道进行变换
    for i in range(w):
        for j in range(h):
            ycbcr_image[i, j, :] = np.dot(transform_matrix, rgb_image[i, j, :]) + shift_matrix
    return ycbcr_image

if __name__ == '__main__':
    img_rgb = cv.imread('E:/1.PNG')
    img_ycbcr = rgb2ycbcr(img_rgb)
    img_NEW = img_ycbcr / 255

    cv.imwrite('F:/img_YCbCr.PNG', img_ycbcr)

    cv.imshow('original image', imutils.resize(img_rgb, 600))
    cv.imshow('Self_YCbCr image', imutils.resize(img_NEW, 600))

    cv.waitKey(0)

9.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第18张图片


10 YCbCr → RGB

10.1 公式转换

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第19张图片

10.2 代码实现

'''-----------------YCbCr → RGB------------------------'''
import numpy as np
import cv2 as cv
import imutils

def ycbcr2rgb(ycbcr_image):
    """convert ycbcr into rgb"""
    if len(ycbcr_image.shape)!=3 or ycbcr_image.shape[2]!=3:
        raise ValueError("input image is not a rgb image")
    ycbcr_image = ycbcr_image.astype(np.float32)
    transform_matrix = np.array([[0.257, 0.564, 0.098],
                                 [-0.148, -0.291, 0.439],
                                 [0.439, -0.368, -0.071]])
    transform_matrix_inv = np.linalg.inv(transform_matrix)
    shift_matrix = np.array([16, 128, 128])
    rgb_image = np.zeros(shape=ycbcr_image.shape)
    w, h, _ = ycbcr_image.shape
    for i in range(w):
        for j in range(h):
            rgb_image[i, j, :] = np.dot(transform_matrix_inv, ycbcr_image[i, j, :]) - np.dot(transform_matrix_inv, shift_matrix)
    return rgb_image.astype(np.uint8)

if __name__ == '__main__':
    img_ycbcr = cv.imread('F:/img_YCbCr.PNG')
    img_rgb = ycbcr2rgb(img_ycbcr)
    img_NEW = img_rgb / 255

    cv.imshow('original image', imutils.resize(img_ycbcr, 600))
    cv.imshow('Self_RGB image', imutils.resize(img_NEW, 600))

    cv.waitKey(0)

10.3 运行效果

Python实现数字图像处理之5种彩色空间转换(单图+多图+视频)_第20张图片

11 扩展1——多图处理

11.1 代码示例

'''-----------------RGB → CMY------------------------'''
import cv2
import imutils

def rgb_cmy(img):
    r, g, b = cv2.split(img)  # split the channels
    # normalization [0,1]
    r = r / 255.0
    g = g / 255.0
    b = b / 255.0
    c = 1 - r
    m = 1 - g
    y = 1 - b
    result = cv2.merge((c, m, y))  # merge the channels
    return result

if __name__ == '__main__':
    for i in range(3):
        img = cv2.imread("F:/{}.PNG".format(i))
        img_CMY = rgb_cmy(img)
        img_NEW = img_CMY * 255
        cv2.imwrite('F:/img_CMY.PNG', img_NEW)
        cv2.imshow("CMY image{}".format(i), imutils.resize(img_CMY, 666))
        cv2.imshow("original image{}".format(i), imutils.resize(img, 666))
    cv2.waitKey(0)
    cv2.destroyAllWindows()

11.2 运行效果

12 扩展2——视频处理

12.1 附:视频爬取代码

import requests
import json
import re

def change_title(title):
    # 替换非法字符
    pattern = re.compile(r"[\/\\\:\*\?\"\<\>\|]")
    new_title = re.sub(pattern, "_", title)
    return new_title

# 示例爬取3页数据
for page in range(1, 4):
    print('---------------正在爬取第{}页小姐姐视频-------------------'.format(page))
    # 获取 URL 地址
    url = 'https://v.6.cn/minivideo/getlist.php?act=recommend&page={}&pagesize=20'.format(page)
    # headers 参数确定
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    }

    # 模拟浏览器发送 URL 地址请求
    response = requests.get(url, headers=headers)
    # 去除 response 响应对象中的文本数据
    response_data = response.text
    # print(response_data)


    # 转换数据类型
    dict_data = json.loads(response_data)    # 字典
    # print(dict_data)
    # 数据解析
    data_list = dict_data['content']['list']   # 列表
    # print(data_list)

    # 遍历
    for data in data_list:
        # print(data)
        video_title = data['title']      # 视频文件名
        video_alias = data['alias']       # 视频作者名
        video_playurl = data['playurl']   # 视频 url
        # print('视频:', video_title, '作者:', video_alias, 'url地址:', video_playurl)
        print('正在下载视频:', video_title)

        new_title = change_title(video_title)

        # 发送视频 URL 请求
        video = requests.get(video_playurl, headers=headers).content

        # 保存数据
        with open(r'F:\Beautiful Girl Video\\' + new_title + '_' + video_alias + '.mp4', 'wb') as video_file:
            video_file.write(video)

        print('视频下载成功…… \n')

    print('---------------第{}页小姐姐视频爬取完毕-------------------'.format(page))

12.2 代码实现

'''-----------------RGB → CMY------------------------'''
import cv2

def rgb_cmy(video):
    while True:
        ret, frame=video.read()
        if not ret:
            break
        else:
            r, g, b = cv2.split(frame)  # split the channels
            # normalization [0,1]
            r = r / 255.0
            g = g / 255.0
            b = b / 255.0
            c = 1 - r
            m = 1 - g
            y = 1 - b
            result = cv2.merge((c, m, y))  # merge the channels
            cv2.imshow('original video',frame)
            cv2.imshow('CMY video',result)
            cv2.waitKey(ret)

if __name__ == '__main__':
    img = cv2.VideoCapture(r"F:\Beautiful Girl Video\video.mp4")
    img_CMY = rgb_cmy(img)

12.3 运行效果


:本文所有内容的讲解视频已发布到:https://space.bilibili.com/386691571

版权声明:本专栏全部为CSDN博主「IT_change」的原创文章,遵循 CC 4.0 BY-SA 版权协议。
                  转载请附上原文出处链接及本声明。

感谢阅读 ! 感谢支持 !  感谢关注 !

希望本文能对读者学习和理解数字图像处理之彩色空间转换有所帮助,并请读者批评指正!

2020年6月初于山西大同

END
 

你可能感兴趣的:(《数字图像处理》学习笔记,python,opencv,数字图像处理,彩色空间转换,Python爬虫)