Exemple #1
0
def colordiff(A, B):
    if B.shape[0] == 1:
        B = np.repeat(B, A.shape[0], axis=0)
    ac = np.sqrt(A[:, 1]**2 + A[:, 2]**2)
    bc = np.sqrt(B[:, 1]**2 + B[:, 2]**2)
    mc = (ac + bc) / 2
    g = (1 - np.sqrt(mc**7 / (mc**7 + 25.0**7))) / 2.
    A = A.copy()
    A[:, 1] *= (1 + g)
    B = B.copy()
    B[:, 1] *= (1 + g)

    A = color.lab2lch(A)
    B = color.lab2lch(B)

    dl = (B[:, 0] - A[:, 0])
    dc = (B[:, 1] - A[:, 1])
    dh = (B[:, 2] - A[:, 2])
    mask1 = (A[:, 1] * B[:, 1] == 0)
    mask2 = (~mask1) & (dh > 180)
    mask3 = (~mask1) & (dh < -180)
    dh[mask1] = 0
    dh[mask2] -= 360
    dh[mask3] += 360

    dh = 2 * np.sqrt(A[:, 1] * B[:, 1]) * np.sin(np.deg2rad(dh / 2.))
    ml = (A[:, 0] + B[:, 0]) / 2
    mc = (A[:, 1] + B[:, 1]) / 2
    mh = np.zeros_like(dh)
    mh[mask1] = A[mask1, 2] + B[mask1, 2]
    mh[~mask1] = mean_hue(A[~mask1, 2], B[~mask1, 2])

    mls = (ml - 50)**2
    sl = 1.0 + 0.015 * mls / np.sqrt(20 + mls)

    # chroma weight
    sc = 1 + 0.045 * mc

    # hue weight
    t = 1 - 0.17 * np.cos(np.deg2rad(mh - 30)) + \
            0.24 * np.cos(np.deg2rad(2 * mh)) + \
            0.32 * np.cos(np.deg2rad(3 * mh + 6)) - \
            0.20 * np.cos(np.deg2rad(4 * mh - 63))
    sh = 1 + 0.015 * mc * t

    # rotation term
    dtheta = 30 * np.exp(-((mh - 275) / 25)**2)
    cr = 2 * np.sqrt(mc**7 / (mc**7 + 25.0**7))
    tr = -np.sin(np.deg2rad(2 * dtheta)) * cr
    return np.sqrt((dl/(1*sl))**2 + (dc/(1*sc))**2 + (dh/(1*sh))**2 + \
                   tr * (dc/(1*sc)) * (dh/(1*sh)))
def plot_segmented_colors(segmented_array, ax, colorSpace='rgb'):
    """
    Counts amount of pixels of corresponding segmented colors and plots 3D diagram

    Parameters
    ----------
    segmented_array: A numpy array containing RGB color rows after color segmentation

    ax : axis

    colorSpace: target color space, either 'rgb' or 'hsv'
    """

    seg_colors, color_counter = count_unique_rows(segmented_array)

    if colorSpace == 'rgb':
        if seg_colors.dtype is not 'float64':
            seg_colors = util.img_as_float(seg_colors.reshape(-1, 1, 3))
        plot_RGB_colors(seg_colors, ax, color_counter)
        return seg_colors
    elif colorSpace == 'hsv':
        colors = seg_colors.copy()
        seg_colors = seg_colors.reshape(seg_colors.shape[0], -1, 3)
        seg_colors = skimage_color.rgb2hsv(seg_colors)
        plot_HSV_colors(seg_colors, ax, colors, color_counter)
        return colors, color_counter
    elif colorSpace == 'LCh':
        colors = seg_colors.copy()
        seg_colors = seg_colors.reshape(-1, 1, 3)
        seg_colors = skimage_color.lab2lch(skimage_color.rgb2lab(seg_colors))
        return plot_CIELCH_colors(seg_colors, ax, colors, color_counter)
Exemple #3
0
 def test_rgb_lch_roundtrip(self):
     rgb = img_as_float(self.img_rgb)
     lab = rgb2lab(rgb)
     lch = lab2lch(lab)
     lab2 = lch2lab(lch)
     rgb2 = lab2rgb(lab2)
     assert_array_almost_equal(rgb, rgb2)
def change_hue(img, hue):
    lab_img = rgb2lab(img)
    lch_img = lab2lch(lab_img)
    lch_img[:, :, 2] = hue
    lab_img = lch2lab(lch_img)
    rgb_img = lab2rgb(lab_img)
    return rgb_img
 def test_rgb_lch_roundtrip(self):
     rgb = img_as_float(self.img_rgb)
     lab = rgb2lab(rgb)
     lch = lab2lch(lab)
     lab2 = lch2lab(lch)
     rgb2 = lab2rgb(lab2)
     assert_array_almost_equal(rgb, rgb2)
Exemple #6
0
def change_color_lch(batch_id, pal_lab, pal_name):
    file_path = './samples/img/'
    result_path = './samples/result_lch/'
    file_list = os.listdir(file_path)
    pal_lch = lab2lch(pal_lab)

    for _, name in enumerate(file_list):
        img_ori = plt.imread(file_path + name)
        img_lab = rgb2lab(img_ori)
        img_lch = lab2lch(img_lab)
        counter_lch = [0, 0, 0, 0, 0, 0, 0]
        for i in range(len(img_lch)):
            for j in range(len(img_lch[i])):
                point_ori = img_lch[i][j][2]
                total_diff_last = 11  # lot((1-0)^2 + (1-0)^2) +1
                for k in range(5):
                    point_pal = pal_lch[k][2]
                    total_diff = abs(point_ori - point_pal)
                    # 180 도 이상 처리 예각으로 대체
                    if total_diff > 5:
                        total_diff = 10 - total_diff
                        counter_lch[6] += 1
                    if total_diff < total_diff_last:
                        point_ori_tmp = point_pal
                        total_diff_last = total_diff
                        counter_fin = k
                if img_lch[i][j][1] <= 0.2 and img_lch[i][j][
                        0] >= 9.8:  # 채도 3 이하 명도 98 이상 패스(흰색)
                    counter_lch[5] += 1
                # elif total_diff_last >= 1.2: #1.41
                #     counter_hsv[6] += 1
                else:
                    counter_lch[counter_fin] += 1
                    img_lch[i][j][2] = point_ori_tmp
        sum_total = counter_lch[0] + counter_lch[1] + counter_lch[
            2] + counter_lch[3] + counter_lch[4] + counter_lch[5]
        print(
            f'[{pal_name}의 {name[0:-4]} 적용 내역] 팔레트1:{counter_lch[0]:,}회, 팔레트2:{counter_lch[1]:,}회, '
            f'팔레트3:{counter_lch[2]:,}회, 팔레트4:{counter_lch[3]:,}회, 팔레트5:{counter_lch[4]:,}회, '
            f'흰색 패스:{counter_lch[5]:,}회, 팔레트 변환 :{sum_total-counter_lch[5]:,}회'
            f'({sum_total-counter_lch[5]-counter_lch[6]:,}회), 총 변환 :{sum_total:,}회'
        )
        img_trans = lch2lab(img_lch)
        img_trans = lab2rgb(img_trans, illuminant='D55')
        plt.imsave(
            os.path.join(result_path,
                         f'{batch_id}_{pal_name}_{name[0:-4]}.png'), img_trans)
def test_lab_lch_roundtrip_dtypes(dtype):
    rgb = img_as_float(data.colorwheel()).astype(dtype=dtype, copy=False)
    lab = rgb2lab(rgb)
    float_dtype = _supported_float_type(dtype)
    assert lab.dtype == float_dtype
    lab2 = lch2lab(lab2lch(lab))
    decimal = 4 if float_dtype == np.float32 else 7
    assert_array_almost_equal(lab2, lab, decimal=decimal)
 def test_lab_lch_roundtrip(self, channel_axis):
     rgb = img_as_float(self.img_rgb)
     rgb = np.moveaxis(rgb, source=-1, destination=channel_axis)
     lab = rgb2lab(rgb, channel_axis=channel_axis)
     lab2 = lch2lab(
         lab2lch(lab, channel_axis=channel_axis),
         channel_axis=channel_axis,
     )
     assert_array_almost_equal(lab2, lab)
Exemple #9
0
def rgb2lch(rgb):
    """Convert RBG to LCH colorspace (via LAB)
    Input and output are in (bands, cols, rows) order
    """
    # reshape for skimage (bands, cols, rows) -> (cols, rows, bands)
    srgb = np.swapaxes(rgb, 0, 2)
    # convert colorspace
    lch = lab2lch(rgb2lab(srgb))
    # return in (bands, cols, rows) order
    return np.swapaxes(lch, 2, 0)
def preserve_color_cielch(content, stylized, image_name):

    # extract info and convert to CIE-LCh for each image
    rgbContent = io.imread(content)
    labContent = color.lab2lch(
        color.xyz2lab(color.rgb2xyz(numpy.asarray(rgbContent))))
    labContentArray = numpy.array(labContent)
    rgbStyle = io.imread(stylized)
    labStyle = color.lab2lch(
        color.xyz2lab(color.rgb2xyz(numpy.asarray(rgbStyle))))
    labStyleArray = numpy.array(labStyle)

    # color transfer
    for i in range(len(labContentArray)):
        for j in range(len(labContentArray[0])):
            labContentArray[i][j][0] = labStyleArray[i][j][0]

    labContentArray = color.xyz2rgb(
        color.lab2xyz(color.lch2lab(labContentArray)))
    viewer = ImageViewer(labContentArray)
    viewer.show()
Exemple #11
0
def get_color_map_1d(anchors):
  n = len(anchors)
  anchors = anchors.reshape((1, -1, 3))
  x = np.mgrid[0:1:n*1j]
  lab = color.rgb2lab(anchors)
  lch = color.lab2lch(lab)
  lch = lch.reshape((-1, 3))
  L = UnivariateSpline(x, lch[:,0])
  C = UnivariateSpline(x, lch[:,1])
  H = UnivariateSpline(x, lch[:,2])
  def curve(t):
    LCH = np.stack((L(t), C(t), H(t)), axis=-1)
    return color.lch2lab(LCH)
  return curve
def training(request):
    LAB_Info = LAB_Clothe.objects.values_list()
    l = LAB_Info[LAB_Info.count()-1][1]
    a = LAB_Info[LAB_Info.count()-1][2]
    b = LAB_Info[LAB_Info.count()-1][3]
    clothe = LAB_Info[LAB_Info.count()-1][4]


    lch = color.lab2lch([float(l), float(a), float(b)])
    c = lch[1]
    h = lch[2] * 180 / np.pi
    lab = [l, a, b]
    labch = [l, a, b, c, h]

    # loading data for selecting dyes
    df_all = pd.read_csv(DATA_FILE_ALL)
    df_all = df_all[df_all['abort'] != 1]
    df_all = df_all[df_all['L'].notnull()]

    df_single = pd.read_csv(DATA_FILE_SINGLE)
    df_single = df_single[df_single['abort'] != 1]

    """ 選擇染料組合 """
    dye_selector = DyeSelector(history_num_limit=history_num_limit,
                               max_collection_count=max_collection_count)
    possible_collections = dye_selector.get_possible_collections(df_all, df_single, labch)

    """ 計算染料濃度 """
    inverse_decoder = InverseDecoder(DECODER_PATH, 100)
    inverse_decoder.build_graph()

    with tf.Session() as sess:
        inverse_decoder.init_model(sess)
        pred = inverse_decoder.predict_concentrations(possible_collections, clothe, lab)
        pred = modify_pred(pred)
        losses = inverse_decoder.lab_loss(pred, [lab] * len(pred))

    """ output result to csv """
    df_output = process_output_csv(pred, losses, decoder_input_columns, clothe, clothe_type_count)
    output_path = os.path.join(OUTPUT_DIR, f'{time.time()}.csv')
    df_output.to_csv(output_path, index=False)

    df_output = df_output[['布號', '染料_1', '濃度_1', '染料_2', '濃度_2', '染料_3', '濃度_3', '染料_4', '濃度_4', 'delta_lab']]

    context = {'output_table': df_output}

    return render(request, 'PigPredict_app/index.html', context)
def LabCHCalculator(frame):
    imagergb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    imagelab = rgb2lab(imagergb)
    imagelch = lab2lch(imagelab)
    L = list()
    a = list()
    b = list()
    C = list()
    H = list()
    [(L.append(y[0]), a.append(y[1]), b.append(y[2])) for x in imagelab
     for y in x]
    [(C.append(y[1]), H.append(y[2])) for x in imagelch for y in x]
    return [
        sum(L) / len(L),
        sum(a) / len(a),
        sum(b) / len(b),
        sum(C) / len(C), (sum(H) * 57.289071045) / len(H)
    ]
Exemple #14
0
def get_color_map_2d(anchors):
  n, m, ch = anchors.shape
  assert ch == 3
  s, t = np.mgrid[0:1:n*1j, 0:1:m*1j]
  lab = color.rgb2lab(anchors)
  lch = color.lab2lch(lab)
  s = s.ravel()
  t = t.ravel()
  h = lch[:,:,2]
  for j in range(1, m):
    for i in range(n):
      while True:
        diff = h[i, j] - h[i, j-1]
        if diff > pi:
          h[i, j] -= 2*pi
        elif diff < -pi:
          h[i, j] += 2*pi
        else:
          break
  h_avg = np.average(h, weights=lch[:,:,1], axis=1)
  reverse = np.zeros(h_avg.shape, dtype=np.uint8)
  reverse[1:] = h_avg[1:] < h_avg[:-1]
  reverse=np.cumsum(reverse)
  print(reverse)
  h += reverse.reshape((-1, 1)) * 2*pi
  print(h)
  l = lch[:,:,0].ravel()
  c = lch[:,:,1].ravel()
  h = h.ravel()
  kx = min(1, n-1)
  L = SmoothBivariateSpline(s, t, l, kx=kx)
  C = SmoothBivariateSpline(s, t, c, kx=kx)
  H = SmoothBivariateSpline(s, t, h, kx=kx)
  def surface(s, t):
    LCH = np.stack((L(s, t, grid=False), C(s, t, grid=False), H(s, t, grid=False)), axis=-1)
    return color.lch2lab(LCH)
  return surface
Exemple #15
0
def componentes(c):
    """
    Esta función obteniene todos los componentes, espectros y represen-
    taciones de color de la image. Los formatos en los cuales se va   a
    transformar la imagen son: RGB, HSV, CMYK, B_LAB, LCH, R_LAB 
    
    Input:
        - c: Imagen a la cual se le quieren sacar los componentes.
    Output:
        - (a1,a2,a3,a4,a5,a6): Posibles representaciones de la imagen.
    """
    a1 = chori(c)
    a2 = cvtColor(c, COLOR_BGR2HSV)
    a2 = chori(a2)
    a3 = phim.rgb2cmyk(np.asarray(c))
    a3 = chori(a3)
    a4 = cvtColor(c, COLOR_BGR2LAB)
    a4_1 = chori(a4)
    a5 = color.lab2lch(a4)
    a5 = chori(a5)
    k = a4[:, :, 2]
    a6 = np.hstack((k, k, k))

    return a1, a2, a3, a4_1, a5, a6
Exemple #16
0
 def test_lab_lch_roundtrip(self):
     rgb = img_as_float(self.img_rgb)
     lab = rgb2lab(rgb)
     lab2 = lch2lab(lab2lch(lab))
     assert_array_almost_equal(lab2, lab)
def shadow_detection(image_file, shadow_mask_file, convolve_window_size = 5, num_thresholds = 3, struc_elem_size = 5):
    """
    This function is used to detect shadow - covered areas in an image, as proposed in the paper 
    'Near Real - Time Shadow Detection and Removal in Aerial Motion Imagery Application' by Silva G.F., Carneiro G.B., 
    Doth R., Amaral L.A., de Azevedo D.F.G. (2017)
    
    Inputs:
    - image_file: Path of image to be processed for shadow removal. It is assumed that the first 3 channels are ordered as
                  Red, Green and Blue respectively
    - shadow_mask_file: Path of shadow mask to be saved
    - convolve_window_size: Size of convolutional matrix filter to be used for blurring of specthem ratio image
    - num_thresholds: Number of thresholds to be used for automatic multilevel global threshold determination
    - struc_elem_size: Size of disk - shaped structuring element to be used for morphological closing operation
    
    Outputs:
    - shadow_mask: Shadow mask for input image
    
    """
    
    if (convolve_window_size % 2 == 0):
        raise ValueError('Please make sure that convolve_window_size is an odd integer')
        
    buffer = int((convolve_window_size - 1) / 2)
    
    
    with rasterio.open(image_file) as f:
        metadata = f.profile
        img = rescale_intensity(np.transpose(f.read(tuple(np.arange(metadata['count']) + 1)), [1, 2, 0]), out_range = 'uint8')
        img = img[:, :, 0 : 3]
    
    
    lch_img = np.float32(lab2lch(rgb2lab(img)))
    
    
    l_norm = rescale_intensity(lch_img[:, :, 0], out_range = (0, 1))
    h_norm = rescale_intensity(lch_img[:, :, 2], out_range = (0, 1))
    sr_img = (h_norm + 1) / (l_norm + 1)
    log_sr_img = np.log(sr_img + 1)
    
    del l_norm, h_norm, sr_img
    gc.collect()

    

    avg_kernel = np.ones((convolve_window_size, convolve_window_size)) / (convolve_window_size ** 2)
    blurred_sr_img = cv2.filter2D(log_sr_img, ddepth = -1, kernel = avg_kernel)
      
    
    del log_sr_img
    gc.collect()
    
                
    flattened_sr_img = blurred_sr_img.flatten().reshape((-1, 1))
    labels = KMeans(n_clusters = num_thresholds + 1, max_iter = 10000).fit(flattened_sr_img).labels_
    flattened_sr_img = flattened_sr_img.flatten()
    df = pd.DataFrame({'sample_pixels': flattened_sr_img, 'cluster': labels})
    threshold_value = df.groupby(['cluster']).min().max()[0]
    df['Segmented'] = np.uint8(df['sample_pixels'] >= threshold_value)
    
    
    del blurred_sr_img, flattened_sr_img, labels, threshold_value
    gc.collect()
    
    
    shadow_mask_initial = np.array(df['Segmented']).reshape((img.shape[0], img.shape[1]))
    struc_elem = disk(struc_elem_size)
    shadow_mask = np.expand_dims(np.uint8(cv2.morphologyEx(shadow_mask_initial, cv2.MORPH_CLOSE, struc_elem)), axis = 0)
    
    
    del df, shadow_mask_initial, struc_elem
    gc.collect()
    

    metadata['count'] = 1
    with rasterio.open(shadow_mask_file, 'w', **metadata) as dst:
        dst.write(shadow_mask)
        
    return shadow_mask
def rgb2lch(rgb):
    return color.lab2lch(color.rgb2lab(rgb / 255.0))
Exemple #19
0
# argparser
parser = ArgumentParser()
parser.add_argument("-l", "--l", dest="l", help="-l: 請輸入0~100的值")
parser.add_argument("-a", "--a", dest="a", help="-a: 請輸入-128~128的值")
parser.add_argument("-b", "--b", dest="b", help="-b: 請輸入-128~128的值")
parser.add_argument("-clothe",
                    "--clothe",
                    dest="clothe",
                    help="-clothe: 請輸入以下三種布料(FVF2184, FVF2429, FVF2666)")

args = parser.parse_args()
l, a, b, clothe = validate(format(args.l), format(args.a), format(args.b),
                           format(args.clothe))
# l, a, b, clothe = 29.64, -9.27, -17.33, 'FVF2666'

lch = color.lab2lch([float(l), float(a), float(b)])
c = lch[1]
h = lch[2] * 180 / np.pi
lab = [l, a, b]
labch = [l, a, b, c, h]

# loading data for selecting dyes
df_all = pd.read_csv(DATA_FILE_ALL)
df_all = df_all[df_all['abort'] != 1]
df_all = df_all[df_all['L'].notnull()]

df_single = pd.read_csv(DATA_FILE_SINGLE)
df_single = df_single[df_single['abort'] != 1]
""" 選擇染料組合 """
dye_selector = DyeSelector(history_num_limit=history_num_limit,
                           max_collection_count=max_collection_count)
Exemple #20
0
REEXP_FOLDER_SCALE = r'\S*scale-(\d+)pc'
# ERROR:root:error: Image size (... pixels) exceeds limit of ... pixels,
# could be decompression bomb DOS attack.
# SEE: https://gitlab.mister-muffin.de/josch/img2pdf/issues/42
Image.MAX_IMAGE_PIXELS = None
#: maximal image size for visualisations, larger images will be downscaled
MAX_IMAGE_SIZE = 5000
#: define pair of forward and backward color space conversion
CONVERT_RGB = {
    'rgb': (lambda img: img, lambda img: img),
    'hsv': (rgb2hsv, hsv2rgb),
    'lab': (rgb2lab, lab2rgb),
    'luv': (rgb2luv, luv2rgb),
    'hed': (rgb2hed, hed2rgb),
    'lch':
    (lambda img: lab2lch(rgb2lab(img)), lambda img: lab2rgb(lch2lab(img))),
}


def detect_binary_blocks(vec_bin):
    """ detect the binary object by beginning, end and length in !d signal

    :param list(bool) vec_bin: binary vector with 1 for an object
    :return tuple(list(int),list(int),list(int)):

    >>> vec = np.array([1] * 15 + [0] * 5 + [1] * 20)
    >>> detect_binary_blocks(vec)
    ([0, 20], [15, 39], [14, 19])
    """
    begins, ends, lengths = [], [], []
Exemple #21
0
 def test_lab_lch_3d(self):
     lab0 = self._get_lab0()
     lch0 = lab2lch(lab0)
     lch3 = lab2lch(lab0[None, None, None, :])
     assert_array_almost_equal(lch0, lch3[0, 0, 0, :])
Exemple #22
0
if img.dtype != 'float32':
    img = cv2.normalize(img.astype('float32'), None, 0.0, 1.0, cv2.NORM_MINMAX)

# get dimensions of input image
x, y, z = img.shape

# store a copy of original image for comparison
img1 = np.zeros((x, y, z))
img1 = img.copy()

alpha = None

# Convert to colorspaces CIELAB, CIELUV, and CIELCH
lab = color.rgb2lab(img)  # - RGB to LAB
luv = color.rgb2luv(img)  # - RGB to LUV
LCH = color.lab2lch(img)  # - LAB to LCH

# Compute G(x, y) for image
Gx = np.zeros((x, y))   # Create empty array for Gx component
Gy = np.zeros((x, y))   # Create empty array for Gy component
for i in range(1, x-1):
    for j in range(1, y-1):
        #Calculate the Gx and Gy per pixel using color difference from Eq 3 (on pg 2 of paper)
        Gx[i, j] = color_difference(lab[i + 1, j, :], lab[i - 1, j, :], luv[i + 1, j, :], luv[i - 1, j, :], alpha)
        Gy[i, j] = color_difference(lab[i, j + 1, :], lab[i, j - 1, :], luv[i, j + 1, :], luv[i, j - 1, :], alpha)

# Assign Lightness, chroma, and hue arrays from LCH to their own respective arrays
L = LCH[:, :, 0]
C = LCH[:, :, 1]
H = LCH[:, :, 2]
T = np.zeros((x, y, 9))
Exemple #23
0
def rgb2lch(rgb):
    lab = color.rgb2lab(rgb)
    return color.lab2lch(lab)
Exemple #24
0
def lab2lch(LabPic):
    color.adapt_rgb.each_channel
    LchPic = color.lab2lch(LabPic)
    return (LchPic)
Exemple #25
0
def lightness(pixel):
    return lab2lch(rgb2lab(pixel))[:, :, 0]
Exemple #26
0
 def test_lab_lch_roundtrip(self):
     rgb = img_as_float(self.img_rgb)
     lab = rgb2lab(rgb)
     lab2 = lch2lab(lab2lch(lab))
     assert_array_almost_equal(lab2, lab)
Exemple #27
0
def chroma(pixel):
    return lab2lch(rgb2lab(pixel))[:, :, 1]
Exemple #28
0
 def test_lab_lch_3d(self):
     lab0 = self._get_lab0()
     lch0 = lab2lch(lab0)
     lch3 = lab2lch(lab0[None, None, None, :])
     assert_array_almost_equal(lch0, lch3[0, 0, 0, :])
Exemple #29
0
def hue(pixel):
    return lab2lch(rgb2lab(pixel))[:, :, 2]