Esempio n. 1
0
def findMaxDeltaEColor(labColor, iter=500):
    """
    :param labColor: lab color in standard range [(0 ~ 100), (-128 ~ 127), (-128 ~ 127)]
    :param iter: random number of iteration, the result will be more precise with larger number
    :return: the approximate color with maximum deltaE regard to labColor
    """
    maxDelta_E = 0
    maxL = None
    maxa = None
    maxb = None
    for i in range(iter):
        L = np.random.randint(0, 100)
        a = np.random.randint(-128, 127)
        b = np.random.randint(-128, 127)
        delta_E = colour.delta_E(labColor, [L, a, b], method=deltaE_method)
        if delta_E > maxDelta_E:
            maxDelta_E = delta_E
            maxL = L
            maxa = a
            maxb = b
    assert maxL is not None
    assert maxa is not None
    assert maxb is not None
    maxStandardLabColor = np.array([L, a, b])
    print("color with maximum delta E found : {}".format(maxDelta_E))
    print(maxStandardLabColor)
    maxOpencvLabColor = standardLAB2opencvLAB(maxStandardLabColor)[np.newaxis, np.newaxis, :] \
        .astype(np.uint8)
    maxRGBColor = cv.cvtColor(maxOpencvLabColor, cv.COLOR_LAB2RGB).reshape(
        (1, 1, 3))
    plt.imshow(maxRGBColor / 255.0)
    plt.show()
Esempio n. 2
0
File: adds.py Progetto: jhasanov/ACV
def delta_E_range():
    XYZ = colour.volume.XYZ_outer_surface()
    # print(XYZ, XYZ.shape)
    combinations = colour.XYZ_to_Lab(
        np.array(list(itertools.combinations(XYZ, 2))))
    # print(combinations)
    delta_E = colour.delta_E(combinations[:, 0, :], combinations[:, 1, :])
    return np.amax(delta_E), np.amin(delta_E)
Esempio n. 3
0
def visualize_color_bin(rgb):
    lab = cv2.cvtColor(rgb.astype(np.float32) / 255, cv2.COLOR_RGB2Lab)
    lab_delta = np.asarray([colour.delta_E(lc, lab) for lc in lab_colors])
    lab_delta = np.argmin(lab_delta, axis=0)
    for i in range(lab.shape[0]):
        for j in range(lab.shape[1]):
            rgb[i, j, :] = rgb_colors[lab_delta[i, j]]
    return rgb
Esempio n. 4
0
 def evaluate_fitness(self, individuals):
     for individual in individuals:
         fitness_value = 1 / (1 + np.sum(
             delta_E(
                 self.target_image_np_lab,
                 self.preprocess_pil_image(individual.phenotype),
             )))
         individual.set_fitness(fitness_value)
Esempio n. 5
0
 def is_close(self, x1, y1):
     color_vec = np.array(self.lab_image[self.x0, self.y0, :])
     color_mat = np.array([(self.lab_image[x1, y1, 0], self.lab_image[x1, y1, 1], self.lab_image[x1, y1, 2])])
     # dist = np.asscalar(delta_e_cie2000(color_vec, color_mat)[0])
     dist = np.asscalar(colour.delta_E(color_vec, color_mat)[0])
     # print(dist)
     if dist < self.thresh:
         return True
     return False
Esempio n. 6
0
 def evaluate_fitness(self, individuals):
     for individual in individuals:
         preprocessed_genotype = self.preprocess_pil_image(individual.genotype)
         fitness_value = 1 / (
             1 + np.mean(delta_E(self.target_image_np_lab, preprocessed_genotype))
         ) + 0.5 * compare_ssim(
             self.target_image_np_lab, preprocessed_genotype, multichannel=True
         )
         individual.set_fitness(fitness_value)
Esempio n. 7
0
def getTransLoss(colors):
    l = len(colors)
    tcolors = [opencvLAB2standardLAB(color) for color in colors]
    temp = [
        colour.delta_E(tcolors, np.tile(color, (l, 1)), method=deltaE_method)
        for color in tcolors
    ]
    Temp = [t.argsort()[:30] for t in temp]
    res = np.stack(temp)
    res2 = np.stack(Temp)
    return res, res2
Esempio n. 8
0
def findMaxDeltaEColorInArray(color_array_a, color_b):
    """
    find the color in color_array_a with max deltaE w.r.t. color_b
    :param color: shape (1) in standard LAB space
    :param color_array: shape (N, 3) in standard LAB space
    :return:
    """
    delta_E = colour.delta_E(color_array_a, color_b, method=deltaE_method)
    index = np.argmax(delta_E)
    max_color = color_array_a[index]
    return index, max_color
def calc_delta_e(src_rgb, dst_rgb, method='cie2000'):
    """
    RGB値からdelta_eを計算。
    rgb値はガンマ補正がかかった8bit整数型の値とする。
    """
    src_linear = (src_rgb / 0xFF)**2.4
    dst_linear = (dst_rgb / 0xFF)**2.4
    src_lab = linear_rgb_to_cielab(src_linear, BT709)
    dst_lab = linear_rgb_to_cielab(dst_linear, BT709)
    delta = delta_E(src_lab, dst_lab, method)

    return delta
Esempio n. 10
0
def d_textRegion2textColor(bboxs, textColor):
    """
    :param bboxs: text region of all characters, LAB color space
    :param textColor: color we try to put on text, LAB color space
    :return: minimum textRegion2textColor distance:
             min(d(bbox, textColor)), where d is a distance function
    """
    l = len(bboxs)
    bboxs = [opencvLAB2standardLAB(box) for box in bboxs]
    p = opencvLAB2standardLAB(textColor)
    d = colour.delta_E(bboxs, np.tile(p, (l, 1)), method=deltaE_method)
    t = np.argsort(d)[0]
    return d[t], t
Esempio n. 11
0
def colorPicker(event, x, y, flags, param):
    global clickedColorLAB
    if event == cv2.EVENT_LBUTTONDOWN:
        colorsBGR = first[y:y + 1, x:x + 1]
        labim = cv2.cvtColor(colorsBGR, cv2.COLOR_BGR2LAB)
        clickedColorLAB = labim[0, 0]
        print("New base {} Lab".format(clickedColorLAB))
    if event == cv2.EVENT_RBUTTONDOWN:
        colorsBGR2 = first[y:y + 1, x:x + 1]
        labim2 = cv2.cvtColor(colorsBGR2, cv2.COLOR_BGR2LAB)
        toval = labim2[0, 0]
        print("To compare {} Lab".format(toval))
        dlt = delta_E(clickedColorLAB, toval)
        print("Delta E = {}".format(dlt))
    def getMaskOfAColor(median_color, image, visited_map):
        """
        :param median_color: lab color
        :return:
        A mask; 0 areas refer to areas not this color; 1 areas refer to areas with this color
        """

        compared_color_template = getColoredTemplateForCompared(
            height, width, median_color)
        distance = colour.delta_E(image, compared_color_template)

        mask = np.where(
            visited_map == 1, 0,
            np.where(distance < PERCEPTUAL_DIS_FOR_DISTINCT_BG, 1, 0))

        return mask
Esempio n. 13
0
def deltaE00(img1, img2):
    """
    Calculate deltaE 2000 over two images and returns average deltaE 2000
    :param img1: numpy
    :param img2: numpy
    :return: float
    """
    from skimage import color
    import colour

    img1 = color.rgb2lab(img1)
    img2 = color.rgb2lab(img2)
    img1 = np.reshape(img1, [-1, 3]).astype(np.float32)
    img2 = np.reshape(img2, [-1, 3]).astype(np.float32)

    delta_e = colour.delta_E(img1, img2, method='CIE 2000')

    return np.mean(delta_e)
 def getCurrentColorForMask(ind, image):
     """
     :param ind: the index of the seed color
     :return: avg color around the seed color
     """
     mid_color = image[ind[0], ind[1]]
     kernel_size = 5
     margin = int(kernel_size / 2)
     u_i, b_i = max(ind[0] - margin, 0), min(ind[0] + margin + 1, height)
     l_j, r_j = max(ind[1] - margin, 0), min(ind[1] + margin + 1, width)
     neighbours = image[u_i:b_i, l_j:r_j]
     B = getColoredTemplateForCompared(neighbours.shape[0],
                                       neighbours.shape[1], mid_color)
     dists = colour.delta_E(neighbours, B)
     colors = neighbours[dists < PERCEPTUAL_DIS_FOR_DISTINCT_BG]
     if len(colors) < int(kernel_size * kernel_size / 2):
         return False, []
     return True, np.average(colors, axis=0).astype('uint8')
Esempio n. 15
0
def deltaE(trueVals, estVals, MINLAT, MAXLAT, cmap=cm.viridis_r):
    norm = Normalize(vmin=MINLAT, vmax=MAXLAT)
    m = cm.ScalarMappable(norm=norm, cmap=cmap)

    trueVals = list(np.array(trueVals).flatten())
    estVals = list(np.array(estVals).flatten())

    trueColors = m.to_rgba(trueVals)[:, :3]  # multiply by 255 for RGB

    trueColors = np.array([trueColors])  # cvtColor req 2-dim array

    trueColors = cv2.cvtColor(trueColors.astype("float32"), cv2.COLOR_RGB2LAB)
    estColors = m.to_rgba(estVals)[:, :3]
    estColors = np.array([estColors])
    estColors = cv2.cvtColor(estColors.astype("float32"), cv2.COLOR_RGB2LAB)

    dE = np.mean(colour.delta_E(trueColors, estColors, method='CIE 2000'))

    return dE
Esempio n. 16
0
def color_bin(rgb):

    rgb_img = visualize_color_bin(rgb)
    edges = cv2.Laplacian(cv2.cvtColor(rgb_img, cv2.COLOR_RGB2GRAY),
                          cv2.CV_64F)
    hsv_obs = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2HSV)
    edges = np.where(edges != 0, 1, 0)
    edges = np.uint8(edges)
    edges = np.expand_dims(edges, axis=-1)
    hsv_obs[:, :, 1:3] = hsv_obs[:, :, 1:3] * edges
    rgb = cv2.cvtColor(hsv_obs, cv2.COLOR_HSV2RGB)
    rgb = np.uint8(rgb)

    lab = cv2.cvtColor(rgb.astype(np.float32) / 255, cv2.COLOR_RGB2Lab)
    lab_delta = np.asarray([colour.delta_E(lc, lab) for lc in lab_colors])
    lab_delta = np.argmin(lab_delta, axis=0)
    one_hot_rgb = np.eye(N_RGBS)[lab_delta]

    return one_hot_rgb
Esempio n. 17
0
def visualize_edged_color_bin(rgb):
    rgb_img = visualize_color_bin(rgb)
    edges = cv2.Laplacian(cv2.cvtColor(rgb_img, cv2.COLOR_RGB2GRAY),
                          cv2.CV_64F)
    hsv_obs = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2HSV)
    edges = np.where(edges != 0, 1, 0)
    edges = np.uint8(edges)
    edges = np.expand_dims(edges, axis=-1)
    hsv_obs[:, :, 1:3] = hsv_obs[:, :, 1:3] * edges
    rgb = cv2.cvtColor(hsv_obs, cv2.COLOR_HSV2RGB)
    rgb = np.uint8(rgb)

    lab = cv2.cvtColor(rgb.astype(np.float32) / 255, cv2.COLOR_RGB2Lab)
    lab_delta = np.asarray([colour.delta_E(lc, lab) for lc in lab_colors])
    lab_delta = np.argmin(lab_delta, axis=0)

    for i in range(lab.shape[0]):
        for j in range(lab.shape[1]):
            rgb[i, j, :] = rgb_colors[lab_delta[i, j]]

    return rgb
Esempio n. 18
0
    def scan (self, x, y):
        if self.img is None:
            raise ValueError ("No image was loaded!")

        base_color = self.img[y, x]
        pixels = list()
        pixels.append((x, y))

        imgcopy = self.img.copy()

        start = time.time()
        while len(pixels) > 0:
            cur = pixels.pop(-1)

            if not self.pixelInBound (*cur):
                continue

            if self.pixelVisited(*cur):
                continue

            self.setPixelVisited(*cur)

            x, y = cur
            # if delta larger than tolerance add to outline and continue
            color_diff = colour.delta_E(base_color, self.img[y, x], method="CIE 1994")
            if color_diff > self.color_diff_tolerance:
                self._outline.append (cur)
                imgcopy[y, x] = [68, 72, 30]
                imgcopy[y if y + 1 >= self.imgheight else y + 1, x] = [68, 72, 30]
                imgcopy[y if y - 1 < 0 else y - 1, x] = [68, 72, 30]
                imgcopy[y, x if x + 1 >= self.imgwidth else x + 1] = [68, 72, 30]
                imgcopy[y, x if x - 1 < 0 else x - 1] = [68, 72, 30]
                continue

            # expand pixel search and add pixel color
            self._distinctColors[tuple(self.img[y, x])] = color_diff
            pixels.extend (((x, y + 1), (x, y - 1), (x + 1, y), (x - 1, y)))

        self.last_scantime = time.time() - start
        self.img = imgcopy
def match_image_by_colour(images, training_images):
    """ Loops through each test category comparing each square extracted from
    the dipstick with all possible test outcomes, in order to find the two closest
    matching colours for each test. To make the colour comparison RGB colours are
    converted to LAB colours and the LAB DELTA E 2000 formula is computed. A list
    is returned containing the indices corresponding to which colours for each test
    had the closet match.
    """
    minimum_indices = []
    minimum = 0
    for index, test_category in enumerate(training_images):
        minimum_delta_e = 101
        for minimum_index, test in enumerate(test_category):
            square_colour = rgb2lab(np.uint8([[images[index]]]))
            test_colour = rgb2lab(np.uint8([[test]]))

            delta_e = colour.delta_E(square_colour, test_colour)
            if delta_e < minimum_delta_e:
                minimum_delta_e = delta_e
                minimum = minimum_index

        minimum_indices.append(minimum)

    return minimum_indices
Esempio n. 20
0
        useblit=True,
        button=[1, 3],  # don't use middle button
        minspanx=5,
        minspany=5,
        spancoords='pixels',
        interactive=True)
    plt.connect('key_press_event', toggle_selector)
    input("Choose ROI")
    roi = toggle_selector.RS.extents  #xmin,xmax,ymin,ymax
    roi = [int(r) for r in roi]

    color = np.array(
        [i[roi[2]:roi[3], roi[0]:roi[1]].mean((0, 1)) / 255 for i in images])
    ##now, convert this into the XYZ domain
    cXYZ = [colour.sRGB_to_XYZ(col) for col in color]
    delE = np.array([[colour.delta_E(c1 * 100, c2) for c2 in XYZ]
                     for c1 in cXYZ])
    bif = np.array([retL[i.argmin()] / 5 for i in delE])

    #Now, extract the voltage from the data files

    #first, pull the appropriate columsn

    nameRegex = re.compile('[wW](\d{3}).*')
    compound = nameRegex.search(name)[1]

    cmpGex = re.compile('^W' + compound + '.*')

    col1 = [i for i, el in enumerate(voltData.columns) if cmpGex.search(el)][0]
    col2 = col1 + 1
    bif = pd.Series(bif, dtype='float')
Esempio n. 21
0
        output_bps=16,
        output_color=rp.ColorSpace.XYZ,
        gamma=(1, 1)).astype(float) / (2.0**16 - 1)
    # rgb = raw.postprocess(user_wb = user_wb)
    # plt.imshow(rgb)
    # plt.show()
    fig, axs = plt.subplots()
    dEs = np.zeros((4, 6), dtype=np.float)
    for i in range(0, 24):
        sample = im_xyz[box[i][1]:box[i][3], box[i][0]:box[i][2]]
        mean_xyz = [np.mean(sample[:, :, x]) for x in range(0, 3)]
        dE = colour.delta_E(
            colour.XYZ_to_Lab(
                mean_xyz,
                illuminant=colour.
                ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65']),
            colour.XYZ_to_Lab(
                cc[i],
                illuminant=colour.
                ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65']))
        #print(dE)
        dEs[int(i / 6)][i % 6] = dE

        # vis = np.tile(mean_xyz, [120, 120, 1])
        # vis2 = np.tile(cc[i], [120, 120, 1])
        # fig, (ax1, ax2, ax3) = plt.subplots(1, 3)
        # ax1.imshow(sample)
        # ax2.imshow(vis)
        # ax3.imshow(vis2)
        # plt.show()
    axs.imshow(dEs)
Esempio n. 22
0
def Distance(xyz, lab):
    lab1 = colour.XYZ_to_Lab(
        xyz, colour.ILLUMINANTS['CIE 1931 2 Degree Standard Observer']['D65'])
    return colour.delta_E(lab, lab1)
Esempio n. 23
0
import numpy as np

import colour
from colour.utilities import message_box

message_box('"Delta E" Computations')

Lab_1 = np.array([100.00000000, 21.57210357, 272.22819350])
Lab_2 = np.array([100.00000000, 426.67945353, 72.39590835])
message_box(
    f'Computing "Delta E" with "CIE 1976" method from given "CIE L*a*b*" '
    f"colourspace matrices:\n\n"
    f"\t{Lab_1}\n"
    f"\t{Lab_2}")
print(colour.delta_E(Lab_1, Lab_2, method="CIE 1976"))
print(colour.difference.delta_E_CIE1976(Lab_1, Lab_2))

print("\n")

message_box(
    f'Computing "Delta E" with "CIE 1994" method from given "CIE L*a*b*" '
    f"colourspace matrices:\n\n"
    f"\t{Lab_1}\n"
    f"\t{Lab_2}")
print(colour.delta_E(Lab_1, Lab_2, method="CIE 1994"))
print(colour.difference.delta_E_CIE1994(Lab_1, Lab_2))

print("\n")

message_box(
Esempio n. 24
0
"""
Showcases *Delta E* colour difference computations.
"""

import colour
from colour.utilities.verbose import message_box

message_box('"Delta E" Computations')

Lab1 = [100, 21.57210357, 272.2281935]
Lab2 = [100, 426.67945353, 72.39590835]
message_box(('Computing "Delta E" with CIE 1976 method from given *CIE Lab* '
             'colourspace matrices:\n'
             '\n\t{0}\n\t{1}'.format(Lab1, Lab2)))
print(colour.delta_E_CIE1976(Lab1, Lab2))
print(colour.delta_E(Lab1, Lab2, method='CIE 1976'))

print('\n')

message_box(('Computing "Delta E" with CIE 1994 method from given *CIE Lab* '
             'colourspace matrices:\n'
             '\n\t{0}\n\t{1}'.format(Lab1, Lab2)))
print(colour.delta_E_CIE1994(Lab1, Lab2))
print(colour.delta_E(Lab1, Lab2, method='CIE 1994'))

print('\n')

message_box(('Computing "Delta E" with CIE 1994 method from given *CIE Lab* '
             'colourspace matrices for "graphics arts" applications:\n'
             '\n\t{0}\n\t{1}'.format(Lab1, Lab2)))
print(colour.delta_E_CIE1994(Lab1, Lab2, textiles=False))
import cv2
import numpy as np
import colour
import os

out = open("./deltaE_output/output.txt", 'w+')

for i in range(int(len([name for name in os.listdir('./deltaE_input')])/5)):

    image1_rgb = cv2.imread("./deltaE_input/" + str(i + 1)+".jpg")
    image2_rgb = cv2.imread("./deltaE_input/cnn" + str(i + 1)+"-1.png")
    image3_rgb = cv2.imread("./deltaE_input/cnn" + str(i + 1)+"-2.png")

    image1_lab = cv2.cvtColor(image1_rgb.astype(np.float32) / 255, cv2.COLOR_RGB2Lab)
    image2_lab = cv2.cvtColor(image2_rgb.astype(np.float32) / 255, cv2.COLOR_RGB2Lab)
    image3_lab = cv2.cvtColor(image3_rgb.astype(np.float32) / 255, cv2.COLOR_RGB2Lab)

    delta_E_1 = colour.delta_E(image1_lab, image2_lab)
    delta_E_2 = colour.delta_E(image1_lab, image3_lab)

    cnn1 = str(i + 1) + " - " + str(np.mean(delta_E_1))
    cnn2 = str(np.mean(delta_E_2))
    out.write(cnn1 + " " + cnn2 + "\n")




Esempio n. 26
0
def computeContours(frame):
    colorsLAB = {
        "Red": ([
            cv2.getTrackbarPos('Red L', 'Color Values'),
            cv2.getTrackbarPos('Red A', 'Color Values'),
            cv2.getTrackbarPos('Red B', 'Color Values')
        ]),
        "Orange": ([
            cv2.getTrackbarPos('Orange L', 'Color Values'),
            cv2.getTrackbarPos('Orange A', 'Color Values'),
            cv2.getTrackbarPos('Orange B', 'Color Values')
        ]),
        "Yellow": ([
            cv2.getTrackbarPos('Yellow L', 'Color Values'),
            cv2.getTrackbarPos('Yellow A', 'Color Values'),
            cv2.getTrackbarPos('Yellow B', 'Color Values')
        ]),
        "Green": ([
            cv2.getTrackbarPos('Green L', 'Color Values'),
            cv2.getTrackbarPos('Green A', 'Color Values'),
            cv2.getTrackbarPos('Green B', 'Color Values')
        ]),
        "Blue": ([
            cv2.getTrackbarPos('Blue L', 'Color Values'),
            cv2.getTrackbarPos('Blue A', 'Color Values'),
            cv2.getTrackbarPos('Blue B', 'Color Values')
        ]),
        "White": ([
            cv2.getTrackbarPos('White L', 'Color Values'),
            cv2.getTrackbarPos('White A', 'Color Values'),
            cv2.getTrackbarPos('White B', 'Color Values')
        ])
    }

    frame2 = frame.copy()

    gausBlur = keepOdd('Blur kSize', 'Settings')

    gaus = cv2.getTrackbarPos('Block Size', 'Settings')
    if gaus < 3:
        gaus = 3
    else:
        count = gaus % 2
        if (count == 0):
            gaus += 1

    # blur = cv2.bilateralFilter(cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY), gausBlur, cv2.getTrackbarPos('Blur Sigma X', 'Settings'), cv2.getTrackbarPos('Blur Sigma X', 'Settings'))
    # blur = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)

    # blur = cv2.GaussianBlur(frame2, (gausBlur, gausBlur), cv2.getTrackbarPos('Blur Sigma X', 'Settings'))
    # blur = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)

    frame2 = cv2.adaptiveThreshold(cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY),
                                   cv2.getTrackbarPos('Max Value', 'Settings'),
                                   cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                   cv2.THRESH_BINARY_INV, gaus,
                                   cv2.getTrackbarPos('C', 'Settings'))

    # frame2 = cv2.adaptiveThreshold(blur,
    #     cv2.getTrackbarPos('Max Value', 'Settings'),
    #     cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
    #     cv2.THRESH_BINARY_INV,
    #     gaus,
    #     cv2.getTrackbarPos('C', 'Settings'))

    se1Size = keepOdd('Closing', 'Settings')
    # se2Size = keepOdd('Opening', 'Settings')
    se1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (se1Size, se1Size))
    # se2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (se2Size,se2Size))
    frame2 = cv2.morphologyEx(frame2, cv2.MORPH_CLOSE, se1)
    # frame2 = cv2.morphologyEx(frame2, cv2.MORPH_OPEN, se2)

    (contours, hierarchy) = cv2.findContours(frame2.copy(), cv2.RETR_TREE,
                                             cv2.CHAIN_APPROX_SIMPLE)

    # Index is used to remove nested squares.
    index = 0
    for cnt in contours:
        if (hierarchy[0, index, 3] != -1):
            epsilon = (cv2.getTrackbarPos('Epsilon Percent', 'Settings') /
                       100) * cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, epsilon, True)

            area = cv2.contourArea(approx, False)
            # arch = cv2.arcLength(approx, True)

            # squareness = 4 * math.pi * area / (arch * arch)

            if (len(approx) == 4
                    and area > cv2.getTrackbarPos('Blob Area', 'Settings')):
                # Square detected. Draw square on original image in green.
                M = cv2.moments(cnt)
                if (M["m00"] != 0):
                    cX = int(M["m10"] / M["m00"])
                    cY = int(M["m01"] / M["m00"])

                    # cv2.drawContours(frame, [approx], 0, (cv2.getTrackbarPos('Contour B', 'Settings'), cv2.getTrackbarPos('Contour G', 'Settings'), cv2.getTrackbarPos('Contour R', 'Settings')), 3)

                    mask = np.zeros(frame2.shape, np.uint8)
                    cv2.drawContours(mask, [cnt], 0, 255, -1)
                    # pixelpoints = np.transpose(np.nonzero(mask))

                    # hsvFrame = cv2.cvtColor(frame.copy(), cv2.COLOR_BGR2HSV)
                    # labFrame = cv2.cvtColor(frame.astype(np.float32) / 255, cv2.COLOR_BGR2Lab)
                    labFrame = cv2.cvtColor(frame, cv2.COLOR_BGR2Lab)
                    meanVal = cv2.mean(labFrame, mask=mask)
                    # color = np.array((int(meanVal[0]), 255, 255), np.uint8)
                    color = np.array((128, int(meanVal[1]), int(meanVal[2])),
                                     np.uint8)

                    resultColor = {}
                    for (k, v) in colorsLAB.items():
                        resultColor[k] = colorSci.delta_E(v, color)

                    #THIS WILL WORK FOR EVEN GREY
                    # print(resultColor)
                    finalColor = min(resultColor, key=resultColor.get)
                    # print(finalColor)

                    # print(color)

                    cv2.circle(frame, (cX, cY), 9, (0, 0, 0), -1)
                    cv2.circle(
                        frame, (cX, cY), 5,
                        (colorsRGB[finalColor][2], colorsRGB[finalColor][1],
                         colorsRGB[finalColor][0]), -1)
            else:
                # Square NOT detected. Draw square on original image in red.
                cv2.drawContours(frame, [approx], 0, (255, 0, 0), 3)

        index += 1

    return frame2
Esempio n. 27
0
    readCSVs = csv.DictReader(csvfile, delimiter=',')
    lab2_list = []
    l2 = []
    a2 = []
    b2 = []
    for row in readCSVs:
        l2 = row['LAB_L']
        a2 = row['LAB_A']
        b2 = row['LAB_B']
        if l2 or a2 or b2.isdigit():
            l2_n = float(l2)
            a2_n = float(a2)
            b2_n = float(b2)
            lab2_data = np.array([l2_n, a2_n, b2_n])
            lab2_list.append(lab2_data)

# Calculate delta_E
CIE_1976 = colour.delta_E(lab_list, lab2_list, method='CIE 1976')
CIE_1994 = colour.delta_E(lab_list, lab2_list, method='CIE 1994')
CIE_2000 = colour.delta_E(lab_list, lab2_list, method='CIE 2000')

# Create & write CSV file
serial_num = range(1, row_count)
np.savetxt(save_path + '/' + 'delta_E.csv',
           np.column_stack((serial_num, CIE_1976, CIE_1994, CIE_2000)),
           delimiter=',',
           fmt='%s',
           header='Sample_ID, CIE_1976, CIE1994, CIE2000')

root.destroy()
Esempio n. 28
0
import colour
from colour.utilities.verbose import message_box

message_box('"Delta E" Computations')

Lab1 = (100.00000000, 21.57210357, 272.22819350)
Lab2 = (100.00000000, 426.67945353, 72.39590835)
message_box(
    (
        'Computing "Delta E" with CIE 1976 method from given *CIE Lab* '
        "colourspace matrices:\n"
        "\n\t{0}\n\t{1}".format(Lab1, Lab2)
    )
)
print(colour.delta_E_CIE1976(Lab1, Lab2))
print(colour.delta_E(Lab1, Lab2, method="CIE 1976"))

print("\n")

message_box(
    (
        'Computing "Delta E" with CIE 1994 method from given *CIE Lab* '
        "colourspace matrices:\n"
        "\n\t{0}\n\t{1}".format(Lab1, Lab2)
    )
)
print(colour.delta_E_CIE1994(Lab1, Lab2))
print(colour.delta_E(Lab1, Lab2, method="CIE 1994"))

print("\n")
Esempio n. 29
0
import colour
import numpy as np
a = np.array([18, -13, 20])
b = np.array([18, -13, 122])
delta_E = colour.delta_E(a, b, method="CIE 2000")
print(delta_E)
Esempio n. 30
0
def test_color(path_im, color_name, ppg_data, wb_roi, patch_roi, path_jpeg = None):
    #Full DNG detail
    # with exiftool.ExifTool() as et:
    #     metadata = et.get_metadata(path_im)
    #     for key in metadata.keys():
    #         print(key, ' ', metadata[key])

    with rp.imread(path_im) as raw:
        h, w = np.shape(raw.raw_image)
        print(h, ' ', w)


        #print(raw.raw_colors)
        m_raw_rgb = np.array([0.0, 0.0, 0.0, 0.0])
        m_raw_cnt = np.array([0, 0, 0, 0])
        for i in range(wb_roi[1], wb_roi[3]):
            for j in range(wb_roi[0], wb_roi[2]):
                m_raw_rgb[raw.raw_color(i, j)] += raw.raw_value(i, j)
                m_raw_cnt[raw.raw_color(i, j)] += 1
        m_raw_rgb /= m_raw_cnt
        # print(m_raw_rgb)
        wp = np.array([m_raw_rgb[0], m_raw_rgb[1], m_raw_rgb[2]])
        wp /= wp[1]
        print('white point: ' + str(wp))
        user_whitebalance = (1.0 / wp).tolist() + [0]
        print('user white balance: ' + str(user_whitebalance))
        print('camera white balance: ' + str(raw.camera_whitebalance))

        print('Custom processing:')
        custom_xyz = raw.postprocess(user_wb=user_whitebalance,
                                     output_bps=16,
                                     output_color=rp.ColorSpace.XYZ,
                                     gamma = (1, 1)).astype(float) / (2.0**16 - 1)

        sample = custom_xyz[patch_roi[1]:patch_roi[3], patch_roi[0]:patch_roi[2]]
        c_xyz = [np.mean(sample[:, :, x]) for x in range(0, 3)]
        c_rgb = cam2xyz.XYZ2sRGB(c_xyz)

        print('Default processing:')
        default_xyz = raw.postprocess(use_camera_wb=True,
                                     output_bps=16,
                                     output_color=rp.ColorSpace.XYZ,
                                     gamma = (1, 1)).astype(float) / (2.0**16 - 1)
        sample = default_xyz[patch_roi[1]:patch_roi[3], patch_roi[0]:patch_roi[2]]
        d_xyz = [np.mean(sample[:, :, x]) for x in range(0, 3)]
        d_rgb = cam2xyz.XYZ2sRGB(d_xyz)
        j_rgb = [0, 0, 0]
        if path_jpeg:
            jpeg_rgb = cv2.cvtColor(cv2.imread(path_jpeg), cv2.COLOR_BGR2RGB)
            sample = jpeg_rgb[patch_roi[1]:patch_roi[3], patch_roi[0]:patch_roi[2]]
            j_rgb = [np.mean(sample[:, :, x]) for x in range(0, 3)]

        c_lab = cam2xyz.XYZ2LAB(c_xyz)
        d_lab = cam2xyz.XYZ2LAB(d_xyz)
        if path_jpeg:
            j_lab = cam2xyz.RGB2LAB(j_rgb)
        print('RGB after eliminate illuminant: ' + str(c_rgb))
        print('PPG RGB: ' + str(ppg_data[color_name]['RGB']))
        print('Lab after eliminate illuminant: ' + str(c_lab))
        print('PPG Lab: ' + str(ppg_data[color_name]['LAB']))

        # dE_c = deltaE(c_lab, np.array(ppg_data[color_name]['LAB']))
        # dE_d = deltaE(d_lab, np.array(ppg_data[color_name]['LAB']))
        dE_c = colour.delta_E(c_lab, np.array(ppg_data[color_name]['LAB']))
        dE_d = colour.delta_E(d_lab, np.array(ppg_data[color_name]['LAB']))
        # print('Custom wb dE: ', deltaE(c_lab, np.array(ppg_data[color_name]['LAB'])))
        # print('Default wb dE: ', deltaE(d_lab, np.array(ppg_data[color_name]['LAB'])))
        print('Custom wb dE: ', dE_c)
        print('Default wb dE: ', dE_d)


        dE_j = -1.0
        if path_jpeg:
            dE_j = colour.delta_E(j_lab, np.array(ppg_data[color_name]['LAB']))
            print('JPEG dE: ', dE_j)

        # vis_s = np.tile(c_rgb, [300, 300, 1])
        # vis_d = np.tile(d_rgb, [300, 300, 1])
        # vis_ppg = np.tile(ppg_data[color_name]['RGB'], [300, 300, 1])
        # if path_jpeg:
        #     vis_j = np.tile(j_rgb, [300, 300, 1])
        # if path_jpeg:
        #     fig, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4)
        #     ax1.imshow(vis_s)
        #     ax1.set_title('Custom wb')
        #     ax2.imshow(vis_ppg)
        #     ax2.set_title('Gt')
        #     ax3.imshow(vis_d)
        #     ax3.set_title('Default wb')
        #     ax4.imshow(vis_j)
        #     ax4.set_title('jpeg')
        #     plt.show()
        return dE_d, dE_c, dE_j, d_rgb, c_rgb, j_rgb, d_xyz, c_xyz
Esempio n. 31
0
def calculateLoss(boxes, palette, log_statistics, search_index, key_frame,
                  frame_mean_delta, config):
    transloss_beta = config["transloss_beta"]
    transloss_gamma = config["transloss_gamma"]
    transloss_theta = config["transloss_theta"]
    distance_gamma = config["distance_gamma"]
    distance_standard = config["distance_standard"]
    tolerance_index = config["tolerance_index"]
    boxes = getBoxMean(boxes)
    boxes_standardLAB = opencvLAB2standardLAB(boxes)  # shape: (box_num x 3)
    palette_standardLAB = palette.standardLAB[search_index]
    distance = colour.delta_E(
        boxes_standardLAB[None, :, :],
        palette_standardLAB[:, None, :],
        method=deltaE_method)  # shape: (palette_color_num x box_num)
    # relative_L = (palette_standardLAB[:, None, 0] + 5) / (boxes_standardLAB[None, :, 0]+5)
    # relative_L[relative_L < 1] = 1/relative_L[relative_L < 1]
    # distance *= relative_L
    # min_distance_each_color = distance.min(axis=1)   # shape: (palette_color_num)
    min_distance_each_color = np.partition(
        distance, kth=tolerance_index,
        axis=1)[:, tolerance_index]  # shape: (palette_color_num)

    # if key_frame:
    #     previous_color_loss_table = palette.DP_loss[palette.nearby_indexes[search_index[:]]]
    # else:
    #     previous_color_loss_table = palette.DP_loss[palette.nearby_indexes[search_index[:]]] \
    #                                 + transloss_beta * palette.nearby_deltaEs[search_index[:]] ** transloss_gamma
    #     # shape: (palette_color_num x nearby_color_num)
    #
    #     # if key_frame:
    #     #     DP_previous_index = np.argmin(palette.DP_loss).repeat(len(search_index))
    #     #     palette.DP_loss[:] = np.inf  # Can be optimized using the previous search_index
    #     #     palette.DP_loss[search_index] = 0
    #     #     previous_color_loss = 0
    #     # else:
    #     #     transloss = transloss_beta * np.exp(-transloss_theta * frame_mean_delta) \
    #     #                 * palette.nearby_deltaEs[search_index[:]] ** transloss_gamma
    #     #     previous_color_loss_table = palette.DP_loss[palette.nearby_indexes[search_index[:]]] + transloss
    #     #     tmp_argmin = np.argmin(previous_color_loss_table, axis=1)  # shape: (palette_color_num)
    #     #     DP_previous_index = palette.nearby_indexes[search_index, tmp_argmin] # shape: (palette_color_num)
    #     previous_color_loss = previous_color_loss_table[range(len(tmp_argmin)), tmp_argmin]

    # Calculate transfer Loss and previous DP index
    transloss = transloss_beta * np.exp(-transloss_theta * frame_mean_delta) \
                * palette.nearby_deltaEs[search_index[:]] ** transloss_gamma
    previous_color_loss_table = palette.DP_loss[palette.nearby_indexes[
        search_index[:]]] + transloss
    tmp_argmin = np.argmin(previous_color_loss_table,
                           axis=1)  # shape: (palette_color_num)
    DP_previous_index = palette.nearby_indexes[
        search_index, tmp_argmin]  # shape: (palette_color_num)
    previous_color_loss = previous_color_loss_table[range(len(tmp_argmin)),
                                                    tmp_argmin]

    # Calcualte distance loss
    distance_loss = min_distance_each_color - distance_standard
    distance_loss[distance_loss > 0] = 0
    distance_loss = np.abs(distance_loss)**distance_gamma

    DP_loss = previous_color_loss + distance_loss
    #
    # distance_loss = -min_distance_each_color
    # DP_loss = previous_color_loss_table[range(len(tmp_argmin)), tmp_argmin] + distance_loss

    log_statistics["max_min_distance"].append(min_distance_each_color.max())
    log_statistics["max_min_distance_color"].append(
        palette_standardLAB[np.argmax(min_distance_each_color)])

    return DP_previous_index, DP_loss
Esempio n. 32
0
Showcases *Delta E* colour difference computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"Delta E" Computations')

Lab_1 = np.array([100.00000000, 21.57210357, 272.22819350])
Lab_2 = np.array([100.00000000, 426.67945353, 72.39590835])
message_box(('Computing "Delta E" with "CIE 1976" method from given '
             '"CIE L*a*b*" colourspace matrices:\n'
             '\n\t{0}\n\t{1}'.format(Lab_1, Lab_2)))
print(colour.delta_E(Lab_1, Lab_2, method='CIE 1976'))
print(colour.difference.delta_E_CIE1976(Lab_1, Lab_2))

print('\n')

message_box(('Computing "Delta E" with "CIE 1994" method from given '
             '"CIE L*a*b*" colourspace matrices:\n'
             '\n\t{0}\n\t{1}'.format(Lab_1, Lab_2)))
print(colour.delta_E(Lab_1, Lab_2, method='CIE 1994'))
print(colour.difference.delta_E_CIE1994(Lab_1, Lab_2))

print('\n')

message_box(('Computing "Delta E" with "CIE 1994" method from given '
             '"CIE L*a*b*" colourspace matrices for "graphics arts" '
             'applications:\n'
Esempio n. 33
0
Showcases *Delta E* colour difference computations.
"""

import numpy as np

import colour
from colour.utilities import message_box

message_box('"Delta E" Computations')

Lab1 = np.array([100.00000000, 21.57210357, 272.22819350])
Lab2 = np.array([100.00000000, 426.67945353, 72.39590835])
message_box(('Computing "Delta E" with "CIE 1976" method from given '
             '"CIE L*a*b*" colourspace matrices:\n'
             '\n\t{0}\n\t{1}'.format(Lab1, Lab2)))
print(colour.delta_E(Lab1, Lab2, method='CIE 1976'))
print(colour.difference.delta_E_CIE1976(Lab1, Lab2))

print('\n')

message_box(('Computing "Delta E" with "CIE 1994" method from given '
             '"CIE L*a*b*" colourspace matrices:\n'
             '\n\t{0}\n\t{1}'.format(Lab1, Lab2)))
print(colour.delta_E(Lab1, Lab2, method='CIE 1994'))
print(colour.difference.delta_E_CIE1994(Lab1, Lab2))

print('\n')

message_box(('Computing "Delta E" with "CIE 1994" method from given '
             '"CIE L*a*b*" colourspace matrices for "graphics arts" '
             'applications:\n'