Ejemplo n.º 1
0
def main():
    """The script's main entry point."""
    args = handle_args()
    with (open(args.data_file, 'rt')
          if args.data_file not in (None, '-') else sys.stdin) as data_file:
        data_reader = CSVDictReader(data_file, quoting=QUOTE_NONNUMERIC)
        try:
            data = HeatmapDataSet((HeatmapPoint(round(row[args.x_column]),
                                                round(row[args.y_column]),
                                                round(row[args.value_column]))
                                   for row in data_reader),
                                  min_value=args.min_value,
                                  max_value=args.max_value)
        except KeyError as err:
            print('Requested header "{}" was not found in input data. Try '
                  'specifying -x/-y/-c.'.format(*err.args),
                  file=sys.stderr)
            return 1
    colormap = (DefaultColorMap() if args.color_map is None else
                AbsoluteColorMap(args.color_map))
    writer = PNGWriter(width=data.bounds.width,
                       height=data.bounds.height,
                       alpha=True)
    with (open(args.output_file, 'wb')
          if args.output_file is not None else sys.stdout.buffer) as outfile:
        writer.write(outfile, colormap.color_heatmap(data))
Ejemplo n.º 2
0
def tig(width: int, height: int) -> bytes:
    with BytesIO() as image:
        palette = [(0xFF, 0xFF, 0xFF, 0x00)]
        writer = Writer(width, height, palette=palette, bitdepth=1, compression=9)
        writer.write(image, [[0 for _ in range(width)] for _ in range(height)])
        image.seek(0)
        return image.read()
    def write( self ):
        slope       = ( 1.0 * self.height ) / self.width
        pixels      = numpy.zeros( ( self.height, self.width ), dtype=int )

        #
        # Something similar to http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm
        # but special cased, since I know the lines are mirrored thrice.
        #
        actualY = 0
        for leftX in range( 0, ( self.width / 2 ) + 1 ):
            # Precalculating.  Math!
            frac        = actualY - int( actualY ) 
            topColor    = self.getColor( 1 - frac )
            bottomColor = self.getColor( frac )
            topY        = int( actualY )
            bottomY     = self.height - topY - 1
            rightX      = self.width - leftX - 1

            # Actual Line (top-left)
            pixels[ topY,       leftX ]   = topColor
            pixels[ topY + 1,   leftX ]   = bottomColor

            # Horizontal Flip (top-right)
            pixels[ topY,       rightX ]  = topColor
            pixels[ topY + 1,   rightX ]  = bottomColor

            # Vertical Flip (bottom-left)
            pixels[ bottomY,     leftX ]  = topColor
            pixels[ bottomY - 1, leftX ]  = bottomColor

            # 180-degree Rotation
            pixels[ bottomY,     rightX ] = topColor
            pixels[ bottomY - 1, rightX ] = bottomColor
            
            # Increment `actualY`
            actualY += slope
            
            # Worry about the border (avoids another loop)
            if self.border:
                pixels[ 0,                leftX  ] = Placeholder.BACKGROUND
                pixels[ self.height - 1,  leftX  ] = Placeholder.BACKGROUND
                pixels[ 0,                rightX ] = Placeholder.BACKGROUND
                pixels[ self.height - 1,  rightX ] = Placeholder.BACKGROUND
                if leftX > 1:
                    pixels[ 1,                leftX  ] = Placeholder.FOREGROUND
                    pixels[ self.height - 2,  leftX  ] = Placeholder.FOREGROUND
                    pixels[ 1,                rightX ] = Placeholder.FOREGROUND
                    pixels[ self.height - 2,  rightX ] = Placeholder.FOREGROUND
                if leftX == 1:
                    for y in range( 1, self.height - 1 ):
                        pixels[ y,  leftX  ] = Placeholder.FOREGROUND
                        pixels[ y,  rightX ] = Placeholder.FOREGROUND

        if self.metadata: 
            self.addMetadata( pixels )

        with open( self.out, 'wb' ) as f:
            w = Writer( self.width, self.height, background=self.colors[0], palette=self.colors, bitdepth=8 )
            w.write( f, pixels )
def draw_map(width, height, map, filename, pixel_function):
    """
    Generic function to draw maps with PyPNG
    """
    writer = Writer(width, height)
    pixels = [reduce(lambda x, y: x + y, [pixel_function(elev) for elev in row]) for row in map]
    with open(filename, 'w') as f:
        writer.write(f, pixels)
Ejemplo n.º 5
0
def draw(name, diagram, column_variables, row_variables):
    rows = list(
        get_rows(diagram, column_variables, row_variables, transform=int))
    writer = Writer(width=screen_width,
                    height=screen_height,
                    greyscale=isinstance(diagram, Diagram))
    with open("visual/{}.png".format(name), "w") as outfile:
        writer.write(outfile, rows)
Ejemplo n.º 6
0
 def generate_captcha_response(self, request, uri, headers):
     ''' Generate a PNG image and return it as captcha mock
     '''
     f = BytesIO()
     w = Writer(206, 40)
     pngdata = [[random.randint(0,255) for i in range(206*w.planes)] for i in range(40)]
     w.write(f, pngdata)
     headers['Content-Type'] = 'image/png'
     return (200, headers, f.getvalue())
Ejemplo n.º 7
0
 def generate_captcha_response(self, request, uri, headers):
     ''' Generate a PNG image and return it as captcha mock
     '''
     f = BytesIO()
     w = Writer(206, 40)
     pngdata = [[random.randint(0, 255) for i in range(206 * w.planes)]
                for i in range(40)]
     w.write(f, pngdata)
     headers['Content-Type'] = 'image/png'
     return (200, headers, f.getvalue())
Ejemplo n.º 8
0
    def _save(self, filename):
        if type(filename) is not str:
            raise ValueError("file name must be a string")

        with open(filename, 'wb') as f:
            rows, cols = len(self.image_data), len(self.image_data[0])
            writer = Writer(cols, rows)

            pixels = _unbox(self.image_data)
            writer.write(f, pixels)

        print(filename, "saved.")
Ejemplo n.º 9
0
    def _save(self, filename):
        if type(filename) is not str:
            raise ValueError("file name must be a string")

        with open(filename, 'wb') as f:
            rows, cols = len(self.image_data), len(self.image_data[0])
            writer = Writer(cols, rows)

            pixels = _unbox(self.image_data)
            writer.write(f, pixels)

        print(filename, "saved.")
Ejemplo n.º 10
0
def imwrite(path, img, dtype=None, cmap=None, **kwargs):
    '''
    accepted file types are...
        for 8 and 16 bit grayscale and RGB images:
            Windows bitmaps - *.bmp, *.dib
            JPEG files - *.jpeg, *.jpg, *.jpe
            JPEG 2000 files - *.jp2
            Portable Network Graphics - *.png
            WebP - *.webp
            Portable image format - *.pbm, *.pgm, *.ppm
            Sun rasters - *.sr, *.ras 
            TIFF files - *.tiff, *.tif
        for binary (bool) masks:
            *.png
        for 32 bit float images:
            *.tiff
    dtype = (None, float,bool)
            all other dtypes are converted to either uint8 or uint16
    cmap = display grayscale as rgb using colormap: 'flame', 'gnuplot2' etc.
    '''
    if dtype in (float, np.float64, np.float32):
        assert path.endswith('.tiff') or path.endswith(
            '.tif'), 'float arrays can only be saved as TIFF/TIF images'
        from PIL import Image
        Image.fromarray(np.asfarray(img)).save(path)
        # ... PIL is about 3x faster than tifffile.imwrite
    elif dtype in (bool, np.bool):
        # this method at about 10x slower than cv2.imwrite
        # however, it generates 8x smaller images (1bit vs 8bit)
        assert path.endswith(
            '.png'), 'boolean masks can only be saved as PNG images'
        assert img.ndim == 2, 'can only save grayscale images as type(bool)'
        from png import Writer
        with open(path, 'wb') as f:
            s0, s1 = img.shape
            w = Writer(s1, s0, greyscale=True, bitdepth=1)
            if not img.dtype == np.uint16:
                img = img.astype(np.uint8)
            w.write(f, img)
    else:
        img = toUIntArray(img, dtype=dtype, **kwargs)
        if cmap is not None:
            assert img.ndim == 2, '<cmap> can only be used for grayscale images'
            img = applyColorMap(img, cmap)
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        return cv2.imwrite(path, img)
def draw_color_map_with_shadow(width, height, map, filename):

    ELEV_MIN = -1.0
    ELEV_MOUNTAIN = 1.0

    SHADOW_RADIUS = 4

    COAST_COLOR = (203, 237, 128)
    HILL_COLOR = (65, 69, 28)
    MOUNTAIN_COLOR = (226, 227, 218)
    SHALLOW_SEA_COLOR = (128, 237, 235)
    DEEP_SEA_COLOR = (2, 69, 92)

    def shadow_color(color, x, y):
        alt = map[y][x]
        delta = 0
        for dist in range(SHADOW_RADIUS):
            # To avoid picking unexisting cells
            if x > dist and y > dist:
                other = map[y-1-dist][x-1-dist]
                diff = other-alt
                if other > ELEV_SEA and other>alt:
                    delta += diff/(1.0+dist)
        delta = min(0.2, delta)
        return gradient(delta, 0, 0.2, color, (0, 0, 0))


    def elev_to_pixel(elev):
        if elev > ELEV_HILL:
            return gradient(elev, ELEV_HILL, ELEV_MOUNTAIN, HILL_COLOR, MOUNTAIN_COLOR)
        elif elev > ELEV_SEA:
            return gradient(elev, ELEV_SEA, ELEV_HILL, COAST_COLOR, HILL_COLOR)
        else:
            return gradient(elev, ELEV_MIN, ELEV_SEA, DEEP_SEA_COLOR, SHALLOW_SEA_COLOR)

    writer = Writer(width, height)

    colors = [[elev_to_pixel(elev) for elev in row] for row in map]
    for y in range(height):
        for x in range(width):
            colors[y][x] = shadow_color(colors[y][x], x, y)
    pixels = [reduce(lambda x, y: x+y, row) for row in colors]
    with open(filename, 'w') as f:
        writer.write(f, pixels)
Ejemplo n.º 12
0
	destWriter = Writer(size[0] * DEST_ROWS, size[1] * DEST_COLS, alpha='RGBA', bitdepth=8)
	print('ok, width %d, height %d.' % (size[0] * DEST_ROWS, size[1] * DEST_COLS))

	src_images = []
	print("\n\t\tReading empty image data..."),
	src_images.append([data for data in Reader(EMPTY_FILE).asDirect()[2]])
	print('ok')
	for num in range(1, IMAGE_NUM+1):
		print('\t\tReading image data "%s"...' % getSrcFileName(num)),
		src_images.append([data for data in Reader(getSrcFileName(num)).asDirect()[2]])
		print('ok')

	ret_image = []
	getImage = (lambda x : src_images[(lambda : 0 if x > IMAGE_NUM else x)()])
	print('')
	for row in range(1, DEST_COLS * DEST_ROWS, DEST_ROWS):
		print("\t\tGenerating row %d..." % ((row-1) / DEST_ROWS + 1)),
		image_first = getImage(row)
		for col in range(0, size[0]):
			data = image_first[col]
			for col_image in range(row+1, row + DEST_ROWS):
				data = concatenate((data, getImage(col_image)[col]))
			ret_image.append(data)
		print('ok')

	print("\n\tOpening %s..." % DEST_NAME),
	DEST = open(DEST_NAME, 'wb')
	print('ok'); print("\tWriting file..."),
	destWriter.write(DEST, ret_image)
	print('ok')
Ejemplo n.º 13
0
    def write(self):
        slope = (1.0 * self.height) / self.width
        pixels = numpy.zeros((self.height, self.width), dtype=int)

        #
        # Something similar to http://en.wikipedia.org/wiki/Xiaolin_Wu's_line_algorithm
        # but special cased, since I know the lines are mirrored thrice.
        #
        actualY = 0
        for leftX in range(0, (self.width / 2) + 1):
            # Precalculating.  Math!
            frac = actualY - int(actualY)
            topColor = self.getColor(1 - frac)
            bottomColor = self.getColor(frac)
            topY = int(actualY)
            bottomY = self.height - topY - 1
            rightX = self.width - leftX - 1

            # Actual Line (top-left)
            pixels[topY, leftX] = topColor
            pixels[topY + 1, leftX] = bottomColor

            # Horizontal Flip (top-right)
            pixels[topY, rightX] = topColor
            pixels[topY + 1, rightX] = bottomColor

            # Vertical Flip (bottom-left)
            pixels[bottomY, leftX] = topColor
            pixels[bottomY - 1, leftX] = bottomColor

            # 180-degree Rotation
            pixels[bottomY, rightX] = topColor
            pixels[bottomY - 1, rightX] = bottomColor

            # Increment `actualY`
            actualY += slope

            # Worry about the border (avoids another loop)
            if self.border:
                pixels[0, leftX] = Placeholder.BACKGROUND
                pixels[self.height - 1, leftX] = Placeholder.BACKGROUND
                pixels[0, rightX] = Placeholder.BACKGROUND
                pixels[self.height - 1, rightX] = Placeholder.BACKGROUND
                if leftX > 1:
                    pixels[1, leftX] = Placeholder.FOREGROUND
                    pixels[self.height - 2, leftX] = Placeholder.FOREGROUND
                    pixels[1, rightX] = Placeholder.FOREGROUND
                    pixels[self.height - 2, rightX] = Placeholder.FOREGROUND
                if leftX == 1:
                    for y in range(1, self.height - 1):
                        pixels[y, leftX] = Placeholder.FOREGROUND
                        pixels[y, rightX] = Placeholder.FOREGROUND

        if self.metadata:
            self.addMetadata(pixels)

        with open(self.out, 'wb') as f:
            w = Writer(self.width,
                       self.height,
                       background=self.colors[0],
                       palette=self.colors,
                       bitdepth=8)
            w.write(f, pixels)
Ejemplo n.º 14
0
                t = t + 1
            self.result[pixelline] = decoded


workQueue = Queue.Queue(10)
encoder = Encoder(workQueue, pixels)
decoderResult = [None] * height

decoders = [None] * NDECODERS
for i in xrange(NDECODERS):
    decoders[i] = Decoder(workQueue, decoderResult)

print 'Decoding using %d decoders' % (len(decoders))

encoder.start()
for decoder in decoders:
    decoder.start()

encoder.join()

print 'Encoding terminated, waiting for the decoders to finish'

for decoder in decoders:
    decoder.join()

print 'Decoding terminated'

coded_writer.write(coded, encoder.result)
decoded_writer.write(decodedf, decoderResult)
  
Ejemplo n.º 15
0
def ico2png(data):
    """Convert the bytestring data of an ICO file to PNG-format data as a bytestring."""
    # try to extract the 6-byte ICO header
    try:
        header = unpack('<3H', data[0:6])
    except:
        raise TypeError  # data is not an ICO
    if header[:2] != (0, 1):
        raise TypeError  # data is not an ICO

    # the number of images in the file is header[2]
    image_count = header[2]

    # collect the icon directories
    directories = []
    for i in xrange(image_count):
        directory = list(unpack('<4B2H2I', data[6 + 16 * i:6 + 16 * i + 16]))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256
        directories.append(directory)

    # select "best" icon (??)
    directory = max(directories, key=(lambda x: x[0:3]))

    # get data of that image
    width = directory[0]
    height = directory[1]
    offset = directory[7]
    result = {
        'width': width,
        'height': height,
        'colors': directory[2],
        'bytes': directory[6],
        'offset': offset,
    }
    if data[offset:offset + 16] == "\211PNG\r\n\032\n":
        # looks like a PNG, so return the data from here out.
        return data[offset:]
    else:
        dib_size = unpack('<I', data[offset:offset + 4])[0]
        if dib_size != 40:
            raise TypeError  # don't know how to handle an ICO where the DIB isn't 40 bytes
        else:
            dib = unpack('<L2l2H2L2l2L', data[offset:offset + dib_size])
            bits_per_pixel = dib[4]
            bmp_data_bytes = dib[6]
            if bmp_data_bytes == 0:
                bmp_data_bytes = width * height * bits_per_pixel / 8
            if bits_per_pixel <= 8:
                # assemble the color palette
                color_count = 2**bits_per_pixel
                raw_colors = [
                    unpack(
                        'BBBB', data[offset + dib_size + 4 * i:offset +
                                     dib_size + 4 * i + 4])
                    for i in xrange(0, color_count)
                ]
                # the RGBQUAD for each palette color is (blue, green, red, reserved)
                palette = [
                    tuple([color[x] for x in (2, 1, 0)])
                    for color in raw_colors
                ]

                # get the XorMap bits
                xor_data_bits = [
                    bit for byte in data[offset + dib_size +
                                         color_count * 4:offset + dib_size +
                                         color_count * 4 + bmp_data_bytes]
                    for bit in _bitlist(unpack('B', byte)[0])
                ]
                # get the AndMap bits
                and_row_size = ((width + 31) >> 5) << 2
                and_data_bits = [
                    bit for byte in data[offset + dib_size + color_count * 4 +
                                         bmp_data_bytes:offset + dib_size +
                                         color_count * 4 + bmp_data_bytes +
                                         and_row_size * height]
                    for bit in _bitlist(unpack('B', byte)[0])
                ]

                # assemble the combined image (with transparency)
                def get_pixel(x, y):
                    if and_data_bits[(height - y - 1) * and_row_size * 8 +
                                     x] == 1:
                        # transparent
                        return (0, 0, 0, 0)
                    else:
                        # use the xor value, made solid
                        return palette[_bitlistvalue(
                            xor_data_bits[bits_per_pixel * (
                                (height - y - 1) * width + x):bits_per_pixel *
                                          ((height - y - 1) * width + x) +
                                          bits_per_pixel])] + (255, )

                pixels = [[
                    c for x in xrange(result['width'])
                    for c in get_pixel(x, y)
                ] for y in xrange(result['height'])]
            elif bits_per_pixel == 32:
                raw_pixels = [[
                    unpack(
                        'BBBB',
                        data[offset + dib_size + 4 * (y * width + x):offset +
                             dib_size + 4 * (y * width + x) + 4])
                    for x in xrange(width)
                ] for y in xrange(height - 1, -1, -1)]
                pixels = [[
                    c for px in row for c in (px[2], px[1], px[0], px[3])
                ] for row in raw_pixels]
            elif bits_per_pixel == 24:
                raw_pixels = [[
                    unpack(
                        'BBB',
                        data[offset + dib_size + 3 * (y * width + x):offset +
                             dib_size + 3 * (y * width + x) + 3])
                    for x in xrange(width)
                ] for y in xrange(height - 1, -1, -1)]
                pixels = [[
                    c for px in row for c in (px[2], px[1], px[0], 255)
                ] for row in raw_pixels]
            else:
                raise TypeError  # don't know how to handle the pixel depth value

    out = StringIO()
    w = PNGWriter(result['width'], result['height'], alpha=True)
    w.write(out, pixels)
    return out.getvalue()
Ejemplo n.º 16
0
def compress_image(img,w,h,f):
	from png import Writer
	w = Writer(w, h, greyscale = False)
	w.write(f,img)
Ejemplo n.º 17
0
def draw(name, diagram, column_variables, row_variables):
    rows = list(get_rows(diagram, column_variables, row_variables, transform=int))
    writer = Writer(width=screen_width, height=screen_height, greyscale=isinstance(diagram, Diagram))
    with open("visual/{}.png".format(name), "w") as outfile:
        writer.write(outfile, rows)
Ejemplo n.º 18
0
def ico2png(data):
	"""Convert the bytestring data of an ICO file to PNG-format data as a bytestring."""
	# try to extract the 6-byte ICO header
	try:
		header = unpack('<3H', data[0:6])
	except:
		raise TypeError # data is not an ICO
	if header[:2] != (0,1):
		raise TypeError # data is not an ICO

	# the number of images in the file is header[2]
	image_count = header[2]

	# collect the icon directories
	directories = []
	for i in xrange(image_count):
		directory = list(unpack('<4B2H2I', data[6 + 16 * i : 6 + 16 * i + 16]))
		for j in xrange(3):
			if not directory[j]:
				directory[j] = 256
		directories.append(directory)

	# select "best" icon (??)
	directory = max(directories, key=(lambda x:x[0:3]))

	# get data of that image
	width = directory[0]
	height = directory[1]
	offset = directory[7]
	result = {
		'width':width,
		'height':height,
		'colors':directory[2],
		'bytes':directory[6],
		'offset':offset,
		}
	if data[offset:offset+16] == "\211PNG\r\n\032\n":
		# looks like a PNG, so return the data from here out.
		return data[offset:]
	else:
		dib_size = unpack('<I', data[offset:offset+4])[0]
		if dib_size != 40:
			raise TypeError # don't know how to handle an ICO where the DIB isn't 40 bytes
		else:
			dib = unpack('<L2l2H2L2l2L', data[offset:offset+dib_size])
			bits_per_pixel = dib[4]
			bmp_data_bytes = dib[6]
			if bmp_data_bytes == 0:
				bmp_data_bytes = width * height * bits_per_pixel / 8
			if bits_per_pixel <= 8:
				# assemble the color palette
				color_count = 2 ** bits_per_pixel
				raw_colors = [
					unpack('BBBB', data[offset + dib_size + 4 * i : offset + dib_size + 4 * i + 4])
					for i in xrange(0,color_count)
					]
				# the RGBQUAD for each palette color is (blue, green, red, reserved)
				palette = [ tuple([color[x] for x in (2, 1, 0)]) for color in raw_colors ]

				# get the XorMap bits
				xor_data_bits = [
					bit
					for byte in data[
						offset + dib_size + color_count * 4
						: offset + dib_size + color_count * 4 + bmp_data_bytes
						]
					for bit in _bitlist(unpack('B',byte)[0])
					]
				# get the AndMap bits
				and_row_size = ((width + 31) >> 5) << 2
				and_data_bits = [
					bit
					for byte in data[
						offset + dib_size + color_count * 4 + bmp_data_bytes
						: offset + dib_size + color_count * 4 + bmp_data_bytes + and_row_size * height
						]
					for bit in _bitlist(unpack('B',byte)[0])
					]

				# assemble the combined image (with transparency)
				def get_pixel(x,y):
					if and_data_bits[(height - y - 1) * and_row_size * 8 + x] == 1:
						# transparent
						return (0,0,0,0)
					else:
						# use the xor value, made solid
						return palette[_bitlistvalue(
							xor_data_bits[
								bits_per_pixel * ((height - y - 1) * width + x)
								: bits_per_pixel * ((height - y - 1) * width + x) + bits_per_pixel
								]
							)] + (255,)
				pixels = [
					[
						c
						for x in xrange(result['width'])
						for c in get_pixel(x,y)
						]
					for y in xrange(result['height'])
					]
			elif bits_per_pixel == 32:
				raw_pixels = [
					[
						unpack('BBBB', data[offset + dib_size + 4 * (y * width + x) : offset + dib_size + 4 * (y * width + x) + 4])
						for x in xrange(width)
						]
					for y in xrange(height-1, -1, -1)
					]
				pixels = [
					[
						c
						for px in row
						for c in (px[2], px[1], px[0], px[3])
						]
					for row in raw_pixels
					]
			elif bits_per_pixel == 24:
				raw_pixels = [
					[
						unpack('BBB', data[offset + dib_size + 3 * (y * width + x) : offset + dib_size + 3 * (y * width + x) + 3])
						for x in xrange(width)
						]
					for y in xrange(height-1, -1, -1)
					]
				pixels = [
					[
						c
						for px in row
						for c in (px[2], px[1], px[0], 255)
						]
					for row in raw_pixels
					]
			else:
				raise TypeError # don't know how to handle the pixel depth value
					
	out = StringIO()
	w = PNGWriter(result['width'],result['height'],alpha=True)
	w.write(out, pixels)
	return out.getvalue()
    def _preprocessing(self, sequence):
        """Preprocessing of SYNTHIA data.

        Performs several steps:
            - Original images are of size 1280x760. To make training and data loading
              faster, we resize them to a width of 640 (factor 2). However, picture
              dimensions need to be a multiple of 16 to pass through 4 levels of
              pooling in VGG16, therefore we have to crop the image a little bit in
              height and end up at a size of 640x368
            - Resizing is done with boilinear interpolation for RGB and taking the upper-
              left corner of every group of pixels for depth and label.
            - Labels are stored in a crude version of the png format. We open this,
              extract the label integer from the first channel (we omit the item ID as we
              do not use it) and store it as numpy file.
            - From the available images, we select a random 20% sample as a test-set and
              store the indexes of the train/test split so they are consistent between
              training runs.
        """
        print('INFO: Preprocessing started for {}. This may take a while.'.
              format(sequence))
        sequence_basepath = path.join(self.base_path, sequence)

        # First we create directories for the downsamples images.
        for modality, direction in itertools.product(
            ['RGB', 'Depth', 'labels'], ['F', 'B', 'L', 'R']):
            new_images = path.join(
                sequence_basepath,
                'resized_{}_{}'.format(modality.lower(), direction))
            if path.exists(new_images):
                # We are doing a fresh preprocessing, so delete old data.
                shutil.rmtree(new_images)
            mkdir(new_images)

            # RGB and Depth Images can simply be resized by PIL.
            if modality in ['RGB', 'Depth']:
                original_images = path.join(
                    sequence_basepath,
                    '{}/Stereo_Right/Omni_{}'.format(modality, direction))

                # As we have to handle different bitdepths and cropped images, we use
                # pypng for writing the new files.
                bitdepth = 8 if modality == 'RGB' else 16
                writer = Writer(width=640,
                                height=368,
                                bitdepth=bitdepth,
                                greyscale=(modality == 'Depth'))

                for filename in listdir(original_images):
                    if modality == 'RGB':
                        image = Image.open(path.join(original_images,
                                                     filename))
                        resized = image.resize([640, 380],
                                               resample=Image.BILINEAR)
                        resized = np.asarray(resized, dtype=np.uint8)
                    elif modality == 'Depth':
                        image = one_channel_image_reader(
                            path.join(original_images, filename), np.uint16)
                        resized = zoom(image, 0.5, mode='nearest', order=0)
                    # The image has to get cropped, see docstring of crop method
                    cropped = crop_resized_image(resized)
                    # Now save again accoding to different formats
                    with open(path.join(new_images, filename), 'wb') as f:
                        # The writer is expecting a consecutive list of RGBRGBR... values
                        if modality == 'RGB':
                            val_list = cropped.reshape(368, 640 * 3).tolist()
                        elif modality == 'Depth':
                            val_list = cropped.tolist()
                        writer.write(f, val_list)
                continue

            # Label image has a weird two-channel format where the 1st channel is the
            # 8bit label integer and the second channel is the instance ID we do not use.
            # We save the extracted label integer as numpy array to make things easier.
            original_images = path.join(
                sequence_basepath,
                'GT/LABELS/Stereo_Right/Omni_{}'.format(direction))

            for filename in listdir(original_images):
                # Labels are stored in the 1st channel of the png file
                array = one_channel_image_reader(
                    path.join(original_images, filename), np.uint8)
                resized = zoom(array, 0.5, mode='nearest', order=0)
                # The image has to get cropped, se docstring of crop method
                cropped = crop_resized_image(resized)
                # Now we can save it as a numpy array
                np.save(path.join(new_images, filename.split('.')[0]), cropped)

        filenames = [
            filename.split('.')[0] for filename in listdir(
                path.join(sequence_basepath, 'resized_rgb_F'))
        ]
        trainset, testset = train_test_split(filenames, test_size=0.2)
        with open('{}/train_test_split.json'.format(sequence_basepath),
                  'w') as f:
            json.dump({'trainset': trainset, 'testset': testset}, f)
        print('INFO: Preprocessing finished.')