Exemple #1
0
def process_images(data_dir, data_labels, size, extension, process=None):

    data = []

    print('Processing data...')

    for f, tags in tqdm(data_labels.values):
        fpath = os.path.join(data_dir, '{}.{}'.format(f, extension))

        img = io.imread(fpath)
        if process == 'RGB':
            img = get_rgb(img, [2, 1, 0])  # RGB from TIF
            img = np.array(img * 128 + 128, dtype=np.uint8)
        elif process == 'NDWI':
            img_layer = get_rgb(img, [3, 2, 1])  # NIR-R-G
            img = (img_layer[:, :, 2] - img_layer[:, :, 0]) / (
                img_layer[:, :, 2] + img_layer[:, :, 0])
            img = np.array(img * 128 + 128, dtype=np.uint8)
        elif process == 'NDVI':
            max_value = 0.7210752894  # evaluated on whole dataset
            min_value = -0.71597245876  # evaluated on whole dataset
            img = ndvi(img, 2, 3)
            img = np.array((img - min_value) * 256 / (max_value - min_value),
                           dtype=np.uint8)
        data.append(cv2.resize(img, (size, size)))

    print('Done')

    return data
Exemple #2
0
    def train_test_images(self, train_positions, test_positions):
        img_train, img_test = np.zeros(
            shape=(self.height, self.width)), np.zeros(shape=(self.height,
                                                              self.width))

        for (i, j) in train_positions:
            label = self.complete_gt[i, j]
            img_train[i, j] = label

        for (i, j) in test_positions:
            label = self.complete_gt[i, j]
            img_test[i, j] = label

        return get_rgb(img_train, color_scale=self.color_scale), get_rgb(
            img_test, color_scale=self.color_scale)
def tif_to_rgb(img, as_int=True):
    #  [2, 1, 0] index is needed because colours are stored as bgr (wavelength order)
    img_rgb = get_rgb(img, [2, 1, 0])
    # scale between 0 and 255 and convert to type uint8
    if as_int:
        img_rgb = (img_rgb * 255).astype('uint8')
    return img_rgb
Exemple #4
0
def display_dataset(img, gt, bands, labels, palette):
    """Display the specified dataset.

    Args:
        img: 3D hyperspectral image
        gt: 2D array labels
        bands: tuple of RGB bands to select
        labels: list of label class names
        palette: dict of colors
        display (optional): type of display, if any

    """
    print("Image has dimensions {}x{} and {} channels".format(*img.shape))
    rgb = spectral.get_rgb(img, bands)
    rgb /= np.max(rgb)
    rgb = np.asarray(255 * rgb, dtype='uint8')

    # Display the RGB composite image
    caption = "RGB (bands {}, {}, {})".format(*bands)
    # send to visdom server
    plt.figure()    
#    plt.imshow(stddev_stretch(rgb))
    plt.imshow(rgb)
    plt.xticks(np.array([]))
    plt.yticks(np.array([]))
    plt.title(caption)
Exemple #5
0
def show_tiff_image_data(bgrn_image):
	"""Show a rendering of scaled RGB of BGRN 4 channel image matrix"""
	tif_rgb = get_rgb(bgrn_image, [2, 1, 0]) # RGB
	# rescaling to 0-255 range - uint8 for display
	rescaleIMG = np.reshape(tif_rgb, (-1, 1))
	scaler = MinMaxScaler(feature_range=(0, 255))
	rescaleIMG = scaler.fit_transform(rescaleIMG)
	img_scaled = (np.reshape(rescaleIMG, tif_rgb.shape)).astype(np.uint8)
	new_style = {'grid': False}
	plt.imshow(img_scaled)
	plt.title('RGB')
	plt.colorbar()
Exemple #6
0
def preprocess_image1(img, target_size):
    if target_size:
        img = resize(img, (img.shape[0], target_size[1], target_size[2]),
                     order=1)
    img_rgb = get_rgb(img.transpose(1, 2, 0), [2, 1, 0])  # R-G-B
    rescaleimg = np.reshape(img_rgb, (-1, 1))
    scaler = MinMaxScaler(feature_range=(0, 255))
    rescaleimg = scaler.fit_transform(rescaleimg)  # .astype(np.float32)
    img_scaled = (np.reshape(rescaleimg, img_rgb.shape)) / 255.0
    img_scaled = img_scaled.transpose(2, 0, 1)
    img_nir = get_rgb(img.transpose(1, 2, 0), [3, 2, 1])  # NIR-R-G
    img_nir_red = (img_nir[:, :, 0] - img_nir[:, :, 1]) / (
        img_nir[:, :, 0] + img_nir[:, :, 1] + np.finfo(float).eps
    )  # (NIR - RED) / (NIR + RED)
    img_nir_red = np.expand_dims(np.clip(img_nir_red, -1, 1), axis=0)
    img_nir_green = (img_nir[:, :, 2] - img_nir[:, :, 0]) / (
        img_nir[:, :, 2] + img_nir[:, :, 0] + np.finfo(float).eps
    )  # (GREEN - NIR) / (GREEN + NIR)
    img_nir_green = np.expand_dims(np.clip(img_nir_green, -1, 1), axis=0)

    return np.concatenate((img_scaled, img_nir_red, img_nir_green), axis=0)
Exemple #7
0
    def set_data(self, data, bands=None, **kwargs):
        '''Sets the data to be shown in the RGB channels.
        
        Arguments:

            `data` (ndarray or SpyImage):

                If `data` has more than 3 bands, the `bands` argument can be
                used to specify which 3 bands to display. `data` will be
                passed to `get_rgb` prior to display.

            `bands` (3-tuple of int):

                Indices of the 3 bands to display from `data`.

        Keyword Arguments:

            Any valid keyword for `get_rgb` or `matplotlib.imshow` can be
            given.
        '''
        import spectral as spy
        rgb_kwargs = {}
        for k in ('stretch', 'stretch_all', 'bounds'):
            if k in kwargs:
                rgb_kwargs[k] = kwargs.pop(k)

        # If it is a gray-scale image, only keep the first RGB component so
        # matplotlib imshow's cmap can still be used.
        self.data = spy.get_rgb(data, bands, **rgb_kwargs)
        if len(data.shape) == 2 or (bands is not None and len(bands) == 1):
            self.data = self.data[:, :, 0]

        if self._image_shape is None:
            self._image_shape = data.shape[:2]
        elif data.shape[:2] != self._image_shape:
            raise ValueError('Image shape is inconsistent with previously ' \
                             'set data.')
        self.imshow_data_kwargs.update(kwargs)
        if 'interpolation' in self.imshow_data_kwargs:
            self.interpolation = self.imshow_data_kwargs['interpolation']
            self.imshow_data_kwargs.pop('interpolation')

        if len(kwargs) > 0 and self.is_shown:
            msg = 'Keyword args to set_data only have an effect if ' \
              'given before the image is shown.'
            warnings.warn(UserWarning(msg))
        if self.is_shown:
            self.refresh()
Exemple #8
0
def convert_tif_pkl(tif_folder='..' + paths.DATA_FOLDER + '/train-tif-sample',
                    jpg_folder='..' + paths.DATA_FOLDER + '/train-jpg-sample'):
    img = np.zeros((256, 256, 3))
    scaler = MinMaxScaler(feature_range=(0, 255))
    for f in tqdm(os.listdir(tif_folder)):
        tif_img = sio.imread(tif_folder + '/' + f)
        fil_no = os.path.splitext(f)[0]
        jpg_img = sio.imread(jpg_folder + '/' + fil_no + '.jpg')
        img2 = get_rgb(tif_img, [2, 1, 0])
        rescaleIMG = np.reshape(img2, (-1, 1))
        rescaleIMG = scaler.fit_transform(rescaleIMG)
        img2 = (np.reshape(rescaleIMG, img2.shape)).astype(np.uint8)
        img = img2
    print img
    plt.imshow(img)
    plt.show(img)
Exemple #9
0
    def loadImg(self, filePath: str):
        if self.imgItem is not None:
            self.graphicsView.scene().removeItem(self.imgItem)
            self.resultLabel.clear()
            self.resultLabel.setText("Click on img")
        self.prevPoint = None
        file: BilFile = open_image(filePath)
        rgb = get_rgb(file)
        rgb = rgb * 255
        rgb = rgb.astype(np.uint8)
        loadedImg = QImage(rgb.tobytes(), rgb.shape[0], rgb.shape[1],
                           rgb.shape[0] * 3, QImage.Format_RGB888)

        self.hyperspectralImg = HyperspectralImgModel(file, loadedImg)
        self.__raiseOnImgLoaded(self.hyperspectralImg)

        p = QPixmap.fromImage(loadedImg, Qt.AutoColor)
        self.imgItem: QGraphicsPixmapItem = self.graphicsView.scene(
        ).addPixmap(p)
        self.scaleImg(self.zoomSlider.value())
Exemple #10
0
def display_dataset(img, gt, bands, labels, palette, vis):
    """Display the specified dataset.

    Args:
        img: 3D hyperspectral image
        gt: 2D array labels
        bands: tuple of RGB bands to select
        labels: list of label class names
        palette: dict of colors
        display (optional): type of display, if any

    """
    print("Image has dimensions {}x{} and {} channels".format(*img.shape))
    rgb = spectral.get_rgb(img, bands)
    rgb /= np.max(rgb)
    rgb = np.asarray(255 * rgb, dtype='uint8')

    # Display the RGB composite image
    caption = "RGB (bands {}, {}, {})".format(*bands)
    # send to visdom server
    vis.images([np.transpose(rgb, (2, 0, 1))], opts={'caption': caption})
Exemple #11
0
    def disconnect(self):
        self.lasso.disconnect_events()
        self.fc[:, -1] = 1
        self.collection.set_facecolors(self.fc)
        self.canvas.draw_idle()


if __name__ == '__main__':
    PROJ_DIR = os.getcwd()
    SAMPLES_DIR = os.path.join(PROJ_DIR, 'samples')
    sample = SAMPLES_DIR + '\\HARC000.bil.hdr'

    s = open_image(sample)  #.load()
    bands = (70, 70, 30)
    rgb = get_rgb(s, bands)

    fig, ax = plt.subplots()
    im = ax.imshow(rgb)
    a = s.asarray()
    pts = ax.scatter(a[:, 0], a[:, 1], s=80)

    print('Offsets: ', pts.get_offsets())
    selector = SelectFromImage(ax, pts)
    plt.draw()

    def accept(event):
        if event.key == "enter":
            print("Selected points:")
            print(selector.xys[selector.ind])
            selector.disconnect()
Exemple #12
0
def output_image(input, output):
    return get_rgb(output, color_scale=input.color_scale)
Exemple #13
0
def rgb(img, bands=None):
    """Returns the RGB image from the selected bands (R, G, B)"""
    return spectral.get_rgb(img, bands=bands)
def compute_ndwi(bgrn_image):
    nrg = get_rgb(bgrn_image, [3, 2, 1]) # NIR-R-G
    ndwi = (nrg[:, :, 2] - nrg[:, :, 0]) / \
        (nrg[:, :, 2] + nrg[:, :, 0]).astype(np.float64)
    return ndwi
Exemple #15
0
def rgb(img, bands=None):
    """Returns the RGB image from the selected bands (R, G, B)"""
    from spectral import get_rgb
    return get_rgb(img, bands=bands)
Exemple #16
0
from matplotlib.path import Path

from spectral import open_image, imshow, get_rgb
import matplotlib.pyplot as plt
import matplotlib.image as img
import matplotlib.cm as cm
from spectral import *

PROJ_DIR = os.getcwd()
SAMPLES_DIR = os.path.join(PROJ_DIR, 'samples')
sample = 'D:\\Hypercubes\\HARC000.bil.hdr'

image = open_image(sample)  #.load()
bands = (70, 70, 30)
fig, ax = plt.subplots()
rgb = get_rgb(image, bands)
im = ax.imshow(rgb)
plt.draw()
plt.show()
pdb.set_trace()
print(image)
x = input()

# im = imshow(s.load(), bands)

# data = s.read_bands(bands)
# im = imshow(s.load(), bands)

# plt.show()

# plt.imshow(s.read_band(0))
    def __call__(self, sample):
        image = sample['image']

        image = get_rgb(image, bands=[55, 41, 12])

        return {'image': image, 'annotation': sample['annotation'].copy()}