示例#1
0
    def test_convert_colorspace(self):
        colspaces = ['HSV', 'RGB CIE', 'XYZ', 'YCbCr', 'YPbPr', 'YDbDr']
        colfuncs_from = [
            hsv2rgb, rgbcie2rgb, xyz2rgb, ycbcr2rgb, ypbpr2rgb, ydbdr2rgb
        ]
        colfuncs_to = [
            rgb2hsv, rgb2rgbcie, rgb2xyz, rgb2ycbcr, rgb2ypbpr, rgb2ydbdr
        ]

        assert_almost_equal(
            convert_colorspace(self.colbars_array, 'RGB', 'RGB'),
            self.colbars_array)

        for i, space in enumerate(colspaces):
            gt = colfuncs_from[i](self.colbars_array)
            assert_almost_equal(
                convert_colorspace(self.colbars_array, space, 'RGB'), gt)
            gt = colfuncs_to[i](self.colbars_array)
            assert_almost_equal(
                convert_colorspace(self.colbars_array, 'RGB', space), gt)

        self.assertRaises(ValueError, convert_colorspace, self.colbars_array,
                          'nokey', 'XYZ')
        self.assertRaises(ValueError, convert_colorspace, self.colbars_array,
                          'RGB', 'nokey')
示例#2
0
def random_shadow(img):   
    h, w = img.shape[0], img.shape[1]
    
    left_y = np.random.randint(-1*h, 2*h, 2) 
    right_y = np.random.randint(-1*h, 2*h, 2)
    #left_y = np.sort(left_y)
    #right_y = np.sort(right_y)
    
    if left_y[0] == right_y[0] or left_y[1] == right_y[1]:
        return img
    
    img = convert_colorspace(img, 'RGB', 'HSV')  # 0-1 float64
    
    #shadow_mask = np.zeros_like(img[:,:,0])
    X_m = np.mgrid[0:img.shape[0],0:img.shape[1]][1] # x coordinates of mask
    Y_m = np.mgrid[0:img.shape[0],0:img.shape[1]][0] # y coordinates of mask

    # upper line defined by (0, left_y[0]) and (w, right_y[0])
    shadow_mask_1 = ((Y_m - right_y[0]) / (left_y[0] - right_y[0]) - (X_m - w) / (0.0 - w)) <= 0
    # lower line defined by (0, left_y[1]) and (w, right_y[1])
    shadow_mask_2 = ((Y_m - right_y[1]) / (left_y[1] - right_y[1]) - (X_m - w) / (0.0 - w)) >= 0
    
    shadow_mask = (shadow_mask_1 & shadow_mask_2)
    
    img[shadow_mask, 2] *= np.random.uniform() * 0.3 + 0.2 # 0.2 ~ 0.5
    
    img = convert_colorspace(img, 'HSV', 'RGB')
    
    return img
    def test_convert_colorspace(self):
        colspaces = ['HSV', 'RGB CIE', 'XYZ', 'YCbCr', 'YPbPr', 'YDbDr']
        colfuncs_from = [
            hsv2rgb, rgbcie2rgb, xyz2rgb,
            ycbcr2rgb, ypbpr2rgb, ydbdr2rgb
        ]
        colfuncs_to = [
            rgb2hsv, rgb2rgbcie, rgb2xyz,
            rgb2ycbcr, rgb2ypbpr, rgb2ydbdr
        ]

        assert_almost_equal(
            convert_colorspace(self.colbars_array, 'RGB', 'RGB'),
            self.colbars_array)

        for i, space in enumerate(colspaces):
            gt = colfuncs_from[i](self.colbars_array)
            assert_almost_equal(
                convert_colorspace(self.colbars_array, space, 'RGB'), gt)
            gt = colfuncs_to[i](self.colbars_array)
            assert_almost_equal(
                convert_colorspace(self.colbars_array, 'RGB', space), gt)

        self.assertRaises(ValueError, convert_colorspace,
                          self.colbars_array, 'nokey', 'XYZ')
        self.assertRaises(ValueError, convert_colorspace,
                          self.colbars_array, 'RGB', 'nokey')
示例#4
0
def rotate_hue(rgb_image, rotate):
    lut = get_lut(rotate)
    hsl = color.convert_colorspace(rgb_image, 'RGB', 'HSV')
    hsl8 = img_as_ubyte(hsl)
    hsl8[:, :, 0] = lut[hsl8[:, :, 0]]
    new_rgb = color.convert_colorspace(hsl8, 'HSV', 'RGB')
    return new_rgb
def img_augment(img, translation=0.0, scale=1.0, rotation=0.0, gamma=1.0,
                contrast=1.0, hue=0.0, border_mode='constant'):
    if not (np.all(np.isclose(translation, [0.0, 0.0])) and
            np.isclose(scale, 1.0) and
            np.isclose(rotation, 0.0)):
        img_center = np.array(img.shape[:2]) / 2.0
        scale = (scale, scale)
        transf = transform.SimilarityTransform(translation=-img_center)
        transf += transform.SimilarityTransform(scale=scale, rotation=rotation)
        translation = img_center + translation
        transf += transform.SimilarityTransform(translation=translation)
        img = transform.warp(img, transf, order=3, mode=border_mode)
    if not np.isclose(gamma, 1.0):
        img **= gamma
    colorspace = 'rgb'
    if not np.isclose(contrast, 1.0):
        img = color.convert_colorspace(img, colorspace, 'hsv')
        colorspace = 'hsv'
        img[..., 1:] **= contrast
    if not np.isclose(hue, 0.0):
        img = color.convert_colorspace(img, colorspace, 'hsv')
        colorspace = 'hsv'
        img[..., 0] += hue
        img[img[..., 0] > 1.0, 0] -= 1.0
        img[img[..., 0] < 0.0, 0] += 1.0
    img = color.convert_colorspace(img, colorspace, 'rgb')
    if np.min(img) < 0.0 or np.max(img) > 1.0:
        raise ValueError('Invalid values in output image.')
    return img
def sigmas(image):
    """Finds the standard deviations of color in the image, in terms of hue / saturation / value"""

    mean = mean_color(image)
    height = len(image)
    width = len(image[0])
    num_pixels = height * width
    mean_hsv = color.convert_colorspace([[mean]], 'RGB', 'HSV')[0][0]
    image_hsv = color.convert_colorspace(image, 'RGB', 'HSV')
    total_hue = 0
    total_sat = 0
    total_val = 0

    for row in range(height):
        for col in range(width):
            """Note that the difference in hues does not use the standard metric, since the space of hues is circular"""
            hue_diff = min(abs(mean_hsv[0] - image_hsv[row][col][0]),
                           1 - abs(mean_hsv[0] - image_hsv[row][col][0]))
            sat_diff = abs(mean_hsv[1] - image_hsv[row][col][1])
            val_diff = abs(mean_hsv[2] - image_hsv[row][col][2])
            total_hue += hue_diff**2
            total_sat += sat_diff**2
            total_val += val_diff**2

    sigma_hue = math.sqrt(float(total_hue) / float(num_pixels))
    sigma_sat = math.sqrt(float(total_sat) / float(num_pixels))
    sigma_val = math.sqrt(float(total_val) / float(num_pixels))

    return [sigma_hue, sigma_sat, sigma_val]
def img_augment(img,
                translation=0.0,
                scale=1.0,
                rotation=0.0,
                gamma=1.0,
                contrast=1.0,
                hue=0.0,
                border_mode='constant'):
    if not (np.all(np.isclose(translation, [0.0, 0.0]))
            and np.isclose(scale, 1.0) and np.isclose(rotation, 0.0)):
        img_center = np.array(img.shape[:2]) / 2.0
        scale = (scale, scale)
        transf = transform.SimilarityTransform(translation=-img_center)
        transf += transform.SimilarityTransform(scale=scale, rotation=rotation)
        translation = img_center + translation
        transf += transform.SimilarityTransform(translation=translation)
        img = transform.warp(img, transf, order=3, mode=border_mode)
    if not np.isclose(gamma, 1.0):
        img **= gamma
    colorspace = 'rgb'
    if not np.isclose(contrast, 1.0):
        img = color.convert_colorspace(img, colorspace, 'hsv')
        colorspace = 'hsv'
        img[..., 1:] **= contrast
    if not np.isclose(hue, 0.0):
        img = color.convert_colorspace(img, colorspace, 'hsv')
        colorspace = 'hsv'
        img[..., 0] += hue
        img[img[..., 0] > 1.0, 0] -= 1.0
        img[img[..., 0] < 0.0, 0] += 1.0
    img = color.convert_colorspace(img, colorspace, 'rgb')
    if np.min(img) < 0.0 or np.max(img) > 1.0:
        raise ValueError('Invalid values in output image.')
    return img
def sort(selection):
    sort = Sorter()
    args = selection

    for i in range(img.shape[1]):
        img[:, i, :] = i / img.shape[0], .9, .9

    in_rgb = color.convert_colorspace(img, 'HSV', 'RGB')

    # Uncomment bellow to see starting image
    imsave('initial.png', in_rgb)

    for i in range(img.shape[0]):
        np.random.shuffle(img[i, :, :])

    in_rgb = color.convert_colorspace(img, 'HSV', 'RGB')
    imsave('initial_shuffled.png', in_rgb)

    # we've now got our shuffled, perfect image. let's jump through hoops now

    maxMoves = 0
    moves = []

    for i in range(img.shape[0]):
        newMoves = []
        if args == 'bubble':
            _, newMoves = sort.bubblesort(list(img[i, :, 0]))
        elif args == 'insertion':
            _, newMoves = sort.insertionsort(list(img[i, :, 0]))
        elif args == 'shell':
            _, newMoves = sort.shellsort(list(img[i, :, 0]))
        elif args == 'heap':
            # need to convert to integers for heap
            integer_version = img[i, :, 0] * 10000
            integer_version = integer_version.astype(int)
            _, newMoves = sort.heapsort(list(integer_version))

        if len(newMoves) > maxMoves:
            maxMoves = len(newMoves)
        moves.append(newMoves)

    currentMove = 0

    # 24 fps, and we want a 5 second gif 24 * 5 = 120 total frames (* 24 5)
    movie_image_step = maxMoves // 540
    movie_image_frame = 0

    os.makedirs(args, exist_ok=True)

    while currentMove < maxMoves:
        for i in range(img.shape[0]):
            if currentMove < len(moves[i]) - 1:
                swap_pixels(i, moves[i][currentMove])

        if currentMove % movie_image_step == 0:
            imsave('%s/%05d.png' % (args, movie_image_frame), color.convert_colorspace(img, 'HSV', 'RGB'))
            movie_image_frame += 1
        currentMove += 1
示例#9
0
def random_brightness(img):
    img = convert_colorspace(img, 'RGB', 'HSV')  # 0-255 uint8 -> 0-1 float64
    # img = np.array(img, dtype = np.float64)
    random_bright = 0.5 + np.random.uniform()
    img[:, :, 2] = img[:, :, 2] * random_bright
    img[:, :, 2][img[:, :, 2] > 1.0] = 1.0
    img = convert_colorspace(img, 'HSV', 'RGB')
    #img = np.array(img * 255., dtype=np.uint8)  # 0-1 float64 -> 0-255 uint8
    return img
示例#10
0
    def test_convert_colorspace(self):
        colspaces = ["HSV", "RGB CIE", "XYZ"]
        colfuncs_from = [hsv2rgb, rgbcie2rgb, xyz2rgb]
        colfuncs_to = [rgb2hsv, rgb2rgbcie, rgb2xyz]

        assert_almost_equal(convert_colorspace(self.colbars_array, "RGB", "RGB"), self.colbars_array)
        for i, space in enumerate(colspaces):
            gt = colfuncs_from[i](self.colbars_array)
            assert_almost_equal(convert_colorspace(self.colbars_array, space, "RGB"), gt)
            gt = colfuncs_to[i](self.colbars_array)
            assert_almost_equal(convert_colorspace(self.colbars_array, "RGB", space), gt)

        self.assertRaises(ValueError, convert_colorspace, self.colbars_array, "nokey", "XYZ")
        self.assertRaises(ValueError, convert_colorspace, self.colbars_array, "RGB", "nokey")
示例#11
0
def save_image(img, frame_num):
    print('{now}  ... saving frame {num}.png'.format(
        now=now(), num=str(frame_num).zfill(3)))
    saveimg = expand_image(img)  #If small, is expanded
    imsave('{dir}/{fn}.png'.format(dir=SORT_ALG, fn=str(frame_num).zfill(3)),
           color.convert_colorspace(saveimg, 'HSV', 'RGB'))
    return frame_num + 1
示例#12
0
def getBrightnessByChannelinColorSpace(s, params):
    prefix = params.get("prefix", None)
    prefix = prefix + "_" if prefix else ""

    logging.info(f"{s['filename']} - \tgetContrast:{prefix}")

    to_color_space = params.get("to_color_space", "RGB")
    limit_to_mask = strtobool(params.get("limit_to_mask", "True"))
    mask_name = params.get("mask_name", "img_mask_use")

    invert = strtobool(params.get("invert", "False"))

    img = s.getImgThumb(s["image_work_size"])

    suffix = ""
    if (to_color_space != "RGB"):
        img = convert_colorspace(img, "RGB", to_color_space)
        suffix = "_" + to_color_space

    for chan in range(0, 3):
        vals = img[:, :, chan]
        if (limit_to_mask):

            mask = s[mask_name] if not invert else ~s[mask_name]
            vals = vals[mask]

            if vals.size == 0:
                vals = np.array(-100)

        s.addToPrintList(f"{prefix}chan{chan+1}_brightness{suffix}",
                         str(vals.mean()))
        s.addToPrintList(f"{prefix}chan{chan+1}_brightness_std{suffix}",
                         str(vals.std()))

    return
示例#13
0
def extrairmagenta(img):
    """
    tentar extrair a magenta
    """
	
    bode = rgb2cmy(img)
    hsv = color.convert_colorspace(img, 'RGB', 'HSV')
    def _generate_tissue_mask_basic(wsi, level):
        """
        Generate a tissue mask.
        This is achieved by Otsu thresholding on the saturation channel \
        followed by morphological closing and opening to remove noise.

        :param wsi:
        :param level:
        :return:
        """
        if not hasattr(wsi, 'jp2'):
            low_res = wsi.read_region(location=(0, 0), level=level, size=wsi.level_dimensions[level]).convert('RGB') \
                # Read slide at low resolution and make sure it's RGB (not e.g. RGBA).
            low_res_numpy = np.asarray(low_res)  # Convert to numpy array.
        else:
            low_res_numpy = wsi.read_region(location=(0, 0), level=level, size=wsi.level_dimensions[level])
        low_res_numpy_hsv = color.convert_colorspace(low_res_numpy, 'RGB', 'HSV')  # Convert to Hue-Saturation-Value.
        saturation = low_res_numpy_hsv[:, :, 1]  # Get saturation channel.
        threshold = filters.threshold_otsu(saturation)  # Otsu threshold.
        mask = (saturation > threshold)  # Tissue is 'high saturation' region.

        # Morphological operations
        disk_radius = 10  # radius of disk for morphological operations.
        disk_object = disk(disk_radius)
        mask = closing(mask, disk_object)  # remove 'pepper'.
        mask = opening(mask, disk_object)  # remove 'salt'.
        assert mask.dtype == bool, 'Mask not Boolean'
        return mask
示例#15
0
	def _generate_tissue_mask(wsi, level):
        """
        To generate a tissue mask for the WSI.
        This is achieved by Otsu thresholding on the saturation channel, then to remove the noise
        morphological closing and opening operations are applied.

        :param wsi: openSlide object for the WSI
        :param level:the level to process the mask generation at
        :return: the generated mask
        """

        temp = wsi.read_region(location=(0, 0), level=level, size=wsi.level_dimensions[level])
        # Convert to Hue-Saturation-Value.
        hsv = color.convert_colorspace(temp, 'RGB', 'HSV')  
        # Get saturation channel.
        saturation = hsv[:, :, 1] 
        # Otsu threshold.
        threshold = filters.threshold_otsu(saturation)  
        # Tissue is 'high saturation' region.
        mask = (saturation > threshold)  

        # Morphological operations-----------------
        # radius of disk for morphological operations.
        disk_r = 10  
        disk_o = disk(disk_r)
        # remove pepper noise
        mask = closing(mask, disk_o)  
        # remove salt noise
        mask = opening(mask, disk_o)  
        return mask
示例#16
0
def sortBy(imageData, sortingParam):
    images = imageData.extract_highRes()
    #convert RGB images to HSV images
    paramImages = []
    if (sortingParam == 'hue' or sortingParam == 'val'
            or sortingParam == 'sat'):
        for image in images:
            hsv = sColor.convert_colorspace(image, 'RGB', 'HSV')
            if (sortingParam == 'hue'):
                imageHue = hsv[:, :, 0]
                val = np.ndarray.flatten(imageHue)
            if (sortingParam == 'sat'):
                imageSat = hsv[:, :, 1]
                val = np.ndarray.flatten(imageSat)
            if (sortingParam == 'val'):
                imageVal = hsv[:, :, 2]
                val = np.ndarray.flatten(imageVal)
            paramImages.append(val.mean())
    else:
        if (len(imageData.images_with_data(sortingParam)) != len(images)):
            raise ValueError(
                "The sorting parameter provided is not present for all the images"
            )
        paramImages = list(imageData.get_data_forall(sortingParam))

    #Sort the list of images by mean (ascending)
    sorted_indexes = np.argsort(paramImages)

    #Select the images from the sorted map and scale them from [0:255] to [0:1]
    rgbImages = []
    for idx in sorted_indexes:
        rgbImages.append(images[idx] / 255.0)

    return rgbImages
示例#17
0
    def test_image(self, input_image, color_space="YUV"):
        """
        Testing images using logistoic regression
        Args:
        ----
            self:pointer to current instance of the class
            input_image:input test image
        Kwargs:
        ------
            color_space: sets color space for use
            default_value:YUV
            data type:str

            confidence:set confidence of classification
            default_value:0.9
            data_type:float
        """
        mask = np.zeros(
            (input_image.shape[0], input_image.shape[1], self.num_classes))
        image = color.convert_colorspace(input_image, "RGB", color_space)[:, :,
                                                                          1]
        image = (image - np.min(image)) / (np.max(image) - np.min(image))
        image = exposure.adjust_gamma(image, gamma=0.5)
        for i in range(self.window_size // 2,
                       mask.shape[0] - (self.window_size // 2)):
            for j in range(self.window_size // 2,
                           mask.shape[1] - (self.window_size // 2)):
                window = image[i - (self.window_size // 2):i +
                               (self.window_size // 2),
                               j - (self.window_size // 2):j +
                               (self.window_size // 2)]
                mask[i, j, :] = self.sigmoid(window.reshape(1, -1), self.W,
                                             self.b)
        return mask
示例#18
0
def pre_process(path):
    img = sd.imread(path)
    img_hsv = sc.convert_colorspace(img, 'RGB', 'HSV')
    h = img_hsv.shape[0]
    w = img_hsv.shape[1]
    px = h * w

    return img_hsv, h, w, px
示例#19
0
 def NextGID(self,image):
     """ Calculates the next Group ID for the input image """
     NewImg = self.LoadImage(image,Greyscale=False,scale=0.25)
     NewImg_HSV = convert_colorspace(NewImg, 'RGB', 'HSV')
     NewColorVector = self.MeasureColorVector(NewImg_HSV,(8,12,3))  #8 bins for Hue, 12 for saturation and 3 for value
     for PreImgCVector in reversed(self.ImagesColorVectorList):
         # Calculate chi sqr distance 
         pass
示例#20
0
    def test_convert_colorspace(self, channel_axis):
        colspaces = ['HSV', 'RGB CIE', 'XYZ', 'YCbCr', 'YPbPr', 'YDbDr']
        colfuncs_from = [
            hsv2rgb, rgbcie2rgb, xyz2rgb, ycbcr2rgb, ypbpr2rgb, ydbdr2rgb
        ]
        colfuncs_to = [
            rgb2hsv, rgb2rgbcie, rgb2xyz, rgb2ycbcr, rgb2ypbpr, rgb2ydbdr
        ]

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

        kw = dict(channel_axis=channel_axis)

        assert_almost_equal(
            convert_colorspace(colbars_array, 'RGB', 'RGB', **kw),
            colbars_array)

        for i, space in enumerate(colspaces):
            gt = colfuncs_from[i](colbars_array, **kw)
            assert_almost_equal(
                convert_colorspace(colbars_array, space, 'RGB', **kw), gt)
            gt = colfuncs_to[i](colbars_array, **kw)
            assert_almost_equal(
                convert_colorspace(colbars_array, 'RGB', space, **kw), gt)

        with pytest.raises(ValueError):
            convert_colorspace(self.colbars_array, 'nokey', 'XYZ')
        with pytest.raises(ValueError):
            convert_colorspace(self.colbars_array, 'RGB', 'nokey')
示例#21
0
 def NextGID(self, image):
     """ Calculates the next Group ID for the input image """
     NewImg = self.LoadImage(image, Greyscale=False, scale=0.25)
     NewImg_HSV = convert_colorspace(NewImg, 'RGB', 'HSV')
     NewColorVector = self.MeasureColorVector(
         NewImg_HSV,
         (8, 12, 3))  #8 bins for Hue, 12 for saturation and 3 for value
     for PreImgCVector in reversed(self.ImagesColorVectorList):
         # Calculate chi sqr distance
         pass
示例#22
0
 def ColorSpaceChange(self, toSpace):
     self.temp = self.temp + 1
     img = self.img
     if self.fromspace == 'RGBA':
         img = color.rgba2rgb(self.img)
         self.fromspace = 'RGB'
     converted_image = color.convert_colorspace(img, self.fromspace,
                                                toSpace)  # having limits
     io.imsave(self.base_dir + 'temp' + str(self.temp) + '.' + self.format,
               converted_image)
     return 'static/Image/temp' + str(self.temp) + '.' + self.format
示例#23
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
示例#24
0
def _get_preprocessed_image(image_file):
    rgb_image = io.imread(image_file)
    shape = (rgb_image.shape[0], rgb_image.shape[1])
    if rgb_image.shape[2] == 4:
        # remove alpha channel
        rgb_image = img_as_float(rgb_image[:, :, 0:-1])
    elif rgb_image.shape[2] == 3:
        rgb_image = img_as_float(rgb_image)
    else:
        raise ValueError(
            "Images must have 3 or 4 channels (RGB or RGB+Alpha; Alpha is ignored)."
        )
    xyz_image = color.convert_colorspace(rgb_image, "rgb", "xyz")
    hsv_image = color.convert_colorspace(rgb_image, "rgb", "hsv")
    structure_image = img_as_float(
        filters.median(filters.scharr(color.rgb2gray(xyz_image)),
                       np.ones((7, 7))))
    image10d = np.dstack((rgb_image, xyz_image, hsv_image, structure_image))
    points10d = image10d.reshape(-1, 10)

    return (shape, rgb_image, points10d)
    def run(self):
        if len(self.images) == 0:
            raise FileNotFoundError("No training data found. Did you supply any?")

        segment_points10d = {}
        for m in self.images:
            segment_points10d[m] = []
            for rgb_image in self.images[m]:
                # ensure correct format and save alpha-channel
                rgb_image = img_as_float(rgb_image)
                if rgb_image.shape[2] == 4:
                    alpha = rgb_image[:,:,3]
                    rgb_image = rgb_image[:,:,0:3]
                elif rgb_image.shape[2] == 3:
                    alpha = np.ones(rgb_image.shape[0:2], dtype=float)
                else:
                    raise ValueError("Training images must have 3 or 4 channels (RGB or RGB+Alpha).")
                xyz_image = color.convert_colorspace(rgb_image, "rgb", "xyz")
                hsv_image = color.convert_colorspace(rgb_image, "rgb", "hsv")
                edges = filters.scharr(color.rgb2gray(xyz_image))
                structure_image = img_as_float(filters.median(edges, np.ones( (7,7) )))
                image11d = np.dstack((rgb_image, xyz_image, hsv_image, structure_image, alpha))
                points11d = image11d.reshape(-1,11)
                points10d = points11d[:,0:10]
                # filter non-opaque points:
                opaque_points11d = points11d[ 1. == points11d[:,10] ]
                opaque_points10d = opaque_points11d[:,0:10]
                segment_points10d[m].append(opaque_points10d)
            segment_points10d[m] = np.vstack(segment_points10d[m])
            print("Model '{}' has {} pixels.".format(m, segment_points10d[m].shape[0]))

        models = {}
        for segment in segment_points10d:
            models[segment] = GaussianMixture(1).fit(segment_points10d[segment])

        for m in models:
            filename = filenames.model_file(self.path, m)
            pickle.dump(models[m], open(filename, "wb"))
            print("Model '{}' saved as '{}'".format(m, filename))
    def _preprocess_(self, xi):
        '''
            Pre-process the sequence to state.
            We're using a deque, which inserts left to right. This pre-processes
            only the most recent image
        :return:
        '''

        xi = xi.squeeze()
        # Un-normalize
        xi = np.round((xi * 255.)).astype(np.uint8)
        x = convert_colorspace(xi, fromspace='rgb',
                               tospace='YCbCr')[..., 0]  # Get only the chroma
        self.sequence.append(x)
示例#27
0
def generate_background_mask(wsi, level):
    disk_radius = 10
    low_res = wsi.read_region(location=(0, 0), level=level, size=wsi.level_dimensions[level]).convert('RGB')
    low_res_numpy = np.asarray(low_res).copy()
    low_res_numpy_hsv = color.convert_colorspace(low_res_numpy, 'RGB', 'HSV')
    saturation = low_res_numpy_hsv[:, :, 1]
    theshold = filters.threshold_otsu(saturation)
    high_saturation = (saturation > theshold)
    disk_object = disk(disk_radius)
    mask = closing(high_saturation, disk_object)
    mask = opening(mask, disk_object)
    if mask.dtype != bool:
        raise Exception('\nBackground mask not boolean')
    return mask
示例#28
0
def detach_luminance(img):
    # Convert image from RGB color space to YCbCr color space
    #   input array must be dtype=np.uint8 nparray
    img_ycbcr = convert_colorspace(img, 'RGB', 'YCbCr')

    # Detach the luminance from Cb and Cr
    img_y = img_ycbcr[:, :, :, :1]
    img_cbcr = img_ycbcr[:, :, :, 1:]

    # Normalize the image
    #   Y is scales to a different range of 16 to 235
    img_y = (img_y - 16) / (235 - 16)
    #   CB and CR are scaled to a different range of 16 to 240.
    img_cbcr = (img_cbcr - 16) / (240 - 16)

    return img_y, img_cbcr
示例#29
0
 def process_frame(self, n, filename, frame):
     misc.imsave('{}_{}_{}_0.jpg'.format(filename, n, self.hash_type()),
                 frame)
     frame = resize(frame, (self.height, self.width), mode='constant')
     misc.imsave('{}_{}_{}_1.jpg'.format(filename, n, self.hash_type()),
                 frame)
     frame = gaussian(frame, sigma=3.0, multichannel=True)
     misc.imsave('{}_{}_{}_2.jpg'.format(filename, n, self.hash_type()),
                 frame)
     xyz = color.convert_colorspace(frame, 'YUV', 'XYZ')
     misc.imsave('{}_{}_{}_3.jpg'.format(filename, n, self.hash_type()),
                 xyz)
     lab = color.xyz2lab(xyz)
     misc.imsave('{}_{}_{}_4.jpg'.format(filename, n, self.hash_type()),
                 lab)
     return lab
示例#30
0
    def getchannel(img, colorspace, channel):
        """Function that returns a single channel from an image.
        ['RGB', ‘HSV’, ‘RGB CIE’, ‘XYZ’, ‘YUV’, ‘YIQ’, ‘YPbPr’, ‘YCbCr’, ‘YDbDr’]
        """

        if len(img.shape) == 2:
            c_img = img.copy()
            img = np.zeros([c_img.shape[0], c_img.shape[1], 3])
            img[:, :, 0] = c_img
            img[:, :, 1] = c_img
            img[:, :, 2] = c_img
            return [img, c_img, 1]

        if colorspace == 'RGB':
            return [img, img[:, :, channel], 3]
        space = color.convert_colorspace(img, 'RGB', colorspace)
        return [space, space[:, :, channel], 3]
示例#31
0
def getBrightnessByChannelinColorSpace(s, params):
    logging.info(f"{s['filename']} - \tgetContrast")
    limit_to_mask = strtobool(params.get("limit_to_mask", "True"))
    to_color_space = params.get("to_color_space", "RGB")
    img = s.getImgThumb(s["image_work_size"])

    suffix = ""
    if (to_color_space != "RGB"):
        img = convert_colorspace(img, "RGB", to_color_space)
        suffix = "_" + to_color_space

    for chan in range(0, 3):
        vals = img[:, :, chan]
        if (limit_to_mask):
            vals = vals[s["img_mask_use"]]
        s.addToPrintList(("chan%d_brightness" + suffix) % (chan + 1),
                         str(vals.mean()))

    return
示例#32
0
def to_movie(image, args):
    current_move = 0

    # 24 fps, and we want a 5 second gif 24 * 5 = 120 total frames (* 24 5)
    movie_image_step = max_moves // 120
    movie_image_frame = 0

    os.makedirs(args.sorter, exist_ok=True)

    while current_move < max_moves:
        for i in range(image.shape[0]):
            if current_move < len(moves[i]) - 1:
                swap_pixels(image, i, moves[i][current_move])

        if current_move % movie_image_step == 0:
            imwrite('%s/%05d.png' % (args.sorter, movie_image_frame),
                    color.convert_colorspace(image, 'HSV', 'RGB'))
            movie_image_frame += 1
        current_move += 1
示例#33
0
def find_m_values(image):
    """Determines the value of m which best fits a hyperbola to the histogram of color differences
    for each color parameter (hue, saturation, value)"""

    height = len(image)
    width = len(image[0])
    image_hsv = color.convert_colorspace(image, 'RGB', 'HSV')
    m_values = [0.0, 0.0, 0.0]
    x_list = range(20)
    y_lists = [[0] * 20, [0] * 20, [0] * 20]

    for row in range(height):
        for col in range(width):
            current_color = image_hsv[row][col]
            for neighbor in forward_pixel_neighbors([row, col], height, width):
                new_color = image_hsv[neighbor[0]][neighbor[1]]
                """Note that the difference in hues does not use the standard metric, since the space of hues is circular"""
                hue_diff = min(abs(current_color[0] - new_color[0]),
                               1 - abs(current_color[0] - new_color[0]))
                sat_diff = abs(current_color[1] - new_color[1])
                val_diff = abs(current_color[2] - new_color[2])
                x_hue = int(100 * hue_diff)
                x_sat = int(100 * sat_diff)
                x_val = int(100 * val_diff)
                if x_hue < 20:
                    y_lists[0][x_hue] += 1
                if x_sat < 20:
                    y_lists[1][x_sat] += 1
                if x_val < 20:
                    y_lists[2][x_val] += 1

    for parameter in range(3):
        y_list = y_lists[parameter]
        max_y_val = max(y_list)
        if max_y_val > 0.0:
            for index in range(len(y_list)):
                y_lists[parameter][index] = float(
                    y_lists[parameter][index]) / float(max_y_val)
        m = fit_hyperbola(x_list, y_list, 0.1)
        m_values[parameter] = m

    return m_values
def pen_marks(img: PIL.Image.Image) -> np.ndarray:
    """Filter out pen marks from a diagnostic slide.

    Pen marks are removed by applying Otsu threshold on the H channel of the image
    converted to the HSV space.

    Parameters
    ---------
    img : PIL.Image.Image
        Input RGB image

    Returns
    -------
    np.ndarray
        Boolean NumPy array representing the mask with the pen marks filtered out.
    """
    np_img = np.array(img)
    np_hsv = sk_color.convert_colorspace(np_img, "RGB", "HSV")
    hue = np_hsv[:, :, 0]
    threshold = sk_filters.threshold_otsu(hue)
    return threshold_to_mask(hue, threshold, operator.gt)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances_argmin
from sklearn.utils import shuffle
from time import time
from skimage import io
from skimage import color

n_colors = 1

inImage = io.imread("/Users/zal/Desktop/bounty.png")
inImage = np.array(inImage, dtype=np.float64) / 255
plt.imshow(inImage)

# Convert to floats instead of the default 8 bits integer coding. Dividing by
# 255 is important so that plt.imshow behaves works well on float data (need to
# be in the range [0-1]
hsvImage = color.convert_colorspace(inImage, 'RGB', 'HSV')

inImage = np.array(hsvImage, dtype=np.float64) / 255
plt.figure(1)
plt.imshow(inImage)
示例#36
0
from helpers import show_image, save_image

# Load image
lena = imread("../lena.jpg")

# Draw and display an image
plt.imshow(lena)
plt.show()

# Matrix indices are [rows, columns]
# Extract the rows 100 to 200 & all columns
sub_lena = lena[100:200 , 0:-1]
show_image(sub_lena)

# Accessing color channels: third index -> [rows, cols, channel]
red_lena = lena[:,:,0]
show_image(red_lena, cmap="gray")

# Convert to grayscale and use different colormap
gray_lena = rgb2gray(lena)
show_image(gray_lena, colormap="inferno")

# Convert to other colorspace
hsv_lena = convert_colorspace(lena, "RGB", "HSV")

# Only show saturation
sat_lena = hsv_lena[:,:,1]
show_image(sat_lena, "gray")

# Save image
save_image(sat_lena, "sat_lena.jpg", "gray")
示例#37
0
文件: image.py 项目: zshipko/imagepy
 def convert_colorspace(self, fromspace, tospace):
     return Image(convert_colorspace(self, fromspace, tospace)).convert_type(self.dtype)
示例#38
0
	def convert_color(self, from_cp, to_cp):
		self.current_image = convert_colorspace(self.current_image, from_cp, to_cp)
		return self.current_image
    #Removing axis
    ax0.axis("off")
    ax1.axis("off")
    ax2.axis("off")

    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, )
"""