示例#1
0
def _process_imgt(img,
                  gt,
                  gamma=0,
                  clahe=False,
                  gray=False,
                  xyz=False,
                  horizontal_flip=False,
                  width_shift_range=0,
                  height_shift_range=0,
                  vertical_flip=0,
                  rotate_range=0,
                  bw_gt=True):
    img = exposure.rescale_intensity(img.astype(float), out_range=(0, 1))
    if gray:
        img = color.rgb2gray(img)
    if xyz:
        img = color.rgb2xyz(img)
        img = exposure.rescale_intensity(img, out_range=(0, 1))
    if clahe:
        img = exposure.equalize_adapthist(img)
    if gamma:
        img = exposure.adjust_gamma(img, gamma)
        img = exposure.rescale_intensity(img, out_range=(0, 1))
    if img.ndim == 2:
        img = np.expand_dims(img, -1)

    img, gt = flip_img(img, gt, horizontal_flip, vertical_flip)
    img, gt = shift_img(img, gt, width_shift_range, height_shift_range,
                        rotate_range)

    return img, gt
示例#2
0
def convert(colorspace, image):

    # Normalize data.
    image = image.astype('float32') / 255
    #conver to HSL
    if colorspace == "HSL":
        image = convertHSL(image)
    #conver to HSV
    if colorspace == "HSV":
        image = color.rgb2hsv(image)

    #conver to XYZ
    if colorspace == "XYZ":
        image = color.rgb2xyz(image)

    #conver to LUV
    if colorspace == "LUV":
        image = color.rgb2luv(image)

    #conver to LAB
    if colorspace == "LAB":
        image = color.rgb2lab(image)

    #conver to YUV
    if colorspace == "YUV":
        image = color.rgb2yuv(image)

    print("finish")
    from scipy.misc import imsave
    imsave('test.png', image)
    return image
示例#3
0
def expand_colorspace_cv(img_str, printonoff='on'):
    # param:
    #     img_str: the string of picture dir || picture list
    #     printonoff: print process in console whether or not
    # return: the list of expanded colorspace picture list
    t = time.time()
    if isinstance(img_str, str):
        if printonoff == 'on': print('|--- Convert classified picture [' + img_str + ']')
        RGB = io.imread(img_str)
        if RGB.shape[2] == 4:    # exists alpha layer
            RGB = RGB[:,:,0:3]
        LAB = color.rgb2lab(RGB)
        if printonoff == 'on': print('|   |--- lab converted')
        HSV = color.rgb2hsv(RGB)
        if printonoff == 'on': print('|   |--- hsv converted')
        XYZ = color.rgb2xyz(RGB)
        if printonoff == 'on': print('|   |--- xyz converted')
        (height, width, dimen) = RGB.shape
        rgb = RGB.reshape(height * width, dimen); del RGB
        lab = LAB.reshape(height * width, dimen); del LAB
        hsv = HSV.reshape(height * width, dimen); del HSV
        xyz = XYZ.reshape(height * width, dimen); del XYZ
        if printonoff == 'on': print('|   ^--- reshaped')
        img_size = (height, width)
        expand = np.concatenate((rgb, lab, hsv, xyz), axis=1);del rgb, lab, hsv, xyz
        if printonoff == 'on':
            print('|        |--- Combined = ' + str(round(sys.getsizeof(expand) / 8 / 1024 / 1024, 3)) + ' MB')
        if printonoff == 'on': print('|        ^--- Cost ' + str(round(time.time() - t, 3)) + ' s')
        return expand, img_size
    else:
        RGB = img_str.reshape(1, img_str.shape[0], 3)
        LAB = color.rgb2lab(RGB)
        if printonoff == 'on': print('|   |   |--- lab converted')
        HSV = color.rgb2hsv(RGB)
        if printonoff == 'on': print('|   |   |--- hsv converted')
        XYZ = color.rgb2xyz(RGB)
        if printonoff == 'on': print('|   |   |--- xyz converted')
        rgb = img_str; del RGB
        lab = LAB[0]; del LAB
        hsv = HSV[0]; del HSV
        xyz = XYZ[0]; del XYZ
        if printonoff == 'on': print('|   |   ^--- reshaped')
        expand = np.concatenate((rgb, lab, hsv, xyz), axis=1); del rgb, lab, hsv, xyz
        if printonoff == 'on':
            print('|   |        |--- Combined = ' + str(round(sys.getsizeof(expand)/8/1024/1024, 3)) + ' MB')
        if printonoff == 'on': print('|   |        ^--- Cost ' + str(round(time.time() - t, 3)) + ' s')
        return expand
示例#4
0
def from_rgb_to_xyz(rgb_colors, normalize=True):

    xyz_colors = rgb2xyz(rgb_colors)

    if normalize:
        return xyz_colors / np.max(xyz_colors)
    else:
        return xyz_colors
示例#5
0
    def test_xyz_rgb_roundtrip(self, channel_axis):
        img_rgb = img_as_float(self.img_rgb)

        img_rgb = np.moveaxis(img_rgb, source=-1, destination=channel_axis)
        round_trip = xyz2rgb(rgb2xyz(img_rgb, channel_axis=channel_axis),
                             channel_axis=channel_axis)

        assert_array_almost_equal(round_trip, img_rgb)
示例#6
0
 def test_rgb2xyz_conversion(self):
     gt = np.array([[[0.950456, 1., 1.088754],
                     [0.538003, 0.787329, 1.06942],
                     [0.592876, 0.28484, 0.969561],
                     [0.180423, 0.072169, 0.950227]],
                    [[0.770033, 0.927831, 0.138527],
                     [0.35758, 0.71516, 0.119193],
                     [0.412453, 0.212671, 0.019334], [0., 0., 0.]]])
     assert_almost_equal(rgb2xyz(self.colbars_array), gt)
示例#7
0
 def test_rgb2xyz_conversion(self):
     gt = np.array([[[0.950456, 1.      , 1.088754],
                     [0.538003, 0.787329, 1.06942 ],
                     [0.592876, 0.28484 , 0.969561],
                     [0.180423, 0.072169, 0.950227]],
                    [[0.770033, 0.927831, 0.138527],
                     [0.35758 , 0.71516 , 0.119193],
                     [0.412453, 0.212671, 0.019334],
                     [0.      , 0.      , 0.      ]]])
     assert_almost_equal(rgb2xyz(self.colbars_array), gt)
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()
示例#9
0
    def build_features_from_arr(self, img_rgb):
        # the third component `_` is actually the number of channels in RGB,
        # which is already defined in the constant `NUM_RGB_CHANNELS`
        num_rows, num_cols, _ = img_rgb.shape
        num_pixels = num_rows * num_cols
        img_lab = color.rgb2lab(img_rgb)
        img_lab_l = img_lab[:, :, 0]  # ACHTUNG: this is a view

        X = np.zeros((num_pixels, self.num_pixel_features), dtype=np.float32)

        # color features
        # tpf.compute_color_features(X_img[:, self.color_slice])
        img_lab_vec = img_lab.reshape(num_rows * num_cols, NUM_LAB_CHANNELS)
        img_xyz_vec = color.rgb2xyz(img_rgb).reshape(num_rows * num_cols,
                                                     NUM_XYZ_CHANNELS)
        img_ill_vec = np.dot(A, np.log(np.dot(B, img_xyz_vec.transpose()) +
                                       1)).transpose()
        X[:, :NUM_LAB_CHANNELS] = img_lab_vec
        X[:,
          NUM_LAB_CHANNELS:NUM_LAB_CHANNELS + NUM_ILL_CHANNELS] = img_ill_vec

        # texture features
        # tpf.compute_texture_features(X_img[:, self.texture_slice],
        #                              self.sigmas, self.num_orientations)
        for i, sigma in enumerate(self.sigmas):
            base_kernel_arr = filters.get_texture_kernel(sigma)
            for j, orientation in enumerate(range(self.num_orientations)):
                # theta = orientation / num_orientations * np.pi
                theta = orientation * 180 / self.num_orientations
                oriented_kernel_arr = ndi.interpolation.rotate(
                    base_kernel_arr, theta)
                img_filtered = ndi.convolve(img_lab_l, oriented_kernel_arr)
                img_filtered_vec = img_filtered.flatten()
                X[:, self.num_color_features + i * self.num_orientations +
                  j] = img_filtered_vec

        # entropy features
        # tpf.compute_entropy_features(X_img[:, self.entropy_slice],
        #                              self.neighborhood, self.scales)
        entropy_start = self.num_color_features + self.num_texture_features
        X[:, entropy_start] = rank.entropy(img_lab_l.astype(np.uint16),
                                           self.neighborhood).flatten()

        for i, factor in enumerate(self.scales[1:], start=1):
            img = transform.resize(
                transform.downscale_local_mean(img_lab_l, (factor, factor)),
                img_lab_l.shape).astype(np.uint16)
            X[:,
              entropy_start + i] = rank.entropy(img,
                                                self.neighborhood).flatten()

        return X
示例#10
0
def alterXYZ(img):
    img = color.rgb2xyz(img)
    params = []
    #X
    img[:, :, 0] += randUnifC(-0.05, 0.05, params=params)
    #Y
    img[:, :, 1] += randUnifC(-0.05, 0.05, params=params)
    #Z
    img[:, :, 2] += randUnifC(-0.05, 0.05, params=params)
    img = np.clip(img, 0, 1.0)
    img = color.xyz2rgb(img)
    img = np.clip(img, 0, 1.0)
    return img
示例#11
0
def G2_getfeatures(ims, fil_paras, gridshape, mode="reflect", cval=0):
    '''
    A routine which takes an array of images with 4 coords.
    Dim 1 and 2: pixel position.
    Dim 3: RGB channel index.
    Dim 4: Time index.
    '''

    num_ims = ims.shape[3]
    num_feats = gridshape[0] * gridshape[1]

    out = np.zeros(num_ims * num_feats, dtype=np.float32).reshape(
        (num_ims, num_feats))

    # Generate the kernel prior to loop over images.
    fil_values = fil_kernel(paras=fil_paras, n_stds=2)

    # Iterate over images.
    for i in range(num_ims):

        featvec = np.arange(0, dtype=np.float32)

        # Slice -> XYZ -> CIE Lab -> Take only Luminance channel.
        im = col.xyz2lab(col.rgb2xyz(ims[:, :, :, i]))[:, :, 0]

        # Convolution.
        fil_response_real = ndi.convolve(input=im,
                                         weights=fil_values["real"],
                                         mode=mode,
                                         cval=cval)
        fil_response_imag = ndi.convolve(input=im,
                                         weights=fil_values["imag"],
                                         mode=mode,
                                         cval=cval)
        fil_response_magnitude = np.sqrt(
            (fil_response_real**2 + fil_response_imag**2))

        # Per-patch statistics.
        imstats = patch_stats(image=fil_response_magnitude,
                              grid_h=gridshape[0],
                              grid_w=gridshape[1])

        # Pass per-patch statistics through non-linearity to compute final feature vector.
        imfeats = nonlin(imstats["mean"])

        # Store the feature vector for this image.
        out[i, :] = imfeats

    # Output is the array of feature vectors, one feature vector for each image.
    return out
示例#12
0
    def test_rgb2xyz_conversion(self, channel_axis):
        gt = np.array([[[0.950456, 1., 1.088754],
                        [0.538003, 0.787329, 1.06942],
                        [0.592876, 0.28484, 0.969561],
                        [0.180423, 0.072169, 0.950227]],
                       [[0.770033, 0.927831, 0.138527],
                        [0.35758, 0.71516, 0.119193],
                        [0.412453, 0.212671, 0.019334], [0., 0., 0.]]])

        img = np.moveaxis(self.colbars_array,
                          source=-1,
                          destination=channel_axis)
        out = rgb2xyz(img, channel_axis=channel_axis)
        out = np.moveaxis(out, source=channel_axis, destination=-1)

        assert_almost_equal(out, gt)
示例#13
0
def get_XYZ(image):
    """Transforms RGB Image into XYZ

    Args:
        image: image to convert

    Returns:
        XYZ information obtained from transformation

    Usage:

    >>> from PIL import Image
    >>> from ipfml.processing import transform
    >>> img = Image.open('./images/test_img.png')
    >>> transform.get_XYZ(img).shape
    (200, 200, 3)
    """

    return color.rgb2xyz(image)
示例#14
0
def task_1():
    """
    Convert the color space of Lena.png from RGB to CIE XYZ

    :return: None
    """
    # Read the Lena rgb image with type uint8
    rgb_img = io.imread('./images/Lena.png')
    # Convert to CIE XYZ
    xyz_img = rgb2xyz(rgb_img)
    fig, ax = plt.subplots(1, 2)
    # Display the image side by side with original
    ax[0].imshow(rgb_img)
    ax[0].set_axis_off()
    ax[0].set_title('Original(RGB) Lena')
    ax[1].imshow(xyz_img)
    ax[1].set_axis_off()
    ax[1].set_title('CIE XYZ Lena')
    plt.show()
示例#15
0
文件: q1.py 项目: danbronzy/cva_hw6
def loadData(path="../data/"):
    """
    Question 1 (c)

    Load data from the path given. The images are stored as input_n.tif
    for n = {1...7}. The source lighting directions are stored in
    sources.mat.

    Paramters
    ---------
    path: str
        Path of the data directory

    Returns
    -------
    I : numpy.ndarray
        The 7 x P matrix of vectorized images

    L : numpy.ndarray
        The 3 x 7 matrix of lighting directions

    s: tuple
        Image shape

    """

    im = [str(x) for x in range(1, 8)]
    I = []
    for i in im:
        arr = imread(path + 'input_{}.tif'.format(i)).astype(np.uint16)
        arr = rgb2xyz(arr)[:, :, 1]
        s = arr.shape
        I.append(arr.flatten())

    I = np.array(I)

    L = np.load(path + 'sources.npy').T

    _, sv, _ = np.linalg.svd(I, full_matrices=False)
    print("I matrix singular values:\n\t{}".format(sv))

    return I, L, s
示例#16
0
def salvarcombinacoes(img):
    img_rgb = color.convert_colorspace(img, 'RGB', 'RGB')
    img_hsv = color.convert_colorspace(img_rgb, 'RGB', 'HSV')
    img_lab = color.rgb2lab(img_rgb)
    img_hed = color.rgb2hed(img_rgb)
    img_luv = color.rgb2luv(img_rgb)
    img_rgb_cie = color.convert_colorspace(img_rgb, 'RGB', 'RGB CIE')
    img_xyz = color.rgb2xyz(img_rgb)
    img_cmy = rgb2cmy(img_rgb)

    lista = [img_rgb, img_hsv, img_lab, img_hed, img_luv, img_rgb_cie, img_xyz, img_cmy]
    lista2 = ["rgb", "hsv", "lab", "hed", "luv", "rgb_cie", "xyz", "cmy"]
    for i in range(len(lista)):
        for j in range(len(lista)):
            for k in range(3):
                for l in range(3):
                    nome = lista2[i] + str(k) + lista2[j] + str(l) + ".jpg"
                    io.imsave(nome, juntarcanais(lista[i][:, :,k], lista[j][:, :, l]), )

    return
示例#17
0
def loadData(path="../data/"):
    """
    Question 1 (c)

    Load data from the path given. The images are stored as input_n.tif
    for n = {1...7}. The source lighting directions are stored in
    sources.mat.

    Paramters
    ---------
    path: str
        Path of the data directory

    Returns
    -------
    I : numpy.ndarray
        The 7 x P matrix of vectorized images

    L : numpy.ndarray
        The 3 x 7 matrix of lighting directions

    s: tuple
        Image shape

    """
    I = []
    for i in range(7):
        image = imread(os.path.join(path, f'input_{i+1}.tif'))
        if image.dtype != np.uint16:
            image = image.astype(np.uint16)

        # Luminance channel is Y
        image = rgb2xyz(image)[:, :, 1]
        s = image.shape
        I.append(image.flatten())

    I = np.asarray(I)
    # print(I.dtype)
    L = np.load(os.path.join(path, "sources.npy")).T
    # print(I.shape, L.shape)
    return I, L, s
示例#18
0
def get_XYZ_Y(image):
    """Transforms RGB Image into XYZ and returns Y

    Args:
        image: image to convert

    Returns:
        The Y chanel from XYZ information

    Usage:

    >>> from PIL import Image
    >>> from ipfml.processing import transform
    >>> img = Image.open('./images/test_img.png')
    >>> y = transform.get_XYZ_Y(img)
    >>> y.shape
    (200, 200)
    """

    xyz = color.rgb2xyz(image)
    return xyz[:, :, 1]
示例#19
0
def xyz_shift(img, kt):
    """Apply chromatic aberration."""
    img = color.rgb2xyz(img)
    shp = img.shape
    red = img[:, :, 0]
    green = img[:, :, 1]
    blue = img[:, :, 2]
    # split channels, make shift
    red = tf.resize(red, output_shape=(shp[0], shp[1]))
    green = tf.resize(green, output_shape=(shp[0] - kt, shp[1] - kt))
    blue = tf.resize(blue, output_shape=(shp[0] - 2 * kt, shp[1] - 2 * kt))

    w, h = blue.shape
    ktd2 = int(kt / 2)
    red_n = np.reshape(red[kt:-kt, kt:-kt], (w, h, 1))
    green_n = np.reshape(green[ktd2:-1 * ktd2, ktd2:-1 * ktd2], (w, h, 1))
    blue_n = np.reshape(blue[:, :], (w, h, 1))

    new_im = np.concatenate((red_n, green_n, blue_n), axis=2)
    new_im = tf.resize(new_im, (shp[0], shp[1]))
    new_im = color.xyz2rgb(new_im)
    return new_im
示例#20
0
def loadData(path="../data/"):
    """
    Question 1 (c)

    Load data from the path given. The images are stored as input_n.tif
    for n = {1...7}. The source lighting directions are stored in
    sources.mat.

    Paramters
    ---------
    path: str
        Path of the data directory

    Returns
    -------
    I : numpy.ndarray
        The 7 x P matrix of vectorized images

    L : numpy.ndarray
        The 3 x 7 matrix of lighting directions

    s: tuple
        Image shape

    """
    img = imread('../data/input_1.tif')
    H, W, _ = img.shape
    s = (H, W)
    I = np.zeros((7, H * W))
    for i in range(7):
        img = imread('../data/input_{}.tif'.format(i + 1))
        img = rgb2xyz(img)
        img = img[:, :, 1].flatten()
        I[i, :] = img

    L = np.load('../data/sources.npy')
    L = L.T
    return I, L, s
示例#21
0
def load_data(folder_path, method='rgb'):
    rgb_img, low_channel_img, hs_img = None, None, None

    file_names = os.listdir(folder_path)
    for file_name in file_names:
        if '.mat' in file_name:
            hs_file_path = os.path.join(folder_path, file_name)

            rgb_img = create_rgb_from_hs(hs_file_path)
            if method == 'lab':
                low_channel_img = color.rgb2lab(rgb_img)
            elif method == 'xyz':
                low_channel_img = color.rgb2xyz(rgb_img)
            else:
                low_channel_img = rgb_img

            data = scipy.io.loadmat(hs_file_path)
            if 'reflectances' in data:
                hs_img = data['reflectances']
                hs_img = hs_img[:, :, :31]
                hs_img = hs_img / np.max(hs_img)

    return rgb_img, low_channel_img, hs_img
示例#22
0
def extract_color_descriptors(image, space=None, verbose=False):
    """
    Extract color descriptors of the image

    Parameters
    ----------
    image:

    space:
        None, equivalent to rgb
        rgb
        hsv
        xyz
        rgbcie

    Returns
    -------
    Descriptors
    """
    if space == 'hsv':
        image = color.rgb2hsv(image)
    elif space == 'xyz':
        image = color.rgb2xyz(image)
    elif space == 'rgbcie':
        image = color.rgb2rgbcie(image)
    elif space == 'gray' or space == 'grey':
        image = color.rgb2gray(image)

    gen = get_patch(image, size=1)
    descs = []
    for patch, coord in gen:
        if verbose and coord[1] % 5 == 0 and coord[0] == 0:
            print 'computed up to %d, %d' % coord
        desc = patch.flatten()
        desc = np.concatenate((desc, np.array(coord)))
        descs.append(desc)
    return np.array(descs)
示例#23
0
def get_XYZ_Z(image):
    """Transforms RGB Image into XYZ and returns Z

    Args:
        image: image to convert

    Returns:
        The Z chanel from XYZ information

    Raises:
        ValueError: If `nb_bits` has unexpected value. `nb_bits` needs to be in interval [1, 8].

    Usage:

    >>> from PIL import Image
    >>> from ipfml.processing import transform
    >>> img = Image.open('./images/test_img.png')
    >>> z = transform.get_XYZ_Z(img)
    >>> z.shape
    (200, 200)
    """

    xyz = color.rgb2xyz(image)
    return xyz[:, :, 2]
示例#24
0
model.add(Convolution2D(64, 4, 4, border_mode='valid'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3, border_mode='valid'))
model.add(Dropout(0.5))
model.add(Activation('relu'))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dense(6))
model.add(Activation('softmax')) #aqui o certo é um htan

sgd = SGD()
model.compile(loss = 'categorical_crossentropy', optimizer = sgd)

env = gym.make('Pong-v0')
obs = env.reset()
xyz = color.rgb2xyz(obs)
y = xyz[:,:,1]	
small = resize(y,(84,84))
in_obs = small.reshape(1, 1, 84, 84)

pred = model.predict(in_obs,batch_size=1,verbose=0)

print(pred)

#h = model.fit(X_train, Y_train, batch_size = 128, nb_epoch=3, validation_data =(X_test, Y_test), verbose=1) 


示例#25
0
 def test_xyz2rgb_conversion(self):
     # only roundtrip test, we checked rgb2xyz above already
     assert_almost_equal(xyz2rgb(rgb2xyz(self.colbars_array)),
                         self.colbars_array)
示例#26
0
文件: image.py 项目: zshipko/imagepy
 def to_xyz(self):
     return Image(rgb2xyz(self.to_rgb_from_gray()[:, :, :3])).convert_type(self.dtype)
def rgb2lms(rgbimage):
    """"""
    return XYZ2lms(rgb2xyz(rgbimage))
示例#28
0
 def test_xyz_rgb_roundtrip(self):
     img_rgb = img_as_float(self.img_rgb)
     assert_array_almost_equal(xyz2rgb(rgb2xyz(img_rgb)), img_rgb)
示例#29
0
 def test_xyz2rgb_conversion(self):
     assert_almost_equal(xyz2rgb(rgb2xyz(self.colbars_array)),
                         self.colbars_array)
示例#30
0
 def test_xyz2rgb_conversion(self):
     assert_almost_equal(xyz2rgb(rgb2xyz(self.colbars_array)),
                         self.colbars_array)
示例#31
0
    print "Thread %s. Opening file : %s" % (sys.argv[1], f)


    ### PROCESSING
        
    # Read the image
    A = io.imread(f)
        
    # Constrast enhancement
    print "Thread %s. Sigmoid transform for contrast." % sys.argv[1]
    B = exposure.adjust_sigmoid(A, gain=12)
        
    # Extract luminosity
    print "Thread %s. Generating luminosity." % sys.argv[1]
    C = color.rgb2xyz(B)[:, :, 1]
    
    # Apply adaptive thresholding
    print "Thread %s. Performing adaptive thresholding." % sys.argv[1]
    D = filter.threshold_adaptive(C, 301)
    D2 = filter.threshold_adaptive(C, 301, offset=-0.01)
        
    # Clean
    print "Thread %s. Cleaning image." % sys.argv[1]
    E = morphology.remove_small_objects(~morphology.remove_small_objects(~D, 100), 100)
    E2 = morphology.remove_small_objects(~morphology.remove_small_objects(~D2, 100), 100)
    blur.append(np.abs(E[:2000, 1000:-1000] - E2[:2000, 1000:-1000]).sum() / 6368000.)

    # Save to disk
    io.imsave(f + "_processed.jpg", ski.img_as_float(E))
        
    return plt

#Input's Block

    #Single Reader
img = data.imread('img/nor.jpg', False,)
    #Set Reader

#Convert Block
img_rgb = color.convert_colorspace(img, 'RGB', 'RGB') #No need
img_hsv = color.convert_colorspace(img_rgb, 'RGB', 'HSV')
img_lab = color.rgb2lab(img_rgb)
img_hed = color.rgb2hed(img_rgb)
img_luv = color.rgb2luv(img_rgb)
img_rgb_cie = color.convert_colorspace(img_rgb, 'RGB', 'RGB CIE')
img_xyz = color.rgb2xyz(img_rgb)

#Save Test Block
"""io.imsave("image_hsv.jpg", img_hsv, )
io.imsave("image_lab.jpg", img_lab, )
io.imsave("image_hed.jpg", img_hed, )
io.imsave("image_luv.jpg", img_luv, )
io.imsave("image_rgb_cie.jpg", img_rgb_cie, )
io.imsave("image_xyz.jpg", img_xyz, )
"""
#Layers Block
"""
canalExtration(img_rgb, "RGB").show()
canalExtration(img_hsv, "HSV").show()
canalExtration(img_lab, "LAB").show()
canalExtration(img_hed, "HED").show()
labels = morphology.watershed(-distance, markers, mask = clean)

io.imshow(labels, interpolation = "nearest", cmap = plt.cm.spectral)

# <codecell>

io.imshow(filter.gaussian_filter(image, 31))

# <codecell>

# Local density

B = image[:, :, 2]
#B = filter.gaussian_filter(np.abs(B - B.mean()), 31)
#io.imshow(B > 1.1*filter.threshold_otsu(B))
io.imshow(color.rgb2xyz(image)[:, :, 2])


#local_density = filter.gaussian_filter(image[:,:,0], 41)# - filter.gaussian_filter(clean, 201)
#io.imshow(local_density > 1.2 * filter.threshold_otsu(local_density, nbins = 1000))
#io.imshow(local_density - local_density.mean() > 0)
"""
#io.imshow(filter.gaussian_filter(clean, 51))
Q = (signal.convolve2d(ski.img_as_float(clean / clean.max()), ski.img_as_float(morphology.disk(201)), "valid"))# - filter.gaussian_filter(clean, 251))
Q -= Q.min()
Q /= Q.max()
io.imshow(Q)
"""

# <codecell>
示例#34
0
文件: converge.py 项目: TimSC/supra
def ColConv(px):
	out = col.rgb2xyz([[px]])[0][0]
	return out
示例#35
0
 def test_xyz_rgb_roundtrip(self):
     img_rgb = img_as_float(self.img_rgb)
     assert_array_almost_equal(xyz2rgb(rgb2xyz(img_rgb)), img_rgb)
示例#36
0
    def test_rgb2xyz_dtype(self):
        img = self.colbars_array
        img32 = img.astype('float32')

        assert rgb2xyz(img).dtype == img.dtype
        assert rgb2xyz(img32).dtype == img32.dtype
示例#37
0
def hsi2lab(shi_pic):
    tmp_rgb = color.hsv2rgb(hsv)
    tmp_xyz = color.rgb2xyz(tmp_rgb)
    return color.xyz2lab(tmp_xyz)
示例#38
0
    def test_xyz2rgb_dtype(self):
        img = rgb2xyz(self.colbars_array)
        img32 = img.astype('float32')

        assert xyz2rgb(img).dtype == img.dtype
        assert xyz2rgb(img32).dtype == img32.dtype
示例#39
0
def test_rgb_to_xyz_against_skimage(random_rgb):
    assert np.allclose(random_rgb.to_xyz(),
                       skcolor.rgb2xyz(random_rgb),
                       rtol=1e-2)
示例#40
0
 def trans(self, img):
     rst = color.rgb2xyz(img)
     print('============', rst.min(), rst.max())
     return (rst * (200)).astype(np.uint8)
A = io.imread(files[0])
As = transform.rescale(A, 0.25)
io.imshow(A)
plt.grid(False)

# <codecell>

#B = exposure.adjust_sigmoid(A, gain=12)
Bs = exposure.adjust_sigmoid(ski.img_as_float(As), gain=12)
#io.imshow(B - exposure.adjust_sigmoid(ski.img_as_float(A), gain=12))

# <codecell>

#C = color.rgb2xyz(B)[:, :, 1]
Cs = color.rgb2xyz(Bs)[:, :, 1]
io.imshow(Cs)
plt.grid(0)

# <codecell>

#D = filter.threshold_adaptive(C, 301)
Ds = filter.threshold_adaptive(Cs, 75)
io.imshow(Ds)
plt.grid(0)

# <codecell>

#E = morphology.remove_small_objects(~morphology.remove_small_objects(~D, 100), 100)
Es = morphology.remove_small_objects(~morphology.remove_small_objects(~Ds, 10), 10)
io.imshow(Es)
示例#42
0
        plt.axis("off")
        plt.title("VonKries")
        plt.tight_layout()
        plt.show()
    #----------------------------------------------------------------
    # Chromatic adaptation with different methods
    #----------------------------------------------------------------
    else:
        print(sorted(colour.CHROMATIC_ADAPTATION_TRANSFORMS))
        # Test view condition
        XYZ_w = np.array([234, 240, 220])
        # Reference view condition
        XYZ_wr = np.array([224, 187, 70])
        method = 'Von Kries'
        VonKries = colour.adaptation.chromatic_adaptation_VonKries(
            rgb2xyz(im_gamma), XYZ_w, XYZ_wr, method)
        try:
            print(VonKries.shape)
        except ValueError:
            print('Dimentional error!')

        fig = plt.figure(figsize=(4, 5))
        fig.add_subplot(111)
        plt.imshow(VonKries)
        plt.title('VonKriesAdaptation')
        plt.tight_layout()
        plt.axis('off')
        plt.show()
    #---------------------------------------------------------------
    # Colorsapce conversation- destation ATD
    # Visualization channel with fake color
 def rgb2xyz(self,imageArray):
     return color.rgb2xyz(imageArray)