Ejemplo n.º 1
0
def sp2xy(sp):
    spd = colour.SpectralDistribution(sp, name='Sample')
    cmfs = colour.colorimetry.MSDS_CMFS_STANDARD_OBSERVER[
        'CIE 1931 2 Degree Standard Observer']
    illuminant = colour.SDS_ILLUMINANTS['D65']
    XYZ = colour.sd_to_XYZ(spd, cmfs, illuminant)
    return colour.XYZ_to_xy(XYZ)
Ejemplo n.º 2
0
 def get_bar_amount_for_color(self, col):
     col = self._get_app_brush_color()
     # return CCT in domain of 0-1
     xy = colour.XYZ_to_xy(np.array(col.lightsource))
     cct = colour.temperature.xy_to_CCT_Hernandez1999(xy)
     if cct < 6500:
         cct = colour.temperature.xy_to_CCT(xy)
     amt = ((cct - 1904) / 23096)**(1/2)
     return max(0.0, amt)
Ejemplo n.º 3
0
def calculateColorValues(splineT, splineR, settings):
    '''Function calculates color values of the Transmission and Refelection side of the stack. 
    Input Arguments are tranmission and reflection spline functions.
    Returns array of values/tuples of different standards.'''
    import colour
    import numpy as np
    wvl = np.linspace(380, 780, 81)
    dic_T = {}
    dic_R = {}
    dic_test = {}
    for idx, value in enumerate(wvl):
        dic_T[value] = splineT(value).item()
        dic_R[value] = splineR(value).item()

    #Removes warnings from conversions.
    colour.filter_warnings()
    cmfs = colour.STANDARD_OBSERVERS_CMFS[settings.color_cmfs]  #1931 etc
    illuminant = colour.ILLUMINANTS_RELATIVE_SPDS[
        settings.color_illuminant]  #D65, A, C

    T_spd = colour.SpectralPowerDistribution('', dic_T)
    T_XYZ = colour.spectral_to_XYZ(T_spd, cmfs, illuminant)
    T_xy = colour.XYZ_to_xy(T_XYZ / 100)
    T_ab = colour.XYZ_to_Lab(T_XYZ / 100,
                             illuminant=colour.ILLUMINANTS[settings.color_cmfs]
                             [settings.color_illuminant])
    T_rgb = colour.XYZ_to_sRGB(
        T_XYZ / 100,
        illuminant=colour.ILLUMINANTS[settings.color_cmfs][
            settings.color_illuminant])

    R_spd = colour.SpectralPowerDistribution('', dic_R)
    R_XYZ = colour.spectral_to_XYZ(R_spd, cmfs, illuminant)
    R_xy = colour.XYZ_to_xy(R_XYZ / 100)
    R_ab = colour.XYZ_to_Lab(R_XYZ / 100,
                             illuminant=colour.ILLUMINANTS[settings.color_cmfs]
                             [settings.color_illuminant])
    R_rgb = colour.XYZ_to_sRGB(
        R_XYZ / 100,
        illuminant=colour.ILLUMINANTS[settings.color_cmfs][
            settings.color_illuminant])

    return (T_XYZ, T_xy, T_ab, T_rgb, R_XYZ, R_xy, R_ab, R_rgb)
Ejemplo n.º 4
0
def rgb_to_k(r, g, b):
    RGB = np.array([r, g, b])
    # Conversion to tristimulus values.
    XYZ = colour.sRGB_to_XYZ(RGB / 255)
    # Conversion to chromaticity coordinates.
    xy = colour.XYZ_to_xy(XYZ)
    # Conversion to correlated colour temperature in K.
    CCT = colour.xy_to_CCT(xy, 'hernandez1999')

    #print(f"{r}{g}{b}")

    return CCT
Ejemplo n.º 5
0
def image_color_temperature(path):
    #convert image to array of pixels
    array = np.array(image_dominant_color_rgb(path))
    
    #conver to xyz https://www.colourphil.co.uk/xyz_colour_space.shtml
    XYZ = colour.sRGB_to_XYZ(array / 255)
    
    #dont need the z value
    xy = colour.XYZ_to_xy(XYZ)
    
    #convert to its kelvin temperature
    CCT = colour.xy_to_CCT(xy, 'hernandez1999')
    return CCT
Ejemplo n.º 6
0
def main():
    while True:
        time.sleep(1)
        img = get_cap()
        avg_color_rgb = bgr_to_rgb(avg_image_colors(img))
        avg_color_xyz = colour.sRGB_to_XYZ(avg_color_rgb)
        avg_color_xy = colour.XYZ_to_xy(avg_color_xyz)
        avg_color_cct = colour.xy_to_CCT(avg_color_xy, 'hernandez1999')
        avg_img_color_cct_xy = colour.temperature.CCT_to_xy(avg_color_cct)

        print("Average RGB Value: {}, Rounded CCT: {}, Sent xy: {}".format(
            avg_color_rgb, avg_color_cct, avg_img_color_cct_xy))

        set_acs_sample(avg_img_color_cct_xy[0], avg_img_color_cct_xy[1])
Ejemplo n.º 7
0
def plot_colors(values, parameters, ylabels):
    #fig, ax = colour.plotting.plot_chromaticity_diagram_CIE1931(standalone=False)
    fig, ax = colour.plotting.plot_planckian_locus_in_chromaticity_diagram_CIE1931([], standalone=False)
    mincct = values[0]['requested']
    maxcct = values[-1]['requested']
    ax.set_title(f'CCT measured for RGB LED, {int(mincct)} to {int(maxcct)}')

    sRGB = colour.RGB_COLOURSPACES['sRGB']

    plotcoloridx = 0
    for value in values:
        plotcolor = f'C{plotcoloridx}'
        plotcoloridx += 1
        cct_requested = value['requested']
#       for ylabel in ylabels:
        x_req, y_req = colour.CCT_to_xy(cct_requested)
        rgb_xvalues = []
        rgb_yvalues = []
        cct_xvalues = []
        cct_yvalues = []
        for ylabel in ylabels:
            r = value[f'rgb_r_{ylabel}']
            g = value[f'rgb_g_{ylabel}']
            b = value[f'rgb_b_{ylabel}']
            RGB = np.array([r, g, b])
            XYZ = colour.RGB_to_XYZ(RGB, sRGB.whitepoint, sRGB.whitepoint, sRGB.RGB_to_XYZ_matrix)
            xy = colour.XYZ_to_xy(XYZ)
            x, y = xy
            rgb_xvalues.append(x)
            rgb_yvalues.append(y)
            cct_measured = value[f'rgb_cct_{ylabel}']
            x, y = colour.CCT_to_xy(cct_measured)
            cct_xvalues.append(x)
            cct_yvalues.append(y)
        matplotlib.pyplot.plot(rgb_xvalues, rgb_yvalues, color=plotcolor, marker='o', linestyle='', label=str(cct_requested))
        matplotlib.pyplot.plot(cct_xvalues, cct_yvalues, color=plotcolor, marker='.', linestyle='')
        matplotlib.pyplot.plot([x_req], [y_req], color=plotcolor, marker='X')
    p_text = []
    for k, v in parameters.items():
        if k in  ('measurement', 'interval'): continue
        p_text.append(f'{k} = {v}')
    ax.text(0.95, 0.05, '\n'.join(p_text), transform=ax.transAxes, bbox=dict(boxstyle='round'), multialignment='left', horizontalalignment='right', verticalalignment='bottom')
    ax.legend()
#        matplotlib.pyplot.annotate(str(cct_requested), 
#            xy=(x, y),
#            xytext=(-50, 30),
#            textcoords='offset points',
#            arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=-0.2'))
    matplotlib.pyplot.show()
Ejemplo n.º 8
0
def calculate_input_temp(frame) -> float:
    array_RGB = numpy.array(list(cv2.mean(frame)[0:3][::-1]))

    array_tristimulus = colour.sRGB_to_XYZ(array_RGB / 255)

    array_chromaticity = colour.XYZ_to_xy(array_tristimulus)

    temporary = colour.xy_to_CCT(array_chromaticity, 'hernandez1999')

    if temporary < 1000:
        # print('Warm bound')
        return 1000
    elif temporary > 12000:
        # print('Cold bound')
        return 12000
    return temporary
Ejemplo n.º 9
0
    def compute_color(self):
        self.sample_spd_data = dict(zip(self.raw_wl, self.raw_spec))
        self.spd = colour.SpectralDistribution(self.sample_spd_data,
                                               name=self.label)
        # Cloning the sample spectral power distribution.
        self.spd_interpolated = self.spd.clone()

        # Interpolating the cloned sample spectral power distribution.
        # Indeed, the algorithm for colour identification needs a spectra with a point each nanometer
        self.spd_interpolated.interpolate(colour.SpectralShape(370, 680, 1))

        self.cmfs = colour.STANDARD_OBSERVERS_CMFS[
            'CIE 1931 2 Degree Standard Observer']
        self.illuminant = colour.ILLUMINANTS_SDS['D65']
        self.XYZ = colour.sd_to_XYZ(self.spd_interpolated, self.cmfs,
                                    self.illuminant)
        self.RGB = colour.XYZ_to_sRGB(self.XYZ / 100)
        """
        We then come to the next obstacle...  The RGB values that we get from this process are often out of range - 
        meaning that they are either greater than 1.0, or even that they are negative!  The first case is fairly 
        straightforward, it means that the color is too bright for the display.  The second case means that the color 
        is too saturated and vivid for the display.  The display must compose all colors from some combination of 
        positive amounts of the colors of its red, green and blue phosphors.  The colors of these phosphors are not 
        perfectly saturated, they are washed out, mixed with white, to some extent.  So not all colors can be displayed 
        accurately.  As an example, the colors of pure spectral lines, all have some negative component.  
        Something must be done to put these values into the 0.0 - 1.0 range that can actually be displayed, 
        known as color clipping.
        
        In the first case, values larger than 1.0, ColorPy scales the color so that the maximum component is 1.0.  
        This reduces the brightness without changing the chromaticity.  The second case requires some change in 
        chromaticity.  By default, ColorPy will add white to the color, just enough to make all of the components 
        non-negative.  (You can also have ColorPy clamp the negative values to zero.  My personal, qualitative, 
        assessment is that adding white produces somewhat better results.  There is also the potential to develop a 
        better clipping function.)
        """
        if min(self.RGB) < 0:
            self.RGB += min(self.RGB)
        if max(self.RGB) > 1:
            self.RGB /= max(self.RGB)

        # TODO why can we get negative values and values > 1 ?
        self.RGB = np.abs(self.RGB)
        self.RGB = np.clip(self.RGB, 0, 1)
        self.xy = colour.XYZ_to_xy(self.XYZ)
Ejemplo n.º 10
0
def rgb_to_temperature(rgb):
    """ Convert sRGB to temperature in Kelvin.
    First, we convert to tristimulus values.
    Second, we convert to chromaticity coordinates.
    Third, we convert to color temp in K from Hernandez paper.

    Parameters
    ----------
    rgb : List/tuple of rgb values, e.g. [255.0, 235.0, 12.0]

    Returns
    -------
    numeric : CCT (correlated color temperature) in kelvin
    """
    rgb_array = numpy.array(rgb)
    xyz = colour.sRGB_to_XYZ(rgb_array / 255)
    xy = colour.XYZ_to_xy(xyz)
    cct = colour.xy_to_CCT_Hernandez1999(xy)
    return cct
Ejemplo n.º 11
0
def XYZ_xyz_Luv_uv_Tc_lum_Eff_lum_KPD(spd, T_method='Robertson1968'):
    cmfs = colour.STANDARD_OBSERVERS_CMFS[
        'CIE 1931 2 Degree Standard Observer']
    # illuminant = colour.ILLUMINANTS_RELATIVE_SPDS['A']
    XYZ = colour.spectral_to_XYZ(spd, cmfs)
    x, y = colour.XYZ_to_xy(XYZ / 100)
    xyz = [x, y, 1 - x - y]
    Luv = colour.XYZ_to_Luv(XYZ)
    uv = colour.UCS_to_uv(colour.XYZ_to_UCS(XYZ))

    if T_method == 'Robertson1968':
        CCT, _D_uv = colour.uv_to_CCT_Robertson1968(uv)
    elif T_method == 'Ohno2013':
        CCT, _D_uv = colour.uv_to_CCT_Ohno2013(uv)

    Tc = [CCT, _D_uv]
    lum_Eff = colour.luminous_efficacy(spd)
    lum_KPD = colour.luminous_efficiency(spd)
    return (XYZ, xyz, Luv, uv, Tc, lum_Eff, lum_KPD)
Ejemplo n.º 12
0
    def copute_color(self):
        self.sample_spd_data = dict(zip(self.raw_wl, self.raw_spec))
        self.spd = colour.SpectralDistribution(self.sample_spd_data,
                                               name=self.label)
        # Cloning the sample spectral power distribution.
        self.spd_interpolated = self.spd.clone()

        # Interpolating the cloned sample spectral power distribution.
        # Indeed, the algorithm for colour identification needs a spectra with a point each nanometer
        self.spd_interpolated.interpolate(colour.SpectralShape(400, 820, 1))

        self.cmfs = colour.STANDARD_OBSERVERS_CMFS[
            'CIE 1931 2 Degree Standard Observer']
        self.illuminant = colour.ILLUMINANTS_SDS['D65']
        self.XYZ = colour.sd_to_XYZ(self.spd_interpolated, self.cmfs,
                                    self.illuminant)
        self.RGB = colour.XYZ_to_sRGB(self.XYZ / 100)
        # TODO why can we get negative values and values > 1 ?
        self.RGB = np.abs(self.RGB)
        self.RGB = np.clip(self.RGB, 0, 1)
        self.xy = colour.XYZ_to_xy(self.XYZ)
Ejemplo n.º 13
0
    def parse_value(self, value):
        if self.sensor_type == "relay_a":
            value = value[0]
        elif self.sensor_type == "relay_b":
            value = value[1]
        elif self.sensor_type == "acceleration":
            value = value[2]
        elif self.sensor_type == "colour_temp":
            r, g, b, c = [int(x / 257) for x in value]
            RGB = np.array([r, g, b])
            XYZ = colour.sRGB_to_XYZ(RGB / 255)
            xy = colour.XYZ_to_xy(XYZ)
            CCT = colour.xy_to_CCT_Hernandez1999(xy)
            value = CCT

        if isinstance(value, numbers.Number):
            if hasattr(self, "multiplier"):
                value = value * self.multiplier
            if hasattr(self, "offset"):
                value = value + self.offset

        return value
Ejemplo n.º 14
0
def _rgb_to_ciexy(img: np.ndarray,
                  backend: Optional[str] = None,
                  **kwargs: Any) -> np.ndarray:
    """ not finished, finished part checked,

    convert `img` from the color space of RGB to the color space of CIExy

    Parameters
    ----------
    img: ndarray,
        the image, in the format (color space) RGB8, be converted to CIExy
    backend: str, default `_CVT_COLOR_BACKEND`, currently can be one in `_AVAILABLE_CVT_COLOR_BACKENDS`,
        the backend to perform the color space conversion
    kwargs: dict,
        not used, only to be compatible with other color space conversion functions

    Returns
    -------
    cie_xy: ndarray,
        `img` in the format (color space) of CIExy
    """
    if backend is None:
        # backend = _CVT_COLOR_BACKEND  # no such method in cv2
        backend = "colour-science"
    if backend.lower() == "cv2":
        pass
    elif backend.lower() == "colour-science":
        cie_xy = colour.XYZ_to_xy(
            _rgb_to_ciexyz(img, backend="colour-science", **kwargs))
    elif backend.lower() == "pil":
        pass
    elif backend.lower() == "naive":
        # default_white_point = np.array([0.3127, 0.3290, 0.0])
        # img_xyz = _rgb_to_ciexyz(img=img, backend=backend, **kwargs)
        pass
    return cie_xy
Ejemplo n.º 15
0
# -*- coding: utf-8 -*-
"""
Showcases correlated colour temperature computations.
"""

import colour
from colour.utilities import message_box

message_box('Correlated Colour Temperature Computations')

cmfs = colour.CMFS['CIE 1931 2 Degree Standard Observer']
illuminant = colour.ILLUMINANTS_SDS['D65']
xy = colour.XYZ_to_xy(colour.sd_to_XYZ(illuminant, cmfs) / 100)
uv = colour.UCS_to_uv(colour.XYZ_to_UCS(colour.xy_to_XYZ(xy)))
message_box(('Converting to "CCT" and "D_uv" from given "CIE UCS" colourspace '
             '"uv" chromaticity coordinates using "Ohno (2013)" method:\n'
             '\n\t{0}'.format(uv)))
print(colour.uv_to_CCT(uv, cmfs=cmfs))
print(colour.temperature.uv_to_CCT_Ohno2013(uv, cmfs=cmfs))

print('\n')

message_box('Faster computation with 3 iterations but a lot less precise.')
print(colour.uv_to_CCT(uv, cmfs=cmfs, iterations=3))
print(colour.temperature.uv_to_CCT_Ohno2013(uv, cmfs=cmfs, iterations=3))

print('\n')

message_box(('Converting to "CCT" and "D_uv" from given "CIE UCS" colourspace '
             '"uv" chromaticity coordinates using "Robertson (1968)" method:\n'
             '\n\t{0}'.format(uv)))
Ejemplo n.º 16
0
    def on_click4(self):  #foto
        stream = io.BytesIO()
        with picamera.PiCamera() as camera:
            camera.start_preview()
            time.sleep(2)
            camera.capture(stream, format='jpeg')
        # Construct a numpy array from the stream
        data = np.frombuffer(stream.getvalue(), dtype=np.uint8)
        # "Decode" the image from the array, preserving colour
        image = cv2.imdecode(data, 1)
        # OpenCV returns an array with data in BGR order. If you want RGB instead
        # use the following...
        image = image[:, :, ::-1]
        cv2.imwrite('original.png', image)

        pixmap = QtGui.QPixmap('./original.png').scaled(
            200, 180, QtCore.Qt.KeepAspectRatio)
        self.label_3.setPixmap(pixmap)

        image = image[150:190, 300:360]
        cv2.imwrite('escala.png', image)

        pixmap = QtGui.QPixmap('./escala.png').scaled(
            200, 180, QtCore.Qt.KeepAspectRatio)
        self.label_4.setPixmap(pixmap)

        ###########################################################
        #Promedio de pixeles#######################################
        ###########################################################
        r = image[:, :, 0]
        g = image[:, :, 1]
        b = image[:, :, 2]

        rp = r.sum() / (r.shape[0] * r.shape[1])
        gp = g.sum() / (g.shape[0] * g.shape[1])
        bp = b.sum() / (b.shape[0] * b.shape[1])
        ###########################################################
        #uso de la libreria colour-science para hallar los kelvin##
        ############################################################
        RGB = np.array([rp, gp, bp])

        # Conversion to tristimulus values.
        XYZ = colour.sRGB_to_XYZ(RGB / 255)

        # Conversion to chromaticity coordinates.
        xy = colour.XYZ_to_xy(XYZ)

        # Conversion to correlated colour temperature in K.
        CCT = colour.temperature.xy_to_CCT_Hernandez1999(xy)
        #rp,gp,bp
        self.CCT = CCT
        if self.CCT < 0:
            self.label_5.setText(
                _translate("MainWindow",
                           "KELVIN OUT: " + str("intenta de nuevo"), None))
        self.label_5.setText(
            _translate("MainWindow", "KELVIN OUT: " + str(round(self.CCT)),
                       None))

        offRed()
        offBlue()
        self.pushButton_4.setStyleSheet(
            _fromUtf8("background-color: rgb(29, 29, 29);"))
        print(self.CCT)
Ejemplo n.º 17
0
        return chi2

def gaussian3(x,p1,p2,p3):
    g=(p1*exp(-(x-440)**2)+p2*exp(-(x-530)**2)+p3*exp(-(x-620)**2))
    return g/sqrt(pi)

comp3=Chi2Functor(gaussian3,x,y)
describe(comp3)
m=Minuit(comp3,p1=1,p2=1,p3=1)
m.migrad();
print(m.values)
sample_spd_fit = {i:gaussian3(i,m.values['p1'],m.values['p2'],m.values['p3']) for i in x }

spd_fit = colour.SpectralPowerDistribution(sample_spd_fit)
XYZf = colour.spectral_to_XYZ(spd_fit, cmfs)
xy = colour.XYZ_to_xy(XYZ) # Conversion to correlated colour temperature in K. 
xyf =  colour.XYZ_to_xy(XYZf)
print("XYZ: ",XYZ)
print(xy)
print("XYZf: ",XYZf)
print(xyf)
#print(colour.delta_E(XYZ,XYZf))

# Plotting the *CIE 1931 Chromaticity Diagram*.
# The argument *standalone=False* is passed so that the plot doesn't get displayed
# and can be used as a basis for other plots.
chromaticity_diagram_plot_CIE1931(standalone=False)

# Plotting the *xy* chromaticity coordinates.
x, y = xy
xf,yf=xyf
Ejemplo n.º 18
0
 def cie_chrome(self):
     XYZ = [self.sam_L, self.sam_a, self.sam_b]
     xy = colour.XYZ_to_xy(XYZ)
     return xy
Ejemplo n.º 19
0
k = np.linspace(col1_k, col2_k, 15, endpoint=True)

rgb_c = np.empty((0, 3), dtype=np.float)
rgb = np.empty((0, 3), dtype=np.float)
#rgb = np.array(list(itertools.product(r,g,b)),dtype=np.float)
#print(rgb)
for idx in range(len(r)):
    rgb = np.append(rgb, np.array([[r[idx], g[idx], b[idx]]]), axis=0)

    r_c = 1 - min(1, c[idx] * (1 - k[idx]) + k[idx])
    g_c = 1 - min(1, m[idx] * (1 - k[idx]) + k[idx])
    b_c = 1 - min(1, y[idx] * (1 - k[idx]) + k[idx])
    rgb_c = np.append(rgb_c, np.array([[r_c, g_c, b_c]]), axis=0)

#sRGBからXYZへ変換
XYZ = colour.sRGB_to_XYZ(rgb)
XYZ_c = colour.sRGB_to_XYZ(rgb_c)
#XYZからxyへ変換
xy = colour.XYZ_to_xy(XYZ)
xy_c = colour.XYZ_to_xy(XYZ_c)

cp.plot_chromaticity_diagram_CIE1931(bounding_box=(-0.1, 0.9, -0.1, 0.9),
                                     standalone=False)

#sRGB領域へプロット

plt.plot(xy[:, 0], xy[:, 1], 'o', markersize=2, label="rgb")
plt.plot(xy_c[:, 0], xy_c[:, 1], 'o', markersize=2, label="cmyk")
plt.legend()

plt.savefig("r2g_4.jpg")
Ejemplo n.º 20
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Showcases correlated colour temperature computations.
"""

import colour
from colour.utilities.verbose import message_box

message_box('Correlated Colour Temperature Computations')

cmfs = colour.CMFS['CIE 1931 2 Degree Standard Observer']
illuminant = colour.ILLUMINANTS_RELATIVE_SPDS['D65']
xy = colour.XYZ_to_xy(colour.spectral_to_XYZ(illuminant, cmfs))
uv = colour.UCS_to_uv(colour.XYZ_to_UCS(colour.xy_to_XYZ(xy)))
message_box(('Converting to "CCT" and "D_uv" from given "CIE UCS" colourspace '
             '"uv" chromaticity coordinates using "Ohno (2013)" method:\n'
             '\n\t{0}'.format(uv)))
print(colour.uv_to_CCT_Ohno2013(uv, cmfs=cmfs))
print(colour.uv_to_CCT(uv, cmfs=cmfs))

print('\n')

message_box('Faster computation with 3 iterations but a lot less precise.')
print(colour.uv_to_CCT_Ohno2013(uv, cmfs=cmfs, iterations=3))

print('\n')

message_box(('Converting to "CCT" and "D_uv" from given "CIE UCS" colourspace '
             '"uv" chromaticity coordinates using "Robertson (1968)" method:\n'
             '\n\t{0}'.format(uv)))
Ejemplo n.º 21
0
data = response.json()
image_id = data['id']
url2 = data['image']
response = requests.get(url2)

with open(r'%s.jpg' %image_id,'wb') as f:
    f.write(response.content)

# Open the image. 
img_bgr = cv2.imread('%s.jpg' %image_id)
img = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2RGB)

#Apply gamma correction.
gamma = 2.4
gamma_img = np.array(255*(img / 255) ** gamma, dtype = 'uint8')

avg_color_gamma = gamma_img.mean(axis=0).mean(axis=0)
dominant_color_gamma = dominant(gamma_img)

XYZ1 = colour.sRGB_to_XYZ(dominant_color_gamma)


xy =  colour.XYZ_to_xy(XYZ1)

saveCIE(xy, image_id)

url = 'https://www.gyanvihar.org/arastu/uploads/'
files = {'image': open('%s.png' %image_id, 'rb')}
requests.post(url, files=files)

Ejemplo n.º 22
0
def convimg2rgb(ti):
    XYZ = colour.sRGB_to_XYZ(ti)
    xy = colour.XYZ_to_xy(XYZ)
    return xy,ti
Ejemplo n.º 23
0
def plotAll(lines = None, scatter = None, hue_lines = None,
            white_point = (1.0/3, 1.0/3), plots = 'all',
            base_filename = None, save_only = False):
    """
    Plot different plots all at once allowing to print lines and scatter data
    and saving the plots for external use.

    linse/scatter:  List of tuples or a single tuple (nparray, label) or
                    a tuple or ndarray only.
                    XYZ data with X/Y/Z in the last dimension.
    white_point:    White point of the XYZ data
    plots:          can be a list of kinds of plots, allowed are 'uv', 'xy', 'rec709',
                    'ictcp' and 'jzazbz'. A single plot can be given as an argument.
                    'all' gives all plots
    base_filename:  Filename to save the plots. "basename_{}.png" as a replacement
                    whith the plot name is applied.
    """

    def prepInput(data):
        res_data = []
        if isinstance(data, (np.ndarray, np.generic)):
            res_data.append((data,None))
        elif isinstance(data, tuple) and isinstance(data[0], (np.ndarray, np.generic)):
            label=None
            if len(data) > 1 and isinstance(data[1], str):
                label=data[1]
            res_data.append((data[0], label))
        elif isinstance(data, list):
            for el in data:
                if isinstance(el, (np.ndarray, np.generic)):
                    res_data.append((el,None))
                elif isinstance(el, tuple) and isinstance(el[0], (np.ndarray, np.generic)):
                    label=None
                    if len(el) > 1 and isinstance(el[1], str):
                        label=el[1]
                    res_data.append((el[0], label))
        return res_data


    if plots == 'all':
        plots = ['uv', 'xy', 'rec709', 'ictcp', 'jzazbz']

    if hue_lines == 'hung':
        tmp = getHungBernsData()
        hue_lines = [(tmp[0][x], tmp[1][x])  for x in range(0, len(tmp[0]), 2)]
    elif hue_lines == 'munsell':
        hue_lines = getMunsellData()

    intern_lines     = prepInput(lines)
    intern_scatter   = prepInput(scatter)
    intern_hue_lines = prepInput(hue_lines)

    xy_lines     = []
    xy_scatter   = []
    xy_hue_lines = []
    for xyz,label in intern_lines:
        xy_lines.append((colour.XYZ_to_xy(xyz, np.array(white_point)), label))
    for xyz,label in intern_scatter:
        xy_scatter.append((colour.XYZ_to_xy(xyz, np.array(white_point)), label))
    for xyz,label in intern_hue_lines:
        xy_hue_lines.append((colour.XYZ_to_xy(xyz, np.array(white_point)), label))
    
    if 'uv' in plots:
        plot_uv(lines=xy_lines, scatter=xy_scatter, hue_lines=xy_hue_lines, white_point=white_point,
                filename=base_filename, save_only=save_only)
    if 'xy' in plots:
        plot_xy(lines=xy_lines, scatter=xy_scatter, hue_lines=xy_hue_lines, white_point=white_point,
                filename=base_filename, save_only=save_only)

    if 'rec709' in plots:
        plot_ycbcr709(lines=intern_lines, scatter=intern_scatter, hue_lines=intern_hue_lines, white_point=white_point,
                      filename=base_filename, save_only=save_only)
    if 'ictcp' in plots:
        plot_ictcp(lines=intern_lines, scatter=intern_scatter, hue_lines=intern_hue_lines, white_point=white_point,
                   filename=base_filename, save_only=save_only)
    if 'jzazbz' in plots:
        plot_jzazbz(lines=intern_lines, scatter=intern_scatter, hue_lines=intern_hue_lines, white_point=white_point,
                    filename=base_filename, save_only=save_only)
Ejemplo n.º 24
0
print(colour.colorimetry.whiteness_Berger1959(XYZ, XYZ_0))

print("\n")

message_box(
    f'Computing "whiteness" using "Taube (1960)" method for given sample and '
    f'reference white "CIE XYZ" tristimulus values matrices:\n\n'
    f"\t{XYZ}\n"
    f"\t{XYZ_0}"
)
print(colour.whiteness(XYZ, XYZ_0, method="Taube 1960"))
print(colour.colorimetry.whiteness_Taube1960(XYZ, XYZ_0))

print("\n")

Lab = colour.XYZ_to_Lab(XYZ / 100, colour.XYZ_to_xy(XYZ_0 / 100))
message_box(
    f'Computing "whiteness" using "Stensby (1968)" method for given sample '
    f'"CIE L*a*b*" colourspace array:\n\n\t{Lab}'
)
print(colour.whiteness(XYZ, XYZ_0, method="Stensby 1968"))
print(colour.colorimetry.whiteness_Stensby1968(Lab))

print("\n")

message_box(
    f'Computing "whiteness" using "ASTM E313" method for given sample '
    f'"CIE XYZ" tristimulus values:\n\n\t{XYZ}'
)
print(colour.whiteness(XYZ, XYZ_0, method="ASTM E313"))
print(colour.colorimetry.whiteness_ASTME313(XYZ))
Ejemplo n.º 25
0
        colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D60']))

print('\n')

xyY = (0.4325, 0.3788, 1.0000)
message_box(('Converting to "CIE XYZ" tristimulus values from given "CIE xyY" '
             'colourspace values:\n'
             '\n\t{0}'.format(xyY)))
print(colour.xyY_to_XYZ(xyY))

print('\n')

message_box(('Converting to "xy" chromaticity coordinates from given '
             '"CIE XYZ" tristimulus values:\n'
             '\n\t{0}'.format(XYZ)))
print(colour.XYZ_to_xy(XYZ))

print('\n')

xy = (0.43250000, 0.37880000)
message_box(('Converting to "CIE XYZ" tristimulus values from given "xy" '
             'chromaticity coordinates:\n'
             '\n\t{0}'.format(xy)))
print(colour.xy_to_XYZ(xy))

print('\n')

message_box(('Converting to "RGB" colourspace from given "CIE XYZ" '
             'tristimulus values:\n'
             '\n\t{0}'.format(XYZ)))
D50 = colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D50']
Ejemplo n.º 26
0
def VCC_VAC(xy, xy_wp, weight):
    return (VCC(xy, xy_wp) * (1.0 - weight) + VAC(xy, xy_wp) * weight)


wp_C = [0.31006, 0.31616]
wp_D65 = [0.31271, 0.32902]

##################################################################################################

grey_colour = colour.notation.RGB_to_HEX([Y_sRGB, Y_sRGB, Y_sRGB])

plot_patches("images/equal_Y.png", patches_XYZ, grey_colour)

weight_vcc_vac = 0.5

whitepoint = wp_C
bg_xy = colour.XYZ_to_xy(colour.sRGB_to_XYZ([Y_sRGB, Y_sRGB, Y_sRGB]))
bg_vcc = VCC_VAC(bg_xy, whitepoint, weight_vcc_vac)

print("BG fac = " + str(bg_vcc))

#Try to compensate the patches
for i in range(0, len(patches_XYZ)):
    patch = patches_XYZ[i]
    patch_xy = colour.XYZ_to_xy(patch)
    Leq_L = VCC_VAC(patch_xy, whitepoint, weight_vcc_vac)
    fac = bg_vcc / Leq_L
    print("Luminance factor for patch " + str(i) + " = " + str(fac))
    patch *= pow(fac, 1)

plot_patches("images/HKE_compensated.png", patches_XYZ, grey_colour)
Ejemplo n.º 27
0
def detect_breaking_events(time,
                           crx_dist,
                           rgb,
                           crx_start=None,
                           crx_end=None,
                           px_mtrc="lightness",
                           colours=None,
                           resample_rule="100L",
                           algorithm="peaks",
                           peak_detection="local_maxima",
                           posterize=False,
                           ncolours=0,
                           threshold=0.1,
                           tswindow=11,
                           denoise=True,
                           pxwindow=3,
                           mask_drysand=False,
                           fix_constrast=False):
    """
    Detect wave breaking events.

    Two main methods are implemented:

    1 - Peak detection: detect wave breaking as lightness peaks in the
                        timestack

        Two peak detection methods are implemented:

        1-a Local maxima. Uses peaklocalextremas() function from pywavelearn
                          to detect local maximas corresponding to wave
                          breaking.

        1-b Differential. Uses the first temporal derivative of the pixel
                          intensity to detect sharp transitions in the
                          timestack that should correspond to wave breaking.

        In both cases, the user can tell to the script to classifiy the
        identified pixel peaks based on known colours. For exemple, water is
        usually blue, sand is brownish and breaking waves are whiteish.
        Only peaks corresponding to wave breakin are append to the output
        structure. This is step done using classifiy_colour()
        from pywavelearn.

    2 - Edge detection: detect wave breaking as sharp edges in the timestack

        Two-options are available:

        2-a Edges only. Wave breaking events are obtained applying a sobel
                        filter to the timestack. Edge locations (time,space)
                        are obrained as:

                        - argument of the maxima (argmax) of a cross-shore
                          pixel intenstiy series obtained at every timestamp.

                        - local maximas of a cross-shore pixel intenstiy series
                          obtained at every timestamp.

        2-b Edges and colours. Wave breaking events are obtained applying a
                               Sobel filter to the timestack and the detected
                               Edges are classified using the colour
                               information as in 1-a. Edge locations
                               (time,space) are obrained as:

                               - argument of the maxima (argmax) of a
                                 cross-shore pixel intenstiy series obtained
                                 at every timestamp.


                               - local maximas of a cross-shore pixel intenstiy
                                 series obtained at every timestamp.
    ----------
    Args:
        time (Mandatory [np.array]): Array of datetimes.

        crx_dist (Mandatory [np.array]): Array of cross-shore locations.

        rgb (Mandatory [np.array]): timestack array.
                                    Shape is [time,crx_dist,3].

        crx_start (Optional [float]): where in the cross-shore orientation to
                                       start the analysis.
                                       Default is crx_dist.min().

        crx_start (Optional [float]): where in the cross-shore orientation to
                                       finish the analysis.
                                       Default is crx_dist.max().

        px_mtrc (Optional [float]): Which pixel intenstiy metric to use.
                                    Default is "lightness".

        resample_rule (Optional [str]): To which frequency interpolate
                                        timeseries Default is  "100L".

        algorithm (Optional [str]): Wave breaking detection algorithm.
                                    Default is "peaks".

        peak_detection (Optional [str]): Peak detection algorithm.
                                         Default is  "local_maxima".

        threshold (Optional [float]): Threshold for peak detection algorithm.
                                      Default is 0.1

        tswindow (Optional [int]): Window for peak detection algorithm.
                                   Default is 11.

        denoise (Optional [bool]): = Denoise timestack using denoise_bilateral
                                     Default is True.

        pxwindow (Optional [int]): Window for denoise_bilateral. Default is 3.

        posterize (Optional [bool]): If true will reduce the number of colours
                                     in the timestack. Default is False.

        ncolours (Optional [str]): Number of colours to posterize.
                                   Default is 16.

        colours (Optional [dict]): A dictionary for the colour learning step.
                                    Something like:
                                    train_colours = {'labels':[0,1,2],
                                                     'aliases':
                                                     ["sand","water","foam"],
                                                     'rgb':[[195,185,155],
                                                            [30,75,75],
                                                            [255,255,255]]
                                                     'target':2}
                                    Default is None.

        mask_drysand (Experimental [bool]) = Mask dry sand using a
                                             colour-temperature (CCT)
                                             relationship. Default is False.
    ----------
    Return:
         time (Mandatory [np.array]): time of occurance of wave breaking
                                      events.

         breakers (Mandatory [np.array]): cross-shore location of wave breaking
                                          events.
    """
    if not crx_start:
        crx_start = crx_dist.min()
        crx_end = crx_dist.max()

    if posterize:
        print("  + >> posterizing")
        rgb = colour_quantization(rgb, ncolours=ncolours)

    # get colour data
    if algorithm == "colour" or algorithm == "edges_and_colour":
        target = colours["target"]
        labels = colours["labels"]
        dom_colours = colours["rgb"]

    # denoise a little bedore computing edges
    if denoise:
        rgb = denoise_bilateral(rgb, pxwindow, multichannel=True)
        # scale back to 0-255
        rgb = (rgb - rgb.min()) / (rgb.max() - rgb.min()) * 255

    # mask sand - Not fully tested
    if mask_drysand:
        print("  + >> masking dry sand [Experimental]")
        # calculate colour temperature
        cct = colour.xy_to_CCT_Hernandez1999(
            colour.XYZ_to_xy(colour.sRGB_to_XYZ(rgb / 255)))
        # scale back to 0-1
        cct = (cct - cct.min()) / (cct.max() - cct.min()) * 255
        # mask
        i, j = np.where(cct == 0)
        rgb[i, j, :] = 0

    if fix_constrast:
        print("  + >> fixing contrast")
        rgb = exposure.equalize_hist(rgb)
        # rgb = (rgb-rgb.min())/(rgb.max()-rgb.min())*255

    # detect edges
    if algorithm == "edges" or algorithm == "edges_and_colour":
        print("  + >> calculating edges")
        edges = sobel_h(rgb2grey(rgb))

    # get pixel lines and RGB values at selected locations only
    if algorithm == "peaks" or algorithm == "colour":
        print("  + >> extracting cross-shore pixels")
        # rescale
        rgb = (rgb - rgb.min()) / (rgb.max() - rgb.min()) * 255
        Y, crx_idx = get_analysis_locations(crx_dist, crx_start, crx_end)
        Time, PxInts, RGB = get_pixel_lines(time,
                                            rgb,
                                            crx_idx,
                                            resample_rule=resample_rule,
                                            pxmtc=px_mtrc)

    # get analysis frequency and a 1 sececond time window
    if not tswindow:
        fs = (time[1] - time[0]).total_seconds()
        win = np.int((1 / fs))
    else:
        win = tswindow

    print("  + >> detecting breaking events")
    PeakTimes = []
    print_check = False
    if algorithm == "peaks" or algorithm == "colour":
        if peak_detection == "argmax":
            peak_detection = "local_maxima"
            print("  - >> setting peak detection to local maxima")
        # loop over data rows
        for pxint, rgb in zip(PxInts, RGB):
            # calculate baseline
            bline = baseline(pxint, 2)
            # calculate pixel peaks
            if peak_detection == "local_maxima":
                _, max_idx = peaklocalextremas(pxint - bline,
                                               lookahead=win,
                                               delta=threshold *
                                               (pxint - bline).max())
            elif peak_detection == "differential":
                # calculate first derivative
                pxintdt = np.diff(pxint - bline)
                # remove values below zero
                pxintdt[pxintdt <= 0] = 0
                # scale from 0 to 1
                pxintdt = pxintdt / pxintdt.max()
                # get indexes
                max_idx = indexes(pxintdt, thres=threshold, min_dist=win)
            else:
                raise ValueError
            # colour learning step
            if algorithm == "colour":
                if not print_check:
                    print("  + >> colour learning")
                    print_check = True
                # classifiy pixels
                breaker_idxs = []
                for idx in max_idx:
                    y_pred = classify_colour(rgb[idx], dom_colours, labels)
                    if y_pred[0] == target:
                        breaker_idxs.append(idx)
            # peaks only
            else:
                breaker_idxs = max_idx
            PeakTimes.append(Time[breaker_idxs])
        # organize peaks and times
        Xpeaks = []
        Ypeaks = []
        for i, pxtimes in enumerate(PeakTimes):
            for v in pxtimes:
                Xpeaks.append(v)
            for v in np.ones(len(pxtimes)) * Y[i]:
                Ypeaks.append(v)
    # edges case
    if algorithm == "edges":
        Xpeaks = []
        Ypeaks = []
        # loop in time
        for i, t in enumerate(time):
            # cross-shore line
            crx_line = edges[i, :]
            # peaks with robust peak detection
            if peak_detection == "differential" or \
               peak_detection == "local_maxima":
                crx_line = (crx_line - crx_line.min()) / (crx_line.max() -
                                                          crx_line.min())
                if not np.all(crx_line == 0):
                    idx_peak = indexes(crx_line,
                                       thres=1 - threshold,
                                       min_dist=win)
                # apped peaks
                for peak in idx_peak:
                    if crx_dist[peak] > crx_start and crx_dist[peak] < crx_end:
                        Xpeaks.append(t)
                        Ypeaks.append(crx_dist[peak])
            # peaks with simple argmax - works better without colour learning
            else:
                peak = np.argmax(crx_line)
                if crx_dist[peak] > crx_start and crx_dist[peak] < crx_end:
                    Xpeaks.append(t)
                    Ypeaks.append(crx_dist[peak])
    # edges + colour learning case
    if algorithm == "edges_and_colour":
        Ipeaks = []
        Jpeaks = []
        # loop in time
        for i, t in enumerate(time):
            # cross-shore line
            crx_line = edges[i, :]
            if peak_detection == "differential" or \
               peak_detection == "local_maxima":
                crx_line = (crx_line - crx_line.min()) / (crx_line.max() -
                                                          crx_line.min())
                # peaks
                if not np.all(crx_line == 0):
                    idx_peak = indexes(crx_line,
                                       thres=1 - threshold,
                                       min_dist=win)
                    if not np.all(crx_line == 0):
                        idx_peak = indexes(crx_line,
                                           thres=1 - threshold,
                                           min_dist=win)
                # apped peaks
                for peak in idx_peak:
                    if crx_dist[peak] > crx_start and crx_dist[peak] < crx_end:
                        Ipeaks.append(i)
                        Jpeaks.append(peak)
            else:
                peak = np.argmax(crx_line)
                if crx_dist[peak] > crx_start and crx_dist[peak] < crx_end:
                    Ipeaks.append(i)
                    Jpeaks.append(peak)
        # colour learning step
        Xpeaks = []
        Ypeaks = []
        for i, j in zip(Ipeaks, Jpeaks):
            if not print_check:
                print("  + >> colour learning")
                print_check = True
            # classify colour
            y_pred = classify_colour(rgb[i, j, :], dom_colours, labels)
            if y_pred[0] == target:
                Xpeaks.append(time[i])
                Ypeaks.append(crx_dist[j])

    # sort values in time and outout
    y = np.array(Ypeaks)[np.argsort(date2num(Xpeaks))]
    x = np.array(Xpeaks)[np.argsort(Xpeaks)]

    return ellapsedseconds(x), y
Ejemplo n.º 28
0
def color_to_temperature(color):
    xyz = colour.sRGB_to_XYZ(
        numpy.array([color.red, color.green, color.blue]) / 255)
    return colour.xy_to_CCT(colour.XYZ_to_xy(xyz), 'hernandez1999')
Ejemplo n.º 29
0
def generate_documentation_plots(output_directory):
    """
    Generates documentation plots.

    Parameters
    ----------
    output_directory : unicode
        Output directory.
    """

    colour.utilities.filter_warnings()

    colour_style()

    np.random.seed(0)

    # *************************************************************************
    # "README.rst"
    # *************************************************************************
    arguments = {
        'tight_layout':
            True,
        'transparent_background':
            True,
        'filename':
            os.path.join(output_directory,
                         'Examples_Plotting_Visible_Spectrum.png')
    }
    plot_visible_spectrum('CIE 1931 2 Degree Standard Observer', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Examples_Plotting_Illuminant_F1_SD.png')
    plot_single_illuminant_sd('FL1', **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Examples_Plotting_Blackbodies.png')
    blackbody_sds = [
        colour.sd_blackbody(i, colour.SpectralShape(0, 10000, 10))
        for i in range(1000, 15000, 1000)
    ]
    plot_multi_sds(
        blackbody_sds,
        y_label='W / (sr m$^2$) / m',
        use_sds_colours=True,
        normalise_sds_colours=True,
        legend_location='upper right',
        bounding_box=(0, 1250, 0, 2.5e15),
        **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Examples_Plotting_Cone_Fundamentals.png')
    plot_single_cmfs(
        'Stockman & Sharpe 2 Degree Cone Fundamentals',
        y_label='Sensitivity',
        bounding_box=(390, 870, 0, 1.1),
        **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Examples_Plotting_Luminous_Efficiency.png')
    sd_mesopic_luminous_efficiency_function = (
        colour.sd_mesopic_luminous_efficiency_function(0.2))
    plot_multi_sds(
        (sd_mesopic_luminous_efficiency_function,
         colour.PHOTOPIC_LEFS['CIE 1924 Photopic Standard Observer'],
         colour.SCOTOPIC_LEFS['CIE 1951 Scotopic Standard Observer']),
        y_label='Luminous Efficiency',
        legend_location='upper right',
        y_tighten=True,
        margins=(0, 0, 0, .1),
        **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Examples_Plotting_BabelColor_Average.png')
    plot_multi_sds(
        colour.COLOURCHECKERS_SDS['BabelColor Average'].values(),
        use_sds_colours=True,
        title=('BabelColor Average - '
               'Spectral Distributions'),
        **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Examples_Plotting_ColorChecker_2005.png')
    plot_single_colour_checker(
        'ColorChecker 2005', text_parameters={'visible': False}, **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Examples_Plotting_Chromaticities_Prediction.png')
    plot_corresponding_chromaticities_prediction(2, 'Von Kries', 'Bianco',
                                                 **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Examples_Plotting_CCT_CIE_1960_UCS_Chromaticity_Diagram.png')
    plot_planckian_locus_in_chromaticity_diagram_CIE1960UCS(['A', 'B', 'C'],
                                                            **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Examples_Plotting_Chromaticities_CIE_1931_Chromaticity_Diagram.png')
    RGB = np.random.random((32, 32, 3))
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1931(
        RGB,
        'ITU-R BT.709',
        colourspaces=['ACEScg', 'S-Gamut'],
        show_pointer_gamut=True,
        **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Examples_Plotting_CRI.png')
    plot_single_sd_colour_rendering_index_bars(colour.ILLUMINANTS_SDS['FL2'],
                                               **arguments)

    # *************************************************************************
    # Documentation
    # *************************************************************************
    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_CVD_Simulation_Machado2009.png')
    plot_cvd_simulation_Machado2009(RGB, **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_Colour_Checker.png')
    plot_single_colour_checker('ColorChecker 2005', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Multi_Colour_Checkers.png')
    plot_multi_colour_checkers(['ColorChecker 1976', 'ColorChecker 2005'],
                               **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Single_SD.png')
    data = {
        500: 0.0651,
        520: 0.0705,
        540: 0.0772,
        560: 0.0870,
        580: 0.1128,
        600: 0.1360
    }
    sd = colour.SpectralDistribution(data, name='Custom')
    plot_single_sd(sd, **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Multi_SDs.png')
    data_1 = {
        500: 0.004900,
        510: 0.009300,
        520: 0.063270,
        530: 0.165500,
        540: 0.290400,
        550: 0.433450,
        560: 0.594500
    }
    data_2 = {
        500: 0.323000,
        510: 0.503000,
        520: 0.710000,
        530: 0.862000,
        540: 0.954000,
        550: 0.994950,
        560: 0.995000
    }
    spd1 = colour.SpectralDistribution(data_1, name='Custom 1')
    spd2 = colour.SpectralDistribution(data_2, name='Custom 2')
    plot_multi_sds([spd1, spd2], **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Single_CMFS.png')
    plot_single_cmfs('CIE 1931 2 Degree Standard Observer', **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Multi_CMFS.png')
    cmfs = ('CIE 1931 2 Degree Standard Observer',
            'CIE 1964 10 Degree Standard Observer')
    plot_multi_cmfs(cmfs, **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_Illuminant_SD.png')
    plot_single_illuminant_sd('A', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Multi_Illuminant_SDs.png')
    plot_multi_illuminant_sds(['A', 'B', 'C'], **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Visible_Spectrum.png')
    plot_visible_spectrum(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_Lightness_Function.png')
    plot_single_lightness_function('CIE 1976', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Multi_Lightness_Functions.png')
    plot_multi_lightness_functions(['CIE 1976', 'Wyszecki 1963'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_Luminance_Function.png')
    plot_single_luminance_function('CIE 1976', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Multi_Luminance_Functions.png')
    plot_multi_luminance_functions(['CIE 1976', 'Newhall 1943'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Blackbody_Spectral_Radiance.png')
    plot_blackbody_spectral_radiance(
        3500, blackbody='VY Canis Major', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Blackbody_Colours.png')
    plot_blackbody_colours(colour.SpectralShape(150, 12500, 50), **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_Colour_Swatch.png')
    RGB = ColourSwatch(RGB=(0.32315746, 0.32983556, 0.33640183))
    plot_single_colour_swatch(RGB, **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Multi_Colour_Swatches.png')
    RGB_1 = ColourSwatch(RGB=(0.45293517, 0.31732158, 0.26414773))
    RGB_2 = ColourSwatch(RGB=(0.77875824, 0.57726450, 0.50453169))
    plot_multi_colour_swatches([RGB_1, RGB_2], **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Single_Function.png')
    plot_single_function(lambda x: x ** (1 / 2.2), **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Multi_Functions.png')
    functions = {
        'Gamma 2.2': lambda x: x ** (1 / 2.2),
        'Gamma 2.4': lambda x: x ** (1 / 2.4),
        'Gamma 2.6': lambda x: x ** (1 / 2.6),
    }
    plot_multi_functions(functions, **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Image.png')
    path = os.path.join(colour.__path__[0], '..', 'docs', '_static',
                        'Logo_Medium_001.png')
    plot_image(colour.read_image(str(path)), **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Corresponding_Chromaticities_Prediction.png')
    plot_corresponding_chromaticities_prediction(1, 'Von Kries', 'CAT02',
                                                 **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Spectral_Locus.png')
    plot_spectral_locus(spectral_locus_colours='RGB', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Chromaticity_Diagram_Colours.png')
    plot_chromaticity_diagram_colours(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Chromaticity_Diagram.png')
    plot_chromaticity_diagram(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Chromaticity_Diagram_CIE1931.png')
    plot_chromaticity_diagram_CIE1931(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Chromaticity_Diagram_CIE1960UCS.png')
    plot_chromaticity_diagram_CIE1960UCS(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Chromaticity_Diagram_CIE1976UCS.png')
    plot_chromaticity_diagram_CIE1976UCS(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_SDs_In_Chromaticity_Diagram.png')
    A = colour.ILLUMINANTS_SDS['A']
    D65 = colour.ILLUMINANTS_SDS['D65']
    plot_sds_in_chromaticity_diagram([A, D65], **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_SDs_In_Chromaticity_Diagram_CIE1931.png')
    plot_sds_in_chromaticity_diagram_CIE1931([A, D65], **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_SDs_In_Chromaticity_Diagram_CIE1960UCS.png')
    plot_sds_in_chromaticity_diagram_CIE1960UCS([A, D65], **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_SDs_In_Chromaticity_Diagram_CIE1976UCS.png')
    plot_sds_in_chromaticity_diagram_CIE1976UCS([A, D65], **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Pointer_Gamut.png')
    plot_pointer_gamut(**arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_RGB_Colourspaces_In_Chromaticity_Diagram.png')
    plot_RGB_colourspaces_in_chromaticity_diagram(
        ['ITU-R BT.709', 'ACEScg', 'S-Gamut'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_RGB_Colourspaces_In_Chromaticity_Diagram_CIE1931.png')
    plot_RGB_colourspaces_in_chromaticity_diagram_CIE1931(
        ['ITU-R BT.709', 'ACEScg', 'S-Gamut'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Colourspaces_In_'
        'Chromaticity_Diagram_CIE1960UCS.png')
    plot_RGB_colourspaces_in_chromaticity_diagram_CIE1960UCS(
        ['ITU-R BT.709', 'ACEScg', 'S-Gamut'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Colourspaces_In_'
        'Chromaticity_Diagram_CIE1976UCS.png')
    plot_RGB_colourspaces_in_chromaticity_diagram_CIE1976UCS(
        ['ITU-R BT.709', 'ACEScg', 'S-Gamut'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Chromaticities_In_'
        'Chromaticity_Diagram_Plot.png')
    RGB = np.random.random((128, 128, 3))
    plot_RGB_chromaticities_in_chromaticity_diagram(RGB, 'ITU-R BT.709',
                                                    **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Chromaticities_In_'
        'Chromaticity_Diagram_CIE1931.png')
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1931(
        RGB, 'ITU-R BT.709', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Chromaticities_In_'
        'Chromaticity_Diagram_CIE1960UCS.png')
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1960UCS(
        RGB, 'ITU-R BT.709', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Chromaticities_In_'
        'Chromaticity_Diagram_CIE1976UCS.png')
    plot_RGB_chromaticities_in_chromaticity_diagram_CIE1976UCS(
        RGB, 'ITU-R BT.709', **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Ellipses_MacAdam1942_In_Chromaticity_Diagram.png')
    plot_ellipses_MacAdam1942_in_chromaticity_diagram(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Ellipses_MacAdam1942_In_'
        'Chromaticity_Diagram_CIE1931.png')
    plot_ellipses_MacAdam1942_in_chromaticity_diagram_CIE1931(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Ellipses_MacAdam1942_In_'
        'Chromaticity_Diagram_CIE1960UCS.png')
    plot_ellipses_MacAdam1942_in_chromaticity_diagram_CIE1960UCS(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Ellipses_MacAdam1942_In_'
        'Chromaticity_Diagram_CIE1976UCS.png')
    plot_ellipses_MacAdam1942_in_chromaticity_diagram_CIE1976UCS(**arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Single_CCTF.png')
    plot_single_cctf('ITU-R BT.709', **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Multi_CCTFs.png')
    plot_multi_cctfs(['ITU-R BT.709', 'sRGB'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_Munsell_Value_Function.png')
    plot_single_munsell_value_function('ASTM D1535-08', **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Multi_Munsell_Value_Functions.png')
    plot_multi_munsell_value_functions(['ASTM D1535-08', 'McCamy 1987'],
                                       **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Single_SD_Rayleigh_Scattering.png')
    plot_single_sd_rayleigh_scattering(**arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_The_Blue_Sky.png')
    plot_the_blue_sky(**arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_Colour_Quality_Bars.png')
    illuminant = colour.ILLUMINANTS_SDS['FL2']
    light_source = colour.LIGHT_SOURCES_SDS['Kinoton 75P']
    light_source = light_source.copy().align(colour.SpectralShape(360, 830, 1))
    cqs_i = colour.colour_quality_scale(illuminant, additional_data=True)
    cqs_l = colour.colour_quality_scale(light_source, additional_data=True)
    plot_colour_quality_bars([cqs_i, cqs_l], **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Single_SD_Colour_Rendering_Index_Bars.png')
    illuminant = colour.ILLUMINANTS_SDS['FL2']
    plot_single_sd_colour_rendering_index_bars(illuminant, **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Multi_SDs_Colour_Rendering_Indexes_Bars.png')
    light_source = colour.LIGHT_SOURCES_SDS['Kinoton 75P']
    plot_multi_sds_colour_rendering_indexes_bars([illuminant, light_source],
                                                 **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Single_SD_Colour_Quality_Scale_Bars.png')
    illuminant = colour.ILLUMINANTS_SDS['FL2']
    plot_single_sd_colour_quality_scale_bars(illuminant, **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Multi_SDs_Colour_Quality_Scales_Bars.png')
    light_source = colour.LIGHT_SOURCES_SDS['Kinoton 75P']
    plot_multi_sds_colour_quality_scales_bars([illuminant, light_source],
                                              **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_Planckian_Locus.png')
    plot_planckian_locus(**arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Planckian_Locus_In_Chromaticity_Diagram.png')
    plot_planckian_locus_in_chromaticity_diagram(['A', 'B', 'C'], **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Planckian_Locus_In_Chromaticity_Diagram_CIE1931.png')
    plot_planckian_locus_in_chromaticity_diagram_CIE1931(['A', 'B', 'C'],
                                                         **arguments)

    arguments['filename'] = os.path.join(
        output_directory,
        'Plotting_Plot_Planckian_Locus_In_Chromaticity_Diagram_CIE1960UCS.png')
    plot_planckian_locus_in_chromaticity_diagram_CIE1960UCS(['A', 'B', 'C'],
                                                            **arguments)
    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Colourspaces_Gamuts.png')
    plot_RGB_colourspaces_gamuts(['ITU-R BT.709', 'ACEScg', 'S-Gamut'],
                                 **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Plotting_Plot_RGB_Colourspaces_Gamuts.png')
    plot_RGB_colourspaces_gamuts(['ITU-R BT.709', 'ACEScg', 'S-Gamut'],
                                 **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Plotting_Plot_RGB_Scatter.png')
    plot_RGB_scatter(RGB, 'ITU-R BT.709', **arguments)

    # *************************************************************************
    # "tutorial.rst"
    # *************************************************************************
    arguments['filename'] = os.path.join(output_directory,
                                         'Tutorial_Visible_Spectrum.png')
    plot_visible_spectrum(**arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Tutorial_Sample_SD.png')
    sample_sd_data = {
        380: 0.048,
        385: 0.051,
        390: 0.055,
        395: 0.060,
        400: 0.065,
        405: 0.068,
        410: 0.068,
        415: 0.067,
        420: 0.064,
        425: 0.062,
        430: 0.059,
        435: 0.057,
        440: 0.055,
        445: 0.054,
        450: 0.053,
        455: 0.053,
        460: 0.052,
        465: 0.052,
        470: 0.052,
        475: 0.053,
        480: 0.054,
        485: 0.055,
        490: 0.057,
        495: 0.059,
        500: 0.061,
        505: 0.062,
        510: 0.065,
        515: 0.067,
        520: 0.070,
        525: 0.072,
        530: 0.074,
        535: 0.075,
        540: 0.076,
        545: 0.078,
        550: 0.079,
        555: 0.082,
        560: 0.087,
        565: 0.092,
        570: 0.100,
        575: 0.107,
        580: 0.115,
        585: 0.122,
        590: 0.129,
        595: 0.134,
        600: 0.138,
        605: 0.142,
        610: 0.146,
        615: 0.150,
        620: 0.154,
        625: 0.158,
        630: 0.163,
        635: 0.167,
        640: 0.173,
        645: 0.180,
        650: 0.188,
        655: 0.196,
        660: 0.204,
        665: 0.213,
        670: 0.222,
        675: 0.231,
        680: 0.242,
        685: 0.251,
        690: 0.261,
        695: 0.271,
        700: 0.282,
        705: 0.294,
        710: 0.305,
        715: 0.318,
        720: 0.334,
        725: 0.354,
        730: 0.372,
        735: 0.392,
        740: 0.409,
        745: 0.420,
        750: 0.436,
        755: 0.450,
        760: 0.462,
        765: 0.465,
        770: 0.448,
        775: 0.432,
        780: 0.421
    }

    sd = colour.SpectralDistribution(sample_sd_data, name='Sample')
    plot_single_sd(sd, **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Tutorial_SD_Interpolation.png')
    sd_copy = sd.copy()
    sd_copy.interpolate(colour.SpectralShape(400, 770, 1))
    plot_multi_sds(
        [sd, sd_copy], bounding_box=[730, 780, 0.25, 0.5], **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Tutorial_Sample_Swatch.png')
    sd = colour.SpectralDistribution(sample_sd_data)
    cmfs = colour.STANDARD_OBSERVERS_CMFS[
        'CIE 1931 2 Degree Standard Observer']
    illuminant = colour.ILLUMINANTS_SDS['D65']
    with domain_range_scale('1'):
        XYZ = colour.sd_to_XYZ(sd, cmfs, illuminant)
        RGB = colour.XYZ_to_sRGB(XYZ)
    plot_single_colour_swatch(
        ColourSwatch('Sample', RGB),
        text_parameters={'size': 'x-large'},
        **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Tutorial_Neutral5.png')
    patch_name = 'neutral 5 (.70 D)'
    patch_sd = colour.COLOURCHECKERS_SDS['ColorChecker N Ohta'][patch_name]
    with domain_range_scale('1'):
        XYZ = colour.sd_to_XYZ(patch_sd, cmfs, illuminant)
        RGB = colour.XYZ_to_sRGB(XYZ)
    plot_single_colour_swatch(
        ColourSwatch(patch_name.title(), RGB),
        text_parameters={'size': 'x-large'},
        **arguments)

    arguments['filename'] = os.path.join(output_directory,
                                         'Tutorial_Colour_Checker.png')
    plot_single_colour_checker(
        colour_checker='ColorChecker 2005',
        text_parameters={'visible': False},
        **arguments)

    arguments['filename'] = os.path.join(
        output_directory, 'Tutorial_CIE_1931_Chromaticity_Diagram.png')
    xy = colour.XYZ_to_xy(XYZ)
    plot_chromaticity_diagram_CIE1931(standalone=False)
    x, y = xy
    plt.plot(x, y, 'o-', color='white')
    # Annotating the plot.
    plt.annotate(
        patch_sd.name.title(),
        xy=xy,
        xytext=(-50, 30),
        textcoords='offset points',
        arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=-0.2'))
    render(
        standalone=True,
        limits=(-0.1, 0.9, -0.1, 0.9),
        x_tighten=True,
        y_tighten=True,
        **arguments)

    # *************************************************************************
    # "basics.rst"
    # *************************************************************************
    arguments['filename'] = os.path.join(output_directory,
                                         'Basics_Logo_Small_001_CIE_XYZ.png')
    RGB = colour.read_image(
        os.path.join(output_directory, 'Logo_Small_001.png'))[..., 0:3]
    XYZ = colour.sRGB_to_XYZ(RGB)
    colour.plotting.plot_image(
        XYZ, text_parameters={'text': 'sRGB to XYZ'}, **arguments)
Ejemplo n.º 30
0
def get_artwork_colors():
    
# Define scope
    scope = 'current_user_playing_track user-read-private user-read-playback-state user-modify-playback-state'

# Obtain Spotify Token (username, client_id, and client_secret will vary per user - for additional information see Spotify API documentation.)
    try:
        token = util.prompt_for_user_token("Chris Penny", client_id='dd41386aabca41aa8dd7ba2f947782b3',client_secret='4bf7eefcbf7241298d92b9f5ad6fe3f0',redirect_uri='http://google.com/')
# Error Case - Remove token cache and replace
    except (AttributeError, JSONDE):
        os.remove(f".cache-{username}")
        token = util.prompt_for_user_token("Chris Penny", client_id='dd41386aabca41aa8dd7ba2f947782b3',client_secret='4bf7eefcbf7241298d92b9f5ad6fe3f0',redirect_uri='http://google.com/')

# Generate spotipy object using Spotify Token
    spot_obj = spotipy.Spotify(auth=token)

# Call spotipy attribute for the currently playing track
    track = spot_obj.current_user_playing_track()
    #print(list(track)) # For Debug

# NOTE: While the current_user_playing_track() attribute results in a dictionary, the album art image URL is not assigned to a key and must be extracted by parsing.
    items = track['item']
    
# Convert dictionary object to string and parse the album art image URL.
    string_items = str(items)
    image_loc = string_items.find('images')
    image_loc_end = string_items.find('width', image_loc)
    image_url = string_items[image_loc+34:image_loc_end-4]

# Use the urllib library to save the image as a temporary file in a sub-directory.
    req.urlretrieve(image_url, "Temporary Image Directory/temp_artwork.jpg")
    #print(image_url) # For Debug

    album_art_test = Image.open("Temporary Image Directory/temp_artwork.jpg").convert("L")
    album_art = Image.open("Temporary Image Directory/temp_artwork.jpg")
#    print(album_art.mode) # For Debug

    histogram = album_art.histogram()
#    print(rgb_data) # For Debug

# Convert image to a numpy array.
    rgb_tuples = np.asarray(album_art)
#    print(rgb_tuples) # For Debug
#    print(type(rgb_tuples.shape)) # For Debug

# Stack with Numpy
    for i in range(0, len(rgb_tuples)):
        if i==0:
            np_stack = rgb_tuples[i]
        if i > 0:
            np_stack = np.vstack((np_stack, rgb_tuples[i]))

#    print(np.shape(np_stack)) # For Debug

    pd_rgb_stack = pd.DataFrame(np_stack, columns = ['r', 'g', 'b'])
    pd_rgb_stack['rgb'] = (pd_rgb_stack['r'].astype(str)) + '_' + (pd_rgb_stack['g'].astype(str)) + '_' + (pd_rgb_stack['b'].astype(str))
    pd_rgb_stack['check_sum'] = pd_rgb_stack[['r', 'b', 'g']].sum(axis=1)
#    print(pd_rgb_stack['check_sum'].head(20)) # For Debug
    check_sum_mean = pd_rgb_stack['check_sum'].mean()
#    print(check_sum_mean) # For Debug


#   Sort by Value Counts to find modal values and return in order of frequency
    pd_rgb_sorted = pd_rgb_stack['rgb'].value_counts().to_frame()
    pd_rgb_sorted.astype(int)
#    print(pd_rgb_sorted.iloc[0]) # For Debug
#    print(pd_rgb_sorted) # For Debug
#    print(pd_rgb_stack['rgb'].head()) # For Debug
#    print(pd_rgb_stack['r']) # For Debug

# Initialize Values for While Loop
    rgb_temp_std = 0
    rgb_temp_sum = 0
    i = -1

    #and (rgb_temp_sum < 50)
# Implement While Loop to ensure selected color is not black/white/greyscale (in which all rgb values are approximately the same)
    while (rgb_temp_std < 15):
        i += 1
        temp = pd_rgb_sorted.index[i]
        parse_1 = temp.find('_')
        parse_2 = temp.find('_', parse_1+1)
        rgb_temp = pd.DataFrame({'r':[temp[0:parse_1]], 'g':[temp[parse_1+1: parse_2]], 'b':[temp[parse_2+1:]]}).astype(int)
        rgb_temp_std = np.std(rgb_temp, 1)[0]
        rgb_temp_sum = rgb_temp['r'] + rgb_temp['g'] + rgb_temp['b']
        rgb_temp_sum = rgb_temp_sum.astype(int)

    rgb_select_1 = rgb_temp
    print('The first selected color is:')
    print(rgb_select_1)

# Write selected rgb values to respective variables for use in distance calculation
    pd_rgb_stack['r_select'] = rgb_select_1['r'][0]
    pd_rgb_stack['g_select'] = rgb_select_1['g'][0]
    pd_rgb_stack['b_select'] = rgb_select_1['b'][0]

# Perform distance calculation (<-- distance formula applied to RGB values)
    pd_rgb_stack['dist_score'] = np.sqrt(np.square(pd_rgb_stack['r'] - pd_rgb_stack['r_select']) + np.square(pd_rgb_stack['g'] - pd_rgb_stack['g_select']) + np.square(pd_rgb_stack['b'] - pd_rgb_stack['b_select']))
#    print(pd_rgb_stack['dist_score'].head(20))
# Inspect Counts
    dist_score_sorted = pd_rgb_stack['dist_score'].value_counts().to_frame()
# Calculate Standard Deviation of Distance Score
    dist_score_std = np.std(pd_rgb_stack['dist_score'])
#    print(dist_score_std)

# Recreate Sorted List on DF
##    pd_rgb_sorted = pd_rgb_stack['rgb'].value_counts().to_frame()
##    pd_rgb_sorted.astype(int)

# Perform left join on pd_rgb_stack to get distance scores in same dataframe
    pd_rgb_merged = pd_rgb_stack.join(pd_rgb_sorted, on = 'rgb', how = 'left', rsuffix = '_count')

# Sort Merged DF and remove duplicates
    pd_rgb_merged = pd_rgb_merged.sort_values(by = ['rgb_count', 'dist_score'], ascending = False)
    pd_rgb_merged['std'] = np.std(pd_rgb_merged[['r','g','b']], axis = 1)
    pd_rgb_merged = pd_rgb_merged.drop_duplicates()
    
# Reset Initial Values for Second While Loop
    rgb_temp_std = 0
    rgb_temp_sum = 0
    temp_dist_score = 0
    j = -1

# Second While Loop
    while (rgb_temp_std < 15 or temp_dist_score < 2*dist_score_std or temp_sum < 120):
        j += 1
        temp = pd_rgb_merged.iloc[j]['rgb']
        temp_r = pd_rgb_merged.iloc[j]['r']
        temp_g = pd_rgb_merged.iloc[j]['g']
        temp_b = pd_rgb_merged.iloc[j]['b']
        temp_dist_score = pd_rgb_merged.iloc[j]['dist_score']
        temp_sum = pd_rgb_merged.iloc[j]['check_sum']
        rgb_temp_std = pd_rgb_merged.iloc[j]['std']

    rgb_select_2 = pd.DataFrame({'r':[temp_r], 'g':[temp_g], 'b':[temp_b]}).astype(int)
    print('The second selected color is:')
    print(rgb_select_2)

# Generate Histograms and Plot
            
    histogram_test = album_art_test.histogram()
    #print(histogram_test)
    r_hist = histogram[1:256]
    r_hist_max = r_hist.index(max(r_hist))
    g_hist = histogram[257:512]
    g_hist_max = g_hist.index(max(g_hist))
    b_hist = histogram[513:768]
    b_hist_max = b_hist.index(max(b_hist))
    rgb_max = [r_hist_max, g_hist_max, b_hist_max]
#    print(rgb_max)

    # Generate Histogram Plot with RGB channels
#    fig, histo = pypl.subplots()
#    histo.plot(r_hist, 'r')
#    histo.plot(g_hist, 'g')
#    histo.plot(b_hist, 'b')
#    histo.plot(histogram_test, 'black')
#    pypl.show() Uncomment to show histogram plot

    # Assuming sRGB encoded colour values.
    RGB = np.array([r_hist_max, g_hist_max, b_hist_max])

    # RGB Values
    rgb_for_conversion = np.vstack((rgb_select_1.values, rgb_select_2.values))
#    rgb_select_1 = rgb_select_1.values
#    rgb_select_2 = rgb_select_2.values

#    rgb_for_conversion = [rgb_select_1, rgb_select_2]


#    print(rgb_for_conversion)
    
    # Conversion to tristimulus values.
    XYZ = colour.sRGB_to_XYZ(rgb_for_conversion / 256)
    print(XYZ)

    # Conversion to chromaticity coordinates.
    xy = colour.XYZ_to_xy(XYZ)
    print(xy)
    return(xy)