python之实验二颜色空间转换与分割

1.编写python代码,使用skimag拆分并显示图像RGB空间的三个通道

(我直接用的包中自带的图像)

python 复制代码
from skimage import data
from matplotlib import pyplot as plt
import numpy as np

if __name__ == "__main__":
    # 载入RGB测试图像
    image = data.astronaut()

    fig = plt.figure()
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    # 两行两列的第一个子图
    axis = fig.add_subplot(221)
    plt.axis('off')  # 不显示坐标轴
    plt.imshow(image)  # 显示RGB彩色图像
    plt.title('RGB图像')

    # 第二个子图,显示R通道图像
    axis = fig.add_subplot(222)
    imageR = image[:, :, 0]
    plt.axis('off')
    plt.imshow(imageR, cmap='gray')
    plt.title('R通道图像')

    # 第三个子图,显示G通道图像
    axis = fig.add_subplot(223)
    imageG = image[:, :, 1]
    plt.axis('off')
    plt.imshow(imageG, cmap='gray')
    plt.title('G通道图像')

    # 第四个子图,显示B通道图像
    axis = fig.add_subplot(224)
    imageB = image[:, :, 2]
    plt.axis('off')
    plt.imshow(imageB, cmap='gray')
    plt.title('B通道图像')

    plt.savefig('RGBimage.tif')
    plt.show()

2.编写python代码实现RGB空间转换为HSI空间(这个是网上随便找的图像)

python 复制代码
from skimage import data, io
from matplotlib import pyplot as plt
import math
import numpy as np
import sys
import os


#定义RGB转HSI
def rgb2hsi(r,g,b):
    r=r/255
    g=g/255
    b=b/255

    num=0.5*((r-g)+(r-b))
    den=((r-g)*(r-g)+(r-b)*(g-b))**0.5

    if b<=g:
        if den == 0:
            den = sys.float_info.min
        h=math.acos(num/den)
    elif b>g:
        if den == 0:
            den = sys.float_info.min
        h=(2*math.pi)-math.acos(num/den)

    s=1-(3*min(r,g,b)/(r+g+b))
    i=(r+g+b)/3

    return int(h),int(s*100),int(i*255)


if __name__ == "__main__":
    print(os.getcwd())
    imgPath = os.path.join(os.getcwd(), 'flower.jpg')
    image = io.imread(imgPath)
    print(image.shape)
    hsi_image=np.zeros(image.shape,dtype='uint8')
    for ii in range(image.shape[0]):
        for jj in range(image.shape[1]):
            r,g,b=image[ii,jj,:]
            h,s,i=rgb2hsi(r,g,b)
            hsi_image[ii,jj,:]=(h,s,i)

    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.subplot(2,3,1)
    plt.axis('off')
    plt.imshow(image)
    plt.title('RGB原图像')
    plt.subplot(2,3,2)
    plt.axis('off')
    plt.imshow(image[:, :, 0], cmap='gray')
    plt.title('R分量')
    plt.subplot(2,3,3)
    plt.axis('off')
    plt.imshow(hsi_image)
    plt.title('HSI图像')
    plt.subplot(2,3,4)
    plt.axis('off')
    plt.imshow(hsi_image[:,:,0], cmap='gray')
    plt.title('H分量')
    plt.subplot(2,3,5)
    plt.axis('off')
    plt.imshow(hsi_image[:,:,1], cmap='gray')
    plt.title('S分量')
    plt.subplot(2,3,6)
    plt.axis('off')
    plt.imshow(hsi_image[:,:,2],cmap='gray')
    plt.title('I分量')
    plt.savefig('HSIimage.tif')
    plt.show()

3.编写python代码实现图像的强度分层(这个需要下载opencv-python库)

在终端 路径 -m pip install opencv-python -i 镜像网站(这里我用的清华的镜像网站)

python 复制代码
D:\PycharmProjects\projects\venv\Scripts\python.exe -m pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
python 复制代码
import cv2
from skimage import data,color
from matplotlib import pyplot as plt
import numpy as np


# def grayBin(image_matrix):
#     initial_conv = np.where((image_matrix < 0.4), 0, 128)
#     final_conv = np.where((image_matrix >= 0.8), 255, initial_conv)
#     return final_conv


if __name__ == "__main__":
    img = data.astronaut()
    grayimg = color.rgb2gray(img) #将彩色图像转化为灰度图像
    # grayimg = cv2.resize(grayimg, (5000,5000))
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.subplot(1, 2, 1)
    plt.imshow(grayimg, cmap = 'gray')
    plt.title('灰度图像')
    rows, cols = grayimg.shape
    labels = np.zeros([rows, cols])
    for i in range(rows):
        for j in range(cols):
            if(grayimg[i, j] < 0.4):
                labels[i, j] = 0
            elif(grayimg[i, j] < 0.8):
                labels[i, j] = 128
            else:
                labels[i, j] = 255
    psdimg = color.label2rgb(labels)#不同的label采用不同的颜色
    # labels1 = grayBin(grayimg)
    # cv2.imwrite("labels.jpg", labels)
    # cv2.imwrite("labels1.jpg", labels1)
    # print((labels1 == labels).all())
    plt.subplot(1, 2, 2)
    plt.imshow(psdimg)
    plt.title('强度分层图像')
    plt.savefig('灰度分层.tif')
    plt.show()

4.编写python代码实现灰度值到彩色变换并画出映射函数

python 复制代码
from skimage import data, color
from matplotlib import pyplot as plt
import numpy as np


# 定义灰度级到彩色变换
L = 256
def GetR(gray):
    if gray < L / 2:
        return 0
    elif gray > L / 4 * 3:
        return L
    else:
        return 4 * gray - 2 * L

def GetG(gray):
    if gray < L / 4:
        return 4 * gray
    elif gray > L / 4 * 3:
        return 4 * L - 4 * gray
    else:
        return L

def GetB(gray):
    if gray < L / 4:
        return L
    elif gray > L / 2:
        return 0
    else:
        return 2 * L - 4 * gray


if __name__ == "__main__":
    img = data.astronaut()
    grayimg = color.rgb2gray(img) * 255  # 将彩色图像转化为灰度图像
    colorimg = np.zeros(img.shape, dtype='uint8')
    for ii in range(img.shape[0]):
        for jj in range(img.shape[1]):
            a = grayimg[ii, jj]
            a0 = GetR(a)
            a1 = GetG(a)
            a2 = GetB(a)

            # 确保值在 0 到 255 之间
            r = np.clip(a0, 0, 255)
            g = np.clip(a1, 0, 255)
            b = np.clip(a2, 0, 255)

            colorimg[ii, jj, :] = (r, g, b)

    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.subplot(1, 2, 1)
    plt.axis('off')
    plt.imshow(grayimg, cmap='gray')
    plt.title('灰度图像')
    plt.subplot(1, 2, 2)
    plt.axis('off')
    plt.imshow(colorimg)
    plt.title('伪彩色图像')
    plt.savefig('Intensity2Color.tif')
    plt.show()

映射

python 复制代码
from matplotlib import pyplot as plt


#定义灰度级到彩色变换 
L = 255    
def GetR(gray):
    if gray < L / 2:
        return 0
    elif gray > L / 4 * 3:
        return L
    else:
        return 4 * gray - 2 * L
       
def GetG(gray):
    if gray < L / 4:
        return 4 * gray
    elif gray > L / 4 * 3:
        return 4 * L - 4 * gray
    else:
        return L
        
def GetB(gray):
    if gray < L / 4:
        return L
    elif gray > L / 2:
        return 0
    else:
        return 2 * L - 4 * gray


if __name__ == "__main__":
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    L = 255
    x = [0, 64, 127, 191, 255]
    #绘制灰度图像到R通道的映射关系
    plt.subplot(2,2,1)
    R = []
    for i in x:
        R.append(GetR(i))
    plt.plot(x, R, 'r--', label = '红色变换')
    plt.legend(loc = 'best')
    #绘制灰度图像到G通道的映射关系
    plt.subplot(2,2,2)
    G = []
    for i in x:
        G.append(GetG(i))
    plt.plot(x, G, 'g', label = '绿色变换')
    plt.legend(loc = 'best')
    #绘制灰度图像到B通道的映射关系
    plt.subplot(2,2,3)
    B = []
    for i in x:
        B.append(GetB(i))
    plt.plot(x, B, 'b', marker = 'o', markersize = 5, label = '蓝色变换')
    plt.legend(loc = 'best')
    #绘制灰度图像到RGB的映射关系
    plt.subplot(2,2,4)
    plt.plot(x, R, 'r--')
    plt.plot(x, G, 'g')
    plt.plot(x, B, 'b', marker = 'o', markersize = 5)
    plt.savefig('灰度到彩色的映射关系.tif')
    plt.show()

5.编写python代码,实现颜色空间分割(这个花是2里的花,我懒得在找图片了)

python 复制代码
import cv2
from skimage import data, io
from matplotlib import pyplot as plt
import math
import numpy as np
import sys


# 定义RGB转HSI
def rgb2hsi(r, g, b):
    r = r / 255
    g = g / 255
    b = b / 255
    num = 0.5 * ((r - g) + (r - b))
    den = ((r - g) ** 2 + (r - b) * (g - b)) ** 0.5
    if b <= g:
        if den == 0:
            den = sys.float_info.min
        h = math.acos(num / den)
    elif b > g:
        if den == 0:
            den = sys.float_info.min
        h = (2 * math.pi) - math.acos(num / den)
    s = 1 - 3 * min(r, g, b) / (r + g + b)
    i = (r + g + b) / 3
    return int(h), int(s * 100), int(i * 255)


if __name__ == "__main__":
    image = io.imread('flower.jpg')
    hsi_image = np.zeros(image.shape, dtype='uint8')
    for ii in range(image.shape[0]):
        for jj in range(image.shape[1]):
            r, g, b = image[ii, jj, :]
            h, s, i = rgb2hsi(r, g, b)
            hsi_image[ii, jj, :] = (h, s, i)

    H = hsi_image[:, :, 0]
    S = hsi_image[:, :, 1]
    I = hsi_image[:, :, 2]

    # 生成二值饱和度模板
    S_template = S > 0.3 * S.max()

    # 色调图像与二值饱和度模板相乘可得到分割结果F
    F = np.multiply(H, S_template)

    plt.figure()  # 创建一个新的图形窗口
    plt.imshow(F, cmap='gray')

    # 显示结果
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    # 在创建第一个子图之前,显式移除当前的轴
    plt.gca().remove()

    plt.subplot(2, 3, 1)
    plt.axis('off')
    plt.imshow(image)
    plt.title('原始RGB图像')

    plt.subplot(2, 3, 2)
    plt.axis('off')
    plt.imshow(H, cmap='gray')
    plt.title('H分量')

    plt.subplot(2, 3, 3)
    plt.axis('off')
    plt.imshow(S, cmap='gray')
    plt.title('S分量')

    plt.subplot(2, 3, 4)
    plt.axis('off')
    plt.imshow(I, cmap='gray')
    plt.title('I分量')

    plt.subplot(2, 3, 5)
    plt.axis('off')
    plt.imshow(S_template, cmap='gray')
    plt.title('二值饱和度模板')

    plt.subplot(2, 3, 6)
    plt.axis('off')
    plt.imshow(F, cmap='gray')
    plt.title('分割结果')

    plt.savefig('HSI彩色分割.tif')
    plt.show()
相关推荐
ZSYP-S3 分钟前
Day 15:Spring 框架基础
java·开发语言·数据结构·后端·spring
yuanbenshidiaos6 分钟前
c++------------------函数
开发语言·c++
程序员_三木18 分钟前
Three.js入门-Raycaster鼠标拾取详解与应用
开发语言·javascript·计算机外设·webgl·three.js
是小崔啊28 分钟前
开源轮子 - EasyExcel01(核心api)
java·开发语言·开源·excel·阿里巴巴
tianmu_sama34 分钟前
[Effective C++]条款38-39 复合和private继承
开发语言·c++
黄公子学安全37 分钟前
Java的基础概念(一)
java·开发语言·python
liwulin050638 分钟前
【JAVA】Tesseract-OCR截图屏幕指定区域识别0.4.2
java·开发语言·ocr
jackiendsc42 分钟前
Java的垃圾回收机制介绍、工作原理、算法及分析调优
java·开发语言·算法
Oneforlove_twoforjob1 小时前
【Java基础面试题027】Java的StringBuilder是怎么实现的?
java·开发语言
羚羊角uou1 小时前
【C++】优先级队列以及仿函数
开发语言·c++