将 RGB 转换为 LAB 以获得多个值

问题描述

我编写了一个代码,它为我提供了图像的平均 RGB 值。现在我想要除了 RGB 值,还有一个 LAB 值。我找到了一个代码来进行转换,但是当我运行代码时,它只给了我最后一个值。

因此,使用此代码,我接收平均 RGB 并将其放入数据帧中:

import cv2 as cv
import glob
import numpy as np
from skimage import io
import pandas as pd
from colormath.color_objects import sRGBColor,LabColor
from colormath.color_conversions import convert_color

path = "image.jpg"
img_number = 1

for file in glob.glob(path):
    print(file)
    img = cv.imread(file)
    scale_percent = 60
    width = int(img.shape[1] * scale_percent / 100)
    height = int(img.shape[0] * scale_percent / 100)
    dim = (width,height)
    imgr = cv.resize(img,dim,interpolation=cv.INTER_AREA)

    hsv = cv.cvtColor(imgr,cv.COLOR_BGR2HSV)
    blur0 = cv.medianBlur(hsv,11)

    low_yellow = np.array([10,42,220])
    high_yellow = np.array([30,255,255])

    mask = cv.inRange(blur0,low_yellow,high_yellow)
    res = cv.bitwise_and(imgr,imgr,mask=mask)

    cv.imwrite("image"+str(img_number)+".jpg",res)
    img_number +=1


path1 = "Image/*.jpg"
img_number = 1

result_df = pd.DataFrame()
for file in glob.glob(path1):
    image = io.imread(file)
    x = image[np.all(image != 0,axis=2)].mean(axis=0)
    result_df = pd.concat((result_df,pd.DataFrame(x)),axis=1)
    df_t = result_df.T
    df_lab = rgb_to_cielab(df_t)
    df_t.columns = ['R','G','B']
    df_t.loc['Mean'] = df_t.mean()

    df = df_t.round(decimals=1)
df.to_excel("Excel.xlsx")

当我想将我的 RGB 值转换为 LAB 时,我发现此代码可以进行转换:

def rgb_to_cielab(a):
"""
a is a pixel with RGB coloring
"""
a1,a2,a3 = a/255

color1_rgb = sRGBColor(a1,a3);

color1_lab = convert_color(color1_rgb,LabColor);

return color1_lab

当我运行这段代码时,它只提供了最后一个值。我很确定我正在创建一个循环,但我不知道如何修复它。有人可以帮我解决这个问题吗?

我知道我的标题与我的真正问题有点不同,但也许有人知道获取 LAB 值的更简单方法

解决方法

简答

检查 this 个问题(可能重复)。

有关 official documentation 的更多详细信息。

长答案

使用这些公式获得您自己的转化率。

  1. RGB => XYZ
  2. XYZ => Lab

请记住,没有一个实验室(取决于您使用的 CIE),因此您可能需要在必要时调整值。