Ejemplo n.º 1
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.º 2
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.º 3
0
print('\n')

xy = colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65']
message_box(('Converting to "CCT" from given "xy" chromaticity coordinates '
             'using "McCamy (1992)" method:\n'
             '\n\t{0}'.format(xy)))
print(colour.xy_to_CCT_McCamy1992(xy))
print(colour.xy_to_CCT(xy, method='McCamy 1992'))

print('\n')

message_box(('Converting to "CCT" from given "xy" chromaticity coordinates '
             'using "Hernandez-Andres, Lee and Romero (1999)" method:\n'
             '\n\t{0}'.format(xy)))
print(colour.xy_to_CCT_Hernandez1999(xy))
print(colour.xy_to_CCT(xy, method='Hernandez 1999'))

print('\n')

CCT = 6503.49254150
message_box(('Converting to "xy" chromaticity coordinates from given "CCT" '
             'using "Kang, Moon, Hong, Lee, Cho and Kim (2002)" method:\n'
             '\n\t{0}'.format(CCT)))
print(colour.CCT_to_xy_Kang2002(CCT))
print(colour.CCT_to_xy(CCT, method="Kang 2002"))

print('\n')

message_box(('Converting to "xy" chromaticity coordinates from given "CCT" '
             'using "CIE Illuminant D Series" method:\n'
Ejemplo n.º 4
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.º 5
0
print('\n')

xy = colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65']
message_box(('Converting to "CCT" from given "xy" chromaticity coordinates '
             'using McCamy (1992) method:\n'
             '\n\t{0}'.format(xy)))
print(colour.xy_to_CCT_McCamy1992(xy))
print(colour.xy_to_CCT(xy, method='McCamy 1992'))

print('\n')

message_box(('Converting to "CCT" from given "xy" chromaticity coordinates '
             'using Hernandez-Andres, Lee and Romero (1999) method:\n'
             '\n\t{0}'.format(xy)))
print(colour.xy_to_CCT_Hernandez1999(xy))
print(colour.xy_to_CCT(xy, method='Hernandez 1999'))

print('\n')

CCT = 6503.4925414981535
message_box(('Converting to "xy" chromaticity coordinates from given "CCT" '
             'using Kang et al. (2002) method:\n'
             '\n\t{0}'.format(CCT)))
print(colour.CCT_to_xy_Kang2002(CCT))
print(colour.CCT_to_xy(CCT, method="Kang 2002"))

print('\n')

message_box(('Converting to "xy" chromaticity coordinates from given "CCT" '
             'using "CIE Illuminant D Series" method:\n'
Ejemplo n.º 6
0
from Quartz.CoreGraphics import CGGetDisplayTransferByTable, CGMainDisplayID
from colour import xy_to_CCT_Hernandez1999, XYZ_to_xy, sRGB_to_XYZ
from time import sleep

lasttemp = None

while True:
    (_, red, green, blue,
     _) = CGGetDisplayTransferByTable(CGMainDisplayID(), 3, None, None, None,
                                      None)

    rgb = [red[2], green[2], blue[2]]
    # print("rgb", rgb)

    temp = xy_to_CCT_Hernandez1999(XYZ_to_xy(sRGB_to_XYZ(rgb)))
    if temp != lasttemp:
        print temp
        sleeptime = 0.1
    else:
        sleeptime = 1
    lasttemp = temp

    sleep(sleeptime)