def test_basic(self):
        w = 22
        h = 10
        bitdepth = 8
        np.random.seed(123)
        img = np.random.randint(0, 256, size=(h, w)).astype(np.uint8)

        f = io.BytesIO()
        numpngw.write_png(f, img, filter_type=1)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1],
                                   height=img.shape[0],
                                   bit_depth=bitdepth, color_type=0,
                                   interlace=0)

        file_contents = check_text(file_contents, b"Creation Time")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        file_contents = check_idat(file_contents, color_type=0,
                                   bit_depth=bitdepth, interlace=0,
                                   img=img)

        check_iend(file_contents)
Beispiel #2
0
    def test_write_png_nbit_grayscale(self):
        # Test the creation of grayscale images for bit depths of 1, 2, 4
        # 8 and 16, with or without a `transparent` color selected.
        np.random.seed(123)
        for bitdepth in [1, 2, 4, 8, 16]:
            for transparent in [None, 0]:
                dt = np.uint16 if bitdepth == 16 else np.uint8
                maxval = 2**bitdepth
                img = np.random.randint(0, maxval, size=(3, 11)).astype(dt)
                if transparent is not None:
                    img[2:4, 2:] = transparent

                f = io.BytesIO()
                numpngw.write_png(f, img, bitdepth=bitdepth,
                                  transparent=transparent)

                file_contents = f.getvalue()

                file_contents = check_signature(file_contents)

                file_contents = check_ihdr(file_contents,
                                           width=img.shape[1],
                                           height=img.shape[0],
                                           bit_depth=bitdepth, color_type=0)

                if transparent is not None:
                    file_contents = check_trns(file_contents, color_type=0,
                                               transparent=transparent)

                file_contents = check_idat(file_contents, color_type=0,
                                           bit_depth=bitdepth, img=img)

                check_iend(file_contents)
Beispiel #3
0
    def test_write_png_with_alpha(self):
        # Test creation of grayscale+alpha and RGBA images (color types 4
        # and 6, resp.), with bit depths 8 and 16.
        w = 25
        h = 15
        np.random.seed(12345)
        for color_type in [4, 6]:
            num_channels = 2 if color_type == 4 else 4
            for bit_depth in [8, 16]:
                dt = np.uint8 if bit_depth == 8 else np.uint16
                img = np.random.randint(0, 2**bit_depth,
                                        size=(h, w, num_channels)).astype(dt)
                f = io.BytesIO()
                numpngw.write_png(f, img)

                file_contents = f.getvalue()

                file_contents = check_signature(file_contents)

                file_contents = check_ihdr(file_contents, width=w, height=h,
                                           bit_depth=bit_depth,
                                           color_type=color_type)

                file_contents = check_idat(file_contents,
                                           color_type=color_type,
                                           bit_depth=bit_depth, img=img)

                check_iend(file_contents)
    def test_text_and_phys(self):
        img = np.arange(15).reshape(3, 5).astype(np.uint8)
        text_list = [('Monster', 'Godzilla'), ('Creation Time', None)]
        phys = (5, 4, 0)

        f = io.BytesIO()
        numpngw.write_png(f, img, filter_type=0, text_list=text_list,
                          phys=phys)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1],
                                   height=img.shape[0],
                                   bit_depth=8, color_type=0,
                                   interlace=0)

        file_contents = check_text(file_contents, b"Monster", b"Godzilla")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        file_contents = check_phys(file_contents, phys)

        file_contents = check_idat(file_contents, color_type=0,
                                   bit_depth=8, interlace=0,
                                   img=img)

        check_iend(file_contents)
Beispiel #5
0
    def test_write_png_8bit_RGB_palette(self):
        img = np.arange(4*5*3, dtype=np.uint8).reshape(4, 5, 3)
        f = io.BytesIO()
        numpngw.write_png(f, img, use_palette=True)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1], height=img.shape[0],
                                   bit_depth=8, color_type=3)

        # Check the PLTE chunk.
        chunk_type, chunk_data, file_contents = next_chunk(file_contents)
        self.assertEqual(chunk_type, b"PLTE")
        p = np.fromstring(chunk_data, dtype=np.uint8).reshape(-1, 3)
        assert_array_equal(p, np.arange(4*5*3, dtype=np.uint8).reshape(-1, 3))

        # Check the IDAT chunk.
        chunk_type, chunk_data, file_contents = next_chunk(file_contents)
        self.assertEqual(chunk_type, b"IDAT")
        decompressed = zlib.decompress(chunk_data)
        b = np.fromstring(decompressed, dtype=np.uint8)
        lines = b.reshape(img.shape[0], img.shape[1]+1)
        img2 = lines[:, 1:].reshape(img.shape[:2])
        expected = np.arange(20, dtype=np.uint8).reshape(img.shape[:2])
        assert_array_equal(img2, expected)

        check_iend(file_contents)
    def test_write_png_timestamp_gamma(self):
        np.random.seed(123)
        img = np.random.randint(0, 256, size=(10, 10)).astype(np.uint8)
        f = io.BytesIO()
        timestamp = (1452, 4, 15, 8, 9, 10)
        gamma = 2.2
        numpngw.write_png(f, img, timestamp=timestamp, gamma=gamma)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1], height=img.shape[0],
                                   bit_depth=8, color_type=0, interlace=0)

        file_contents = check_text(file_contents, b"Creation Time")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        file_contents = check_time(file_contents, timestamp)

        file_contents = check_gama(file_contents, gamma)

        file_contents = check_idat(file_contents, color_type=0, bit_depth=8,
                                   interlace=0, img=img)

        check_iend(file_contents)
Beispiel #7
0
    def test_write_png_timestamp_gamma(self):
        np.random.seed(123)
        img = np.random.randint(0, 256, size=(10, 10)).astype(np.uint8)
        f = io.BytesIO()
        timestamp = (1452, 4, 15, 8, 9, 10)
        gamma = 2.2
        numpngw.write_png(f, img, timestamp=timestamp, gamma=gamma)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1],
                                   height=img.shape[0],
                                   bit_depth=8,
                                   color_type=0,
                                   interlace=0)

        file_contents = check_text(file_contents, b"Creation Time")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        file_contents = check_time(file_contents, timestamp)

        file_contents = check_gama(file_contents, gamma)

        file_contents = check_idat(file_contents,
                                   color_type=0,
                                   bit_depth=8,
                                   interlace=0,
                                   img=img)

        check_iend(file_contents)
Beispiel #8
0
def process(image_files):
#    if not net:
#        init_caffe()
    caffe.set_mode_gpu()
    caffe.set_device(1)
    model_def = 'deploy_unreal.prototxt'
    model_weights = 'model/DispNetCorr1D_CVPR2016.caffemodel'

    net = caffe.Net(model_def, model_weights, caffe.TEST)

    transformer = caffe.io.Transformer({'data': net.blobs['img0'].data.shape})

    transformer.set_transpose('data', (2,0,1))  # move image channels to outermost dimension
    #transformer.set_mean('data', mu)            # subtract the dataset-mean value in each channel
    transformer.set_raw_scale('data', 255)      # rescale from [0, 1] to [0, 255]
    transformer.set_channel_swap('data', (2,1,0))  # swap channels from RGB to BGR

    img_L0 = caffe.io.load_image(image_files[0])
    img_R0 = caffe.io.load_image(image_files[1])

    img_L = transformer.preprocess('data', img_L0)
    img_R = transformer.preprocess('data', img_R0)

    net.blobs['img0'].data[...] = img_L
    net.blobs['img1'].data[...] = img_R
    print('caffe initialized...')
    net.forward()

    output = net.blobs['predict_disp_final'].data[0,0,:,:]
    disp_est = -1*output
    numpngw.write_png(image_files[2], np.uint16(disp_est*256))
Beispiel #9
0
    def test_write_png_bkgd(self):
        # Test creation of RGB images (color type 2), with a background color.
        w = 16
        h = 8
        np.random.seed(123)
        for bit_depth in [8, 16]:
            maxval = 2**bit_depth
            bg = (maxval - 1, maxval - 2, maxval - 3)
            dt = np.uint16 if bit_depth == 16 else np.uint8
            img = np.random.randint(0, maxval, size=(h, w, 3)).astype(dt)

            f = io.BytesIO()
            numpngw.write_png(f, img, background=bg, filter_type=0)

            file_contents = f.getvalue()

            file_contents = check_signature(file_contents)

            file_contents = check_ihdr(file_contents, width=w, height=h,
                                       bit_depth=bit_depth, color_type=2,
                                       interlace=0)

            file_contents = check_text(file_contents, b"Creation Time")
            software = numpngw._software_text().encode('latin-1')
            file_contents = check_text(file_contents, b"Software",
                                       software)

            file_contents = check_bkgd(file_contents, color=bg, color_type=2)

            file_contents = check_idat(file_contents, color_type=2,
                                       bit_depth=bit_depth, interlace=0,
                                       img=img)

            check_iend(file_contents)
def _save_pairs(dataset, save_path, data_type):
    keys = dataset.keys()
    for key in keys:
        dcm = dataset[f"{key}/t2"][()]
        label = dataset[f"{key}/seg"][()]

        start, end = _range_idx(label, 20)
        for i in range(start, end):
            slice_dcm = dcm[:, :, i]

            slice_dcm = slice_dcm * ((pow(2, 16) - 1) / slice_dcm.max())
            slice_dcm = slice_dcm.astype("uint16")
            slice_label = label[:, :, i]

            # Add skull structure into label
            skull_mask = np.zeros_like(slice_dcm)
            skull_mask[slice_dcm > 0] = 1
            ndimage.binary_fill_holes(skull_mask)
            skull_mask = cv2.Laplacian(skull_mask.astype("uint8"), cv2.CV_8U)
            skull_mask[skull_mask > 0] = 1
            slice_label = slice_label + skull_mask
            slice_label = slice_label.astype("uint8")
            slice_label[slice_label > 0] = 255

            numpngw.write_png(
                os.path.join(save_path, "B", data_type, f"{key}_{i}.png"),
                slice_dcm)
            numpngw.write_png(
                os.path.join(save_path, "A", data_type, f"{key}_{i}.png"),
                slice_label)
            print(f"Save image to: {save_path}/A/{data_type}/{key}_{i}.png...")
Beispiel #11
0
def show_image(a):
    png_array = cStringIO.StringIO()
    numpngw.write_png(png_array, a)
    encoded_png_array = base64.b64encode(png_array.getvalue())
    png_array.close()
    image_seq = '\033]1337;File=[width=auto;height=auto;inline=1]:' + encoded_png_array + '\007'
    print(image_seq)
Beispiel #12
0
    def test_text_and_phys(self):
        img = np.arange(15).reshape(3, 5).astype(np.uint8)
        text_list = [('Monster', 'Godzilla'), ('Creation Time', None)]
        phys = (5, 4, 0)

        f = io.BytesIO()
        numpngw.write_png(f, img, filter_type=0, text_list=text_list,
                          phys=phys)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1],
                                   height=img.shape[0],
                                   bit_depth=8, color_type=0,
                                   interlace=0)

        file_contents = check_text(file_contents, b"Monster", b"Godzilla")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        file_contents = check_phys(file_contents, phys)

        file_contents = check_idat(file_contents, color_type=0,
                                   bit_depth=8, interlace=0,
                                   img=img)

        check_iend(file_contents)
Beispiel #13
0
    def test_basic(self):
        w = 22
        h = 10
        bitdepth = 8
        np.random.seed(123)
        img = np.random.randint(0, 256, size=(h, w)).astype(np.uint8)

        f = io.BytesIO()
        numpngw.write_png(f, img, filter_type=1)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=img.shape[1],
                                   height=img.shape[0],
                                   bit_depth=bitdepth, color_type=0,
                                   interlace=0)

        file_contents = check_text(file_contents, b"Creation Time")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        file_contents = check_idat(file_contents, color_type=0,
                                   bit_depth=bitdepth, interlace=0,
                                   img=img)

        check_iend(file_contents)
Beispiel #14
0
def generateQLook(generalSceneId, qlfiles):
    profile = None
    with rasterio.open(qlfiles[0]) as src:
        profile = src.profile

    numlin = 768
    numcol = int(float(profile['width']) / float(profile['height']) * numlin)
    image = numpy.ones((
        numlin,
        numcol,
        len(qlfiles),
    ), dtype=numpy.uint8)
    pngname = '/tmp/{}.png'.format(generalSceneId)

    nb = 0
    for file in qlfiles:
        with rasterio.open(file) as src:
            raster = src.read(1, out_shape=(numlin, numcol))
            # Rescale to 0-255 values
            nodata = raster <= 0
            if raster.min() != 0 or raster.max() != 0:
                raster = raster.astype(numpy.float32) / 10000. * 255.
                raster[raster > 255] = 255
            image[:, :, nb] = raster.astype(numpy.uint8) * numpy.invert(nodata)
            nb += 1

    write_png(pngname, image, transparent=(0, 0, 0))
    return pngname
Beispiel #15
0
    def test_write_png_bkgd(self):
        # Test creation of RGB images (color type 2), with a background color.
        w = 16
        h = 8
        np.random.seed(123)
        for bit_depth in [8, 16]:
            maxval = 2**bit_depth
            bg = (maxval - 1, maxval - 2, maxval - 3)
            dt = np.uint16 if bit_depth == 16 else np.uint8
            img = np.random.randint(0, maxval, size=(h, w, 3)).astype(dt)

            f = io.BytesIO()
            numpngw.write_png(f, img, background=bg)

            file_contents = f.getvalue()

            file_contents = check_signature(file_contents)

            file_contents = check_ihdr(file_contents, width=w, height=h,
                                       bit_depth=bit_depth, color_type=2)

            file_contents = check_bkgd(file_contents, color=bg, color_type=2)

            file_contents = check_idat(file_contents, color_type=2,
                                       bit_depth=bit_depth, img=img)

            check_iend(file_contents)
Beispiel #16
0
def process(image_files):
    #    if not net:
    #        init_caffe()
    caffe.set_mode_gpu()
    caffe.set_device(1)
    model_def = 'deploy_unreal.prototxt'
    model_weights = 'model/DispNetCorr1D_CVPR2016.caffemodel'

    net = caffe.Net(model_def, model_weights, caffe.TEST)

    transformer = caffe.io.Transformer({'data': net.blobs['img0'].data.shape})

    transformer.set_transpose(
        'data', (2, 0, 1))  # move image channels to outermost dimension
    #transformer.set_mean('data', mu)            # subtract the dataset-mean value in each channel
    transformer.set_raw_scale('data', 255)  # rescale from [0, 1] to [0, 255]
    transformer.set_channel_swap('data',
                                 (2, 1, 0))  # swap channels from RGB to BGR

    img_L0 = caffe.io.load_image(image_files[0])
    img_R0 = caffe.io.load_image(image_files[1])

    img_L = transformer.preprocess('data', img_L0)
    img_R = transformer.preprocess('data', img_R0)

    net.blobs['img0'].data[...] = img_L
    net.blobs['img1'].data[...] = img_R
    print('caffe initialized...')
    net.forward()

    output = net.blobs['predict_disp_final'].data[0, 0, :, :]
    disp_est = -1 * output
    numpngw.write_png(image_files[2], np.uint16(disp_est * 256))
Beispiel #17
0
    def test_write_png_RGB(self):
        # Test creation of RGB images (color type 2), with and without
        # a `transparent` color selected, and with bit depth 8 and 16.
        w = 24
        h = 10
        np.random.seed(12345)
        for transparent in [None, (0, 0, 0)]:
            for bit_depth in [8, 16]:
                dt = np.uint16 if bit_depth == 16 else np.uint8
                maxval = 2**bit_depth
                img = np.random.randint(0, maxval, size=(h, w, 3)).astype(dt)
                if transparent:
                    img[2:4, 2:4] = transparent

                f = io.BytesIO()
                numpngw.write_png(f, img, transparent=transparent)

                file_contents = f.getvalue()

                file_contents = check_signature(file_contents)

                file_contents = check_ihdr(file_contents, width=w, height=h,
                                           bit_depth=bit_depth, color_type=2)

                if transparent:
                    file_contents = check_trns(file_contents, color_type=2,
                                               transparent=transparent)

                file_contents = check_idat(file_contents, color_type=2,
                                           bit_depth=bit_depth, img=img)

                check_iend(file_contents)
def create_qlook_file(pngname, qlfile):
    """Create sentinel 2 quicklook."""
    image = numpy.ones((768, 768, 3,), dtype=numpy.uint8)
    dataset = gdal.Open(qlfile, gdal.GA_ReadOnly)
    for nb in [0, 1, 2]:
        raster = dataset.GetRasterBand(nb + 1).ReadAsArray(0, 0, dataset.RasterXSize, dataset.RasterYSize)
        image[:, :, nb] = resize(raster, (768, 768), order=1, preserve_range=True).astype(numpy.uint8)
        write_png(pngname, image, transparent=(0, 0, 0))
Beispiel #19
0
 def to_png16(self, out_fp=None, trash=False):
     #        import numpy as np
     from numpngw import write_png
     import skimage.io
     if not out_fp:
         out_fp = self.with_suffix(".png")
     img = skimage.io.imread(self, plugin='tifffile')
     write_png(out_fp, img)
Beispiel #20
0
def convert(raw_path, temp_path, dest_path, domains, dry_run=True):
    total = 0
    for image_path in glob.glob(os.path.join(raw_path, "*B[0-9].png")):
        image_name = image_path.split(os.path.sep)[-1]
        image_name_base = image_name.split('.')[0]

        domain = image_name_base.split('_')[0]
        if domain in domains:
            image_name_raw = image_name_base + '.png'
            image_name_mask = image_name_base + '_mask.png'

            img_uint16 = imread(os.path.join(raw_path, image_name_raw),
                                as_gray=True)  #np.uint16 [0, 65535]
            mask_uint16 = imread(os.path.join(raw_path, image_name_mask),
                                 as_gray=True)  #np.uint16 [0, 65535]
            img_f64 = resize(img_uint16, (224, 224),
                             preserve_range=True)  #np.float64 [0.0, 65535.0]
            mask_f64 = resize(mask_uint16, (224, 224),
                              order=0,
                              preserve_range=True)  #np.float64 [0.0, 65535.0]

            #Convert greyscale to RGB greyscale
            img_max = img_f64.max()
            img_min = img_f64.min()
            img_range = img_max - img_min
            mask_max = mask_f64.max()
            if (img_max != 0.0 and img_range > 255.0):
                img_uint8 = np.round(img_f64 / img_max * 255.0).astype(
                    np.uint8)  #np.float32 [0, 65535.0]
            else:
                img_uint8 = img_f64.astype(np.uint8)
            if (mask_max != 0.0):
                mask_uint8 = np.floor(mask_f64 / mask_max * 255.0).astype(
                    np.uint8)  #np.uint8 [0, 255]
            else:
                mask_uint8 = mask_f64.astype(np.uint8)

            print(image_name_base)
            thickness = 3
            kernel = cv2.getStructuringElement(cv2.MORPH_RECT,
                                               (thickness, thickness))
            mask_edge = cv2.Canny(
                mask_uint8, 250, 255 * 2
            )  #thresholds = Use diagonals to detect strong edges, then connect anything with at least a single edge
            mask_edge_f32 = cv2.dilate(
                mask_edge.astype('float64'), kernel,
                iterations=1).astype(np.float32)  #np.float32 [0.0, 255.0]
            mask_edge_f32 = np.where(mask_edge_f32 > 127.0, 1.0, 0.0)

            save_path_raw = os.path.join(dest_path, image_name_raw)
            save_path_mask = os.path.join(dest_path, image_name_mask)
            total += 1
            print('Saving #' + str(total) + ' processed raw to:',
                  save_path_raw)
            if (dry_run == False):
                numpngw.write_png(save_path_raw, img_uint8)
                imsave(save_path_mask, mask_edge_f32)
Beispiel #21
0
def separate_labels(npim, label_list, outpath):
    """
    For converting the classifier results to unreal masks
    """
    for i,label in enumerate(label_list):
        out = np.zeros(npim.shape)
        out[npim == i+1] = 65535
        out = out.astype(np.uint16)
        numpngw.write_png('%s.png' % os.path.join(outpath, label), out)
Beispiel #22
0
def save_as_16b(_img, tgt_path):
    """
    saving a numpy array [0,1] as 16 bit grayscale image
    :param _img:
    :param tgt_path:
    :return:
    """
    _img_16b = (np.clip(_img, 0.0, 1.0) * 65535.).astype(np.uint16)
    write_png(tgt_path, _img_16b, bitdepth=16)
def save_depth(result, config, saver, output_path):

    with tf.Session(config=config) as sess:
        ckpt = tf.train.get_checkpoint_state(CHECKPOINT_DIR)
        if ckpt and ckpt.model_checkpoint_path:
            # Restores from checkpoint
            saver.restore(sess, ckpt.model_checkpoint_path)
            #Assuming model_checkpoint_path looks something like:
            # extract global_step from it.
            global_step = ckpt.model_checkpoint_path.split('/')[-1].split(
                '-')[-1]
            print('Checkpoint is loaded')
        else:
            print('No checkpoint file found')
            return
        # Start the queue runners.
        coord = tf.train.Coordinator()
        try:
            threads = []
            for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
                threads.extend(
                    qr.create_threads(sess,
                                      coord=coord,
                                      daemon=True,
                                      start=True))

            start_time = time.time()
            res = sess.run([result])
            duration = time.time() - start_time
            print("Loading model and evaluation took (seconds): ", duration)

            res = np.array(res)
            print("Minimum value of depth (meters): ", np.min(res))
            print("Maximum value of depth (meters): ", np.max(res))
            res *= 1000

            for i in range(0, res.shape[4]):
                if i < 10:
                    image_name = "LSTM_depth_0" + str(i) + ".png"
                else:
                    image_name = "LSTM_depth_" + str(i) + ".png"

                name = output_path + image_name

                depth = np.array(res[0, 0, :, :, i], dtype=np.uint16)

                if SaveDepthRealValued == True:
                    numpngw.write_png(name, depth)
                else:
                    scipy.misc.toimage(depth, cmin=0, cmax=5000).save(name)

        except Exception as e:  # pylint: disable=broad-except
            coord.request_stop(e)
        coord.request_stop()
        coord.join(threads, stop_grace_period_secs=10)
        print("Result depths saved in ./example/ folder")
Beispiel #24
0
def make_image(n_int, CMs_ind):

    n = str(n_int)

    table = np.loadtxt('./output/ctags' + n + '.out', skiprows=1)
    img = np.ones(table.shape + (3, ), dtype=np.uint8) * 255
    conts = np.loadtxt('./output/contactM' + n + '.out', skiprows=1)
    fibs = np.loadtxt('./output/fib.out', skiprows=1)

    edges = np.zeros(table.shape, dtype=np.uint8)
    vert = table[:, 1:] != table[:, :-1]
    hor = table[1:, :] != table[:-1, :]
    edges[:, 1:] = vert
    edges[:, :-1] += vert
    edges[1:, :] += hor
    edges[:-1, :] += hor
    edges = np.uint8(edges != 0)

    is_CM = np.vectorize(lambda x: x in CMs_ind)

    null = np.uint8(table == 0)
    CMs = is_CM(table).astype('uint8')
    FBs = np.ones_like(table) - null - CMs

    f = 0
    cont_edges = edges
    if sys.argv[
            3] != "0":  #if not 0, show contacts/attachments at least on the edge of the cell
        f = 0.5
    if sys.argv[
            3] == "2":  #if 2, show all of the attachment sites, even those under the cell
        cont_edges = 1

    img[:, :, 0] = conts * 255
    img[:, :, 1] = edges * 255
    #write_png("./imgs/conts.png", img)

    Fibs = fibs * (1 - CMs) * (1 - FBs) * 255 * 0.1

    img[:, :, 0] = CMs * (1 - 0.5 * edges) * 255 + FBs * (
        1 - 0.5 * edges
    ) * 255 + f * conts * cont_edges * CMs * 255 + f * conts * cont_edges * FBs * 255 + Fibs
    img[:, :, 1] = FBs * (
        1 - 0.5 * edges
    ) * 255 + 2 * f * conts * cont_edges * CMs * 255 + f * conts * cont_edges * FBs * 255 + Fibs
    img[:, :, 2] = FBs * (
        1 - 0.5 * edges) * 255 - f * conts * cont_edges * FBs * 255 + Fibs

    areas = np.zeros(4)
    conv = (2.5 / 1000)**2  #to mm
    areas = (np.sum(CMs) * conv, np.sum(FBs) * conv)

    write_png("./imgs/example%05d.png" % n_int, img)

    return areas
def predict(model_data_path, image_root, output_root):

    # Default input size
    height = 228
    width = 304
    channels = 3
    batch_size = 1

    # Create a placeholder for the input image
    input_node = tf.placeholder(tf.float32,
                                shape=(None, height, width, channels))

    # Construct the network
    net = models.ResNet50UpProj({'data': input_node}, batch_size, 1, False)

    with tf.Session() as sess:

        # Load the converted parameters
        print('Loading the model')

        # Use to load from ckpt file
        saver = tf.train.Saver()
        saver.restore(sess, model_data_path)

        # Use to load from npy file
        #net.load(model_data_path, sess)

        fileNum = len([name for name in os.listdir(image_root)])
        names = [name for name in os.listdir(image_root)]
        print(image_root)
        print(fileNum)
        #for idx in range(0, fileNum):
        for nm in names:
            #image_path = image_root + "color_out" + str(idx+1).zfill(6) + ".png"
            image_path = image_root + nm
            #output_path = output_root + "depth_out" + str(idx+1).zfill(6) + ".png"
            output_path = output_root + nm
            # Read image
            img = Image.open(image_path)
            img = img.resize([width, height], Image.ANTIALIAS)
            img = np.array(img).astype('float32')
            img = np.expand_dims(np.asarray(img), axis=0)

            # Evalute the network for the given image
            pred = sess.run(net.get_output(), feed_dict={input_node: img})

            pre_new = pred[0, :, :, 0]
            pre_new = pre_new * 1000 * 5

            pre_resize = scipy.ndimage.zoom(pre_new, 4, order=0)

            img = np.zeros((128 * 4, 160 * 4, 1), dtype=np.uint16)
            img[:, :, 0] = pre_resize

            numpngw.write_png(output_path, img)
Beispiel #26
0
    def test_write_png_bkgd_palette(self):
        # Test creation of RGB images with a background color
        # when use_palette is True.
        w = 6
        h = 8
        np.random.seed(123)
        for bg_in_img in [True, False]:
            bit_depth = 8
            maxval = 2**bit_depth
            bg = (maxval - 1, maxval - 3, maxval - 2)

            img = np.arange(1, w*h*3 + 1, dtype=np.uint8).reshape(h, w, 3)
            if bg_in_img:
                img[-1, -1] = bg

            f = io.BytesIO()
            numpngw.write_png(f, img, background=bg, use_palette=True)

            file_contents = f.getvalue()

            file_contents = check_signature(file_contents)

            file_contents = check_ihdr(file_contents, width=w, height=h,
                                       bit_depth=bit_depth, color_type=3,
                                       interlace=0)

            file_contents = check_text(file_contents, b"Creation Time")
            software = numpngw._software_text().encode('latin-1')
            file_contents = check_text(file_contents, b"Software",
                                       software)

            # Check the PLTE chunk.
            chunk_type, chunk_data, file_contents = next_chunk(file_contents)
            self.assertEqual(chunk_type, b"PLTE")
            plte = np.frombuffer(chunk_data, dtype=np.uint8).reshape(-1, 3)
            expected_palette = np.arange(1, w*h*3+1,
                                         dtype=np.uint8).reshape(-1, 3)
            if bg_in_img:
                expected_palette[-1] = bg
            else:
                expected_palette = np.append(expected_palette,
                                             np.array([bg], dtype=np.uint8),
                                             axis=0)
            assert_array_equal(plte, expected_palette,
                               "unexpected palette %r %r" %
                               (plte[-2], expected_palette[-2]))

            file_contents = check_bkgd(file_contents, color=bg, color_type=3,
                                       palette=expected_palette)

            file_contents = check_idat(file_contents, color_type=3,
                                       bit_depth=bit_depth, interlace=0,
                                       img=img, palette=plte)

            check_iend(file_contents)
    def test_write_png_bkgd_palette(self):
        # Test creation of RGB images with a background color
        # when use_palette is True.
        w = 6
        h = 8
        np.random.seed(123)
        for bg_in_img in [True, False]:
            bit_depth = 8
            maxval = 2**bit_depth
            bg = (maxval - 1, maxval - 3, maxval - 2)

            img = np.arange(1, w*h*3 + 1, dtype=np.uint8).reshape(h, w, 3)
            if bg_in_img:
                img[-1, -1] = bg

            f = io.BytesIO()
            numpngw.write_png(f, img, background=bg, use_palette=True)

            file_contents = f.getvalue()

            file_contents = check_signature(file_contents)

            file_contents = check_ihdr(file_contents, width=w, height=h,
                                       bit_depth=bit_depth, color_type=3,
                                       interlace=0)

            file_contents = check_text(file_contents, b"Creation Time")
            software = numpngw._software_text().encode('latin-1')
            file_contents = check_text(file_contents, b"Software",
                                       software)

            # Check the PLTE chunk.
            chunk_type, chunk_data, file_contents = next_chunk(file_contents)
            self.assertEqual(chunk_type, b"PLTE")
            plte = np.fromstring(chunk_data, dtype=np.uint8).reshape(-1, 3)
            expected_palette = np.arange(1, w*h*3+1,
                                         dtype=np.uint8).reshape(-1, 3)
            if bg_in_img:
                expected_palette[-1] = bg
            else:
                expected_palette = np.append(expected_palette,
                                             np.array([bg], dtype=np.uint8),
                                             axis=0)
            assert_array_equal(plte, expected_palette,
                               "unexpected palette %r %r" %
                               (plte[-2], expected_palette[-2]))

            file_contents = check_bkgd(file_contents, color=bg, color_type=3,
                                       palette=expected_palette)

            file_contents = check_idat(file_contents, color_type=3,
                                       bit_depth=bit_depth, interlace=0,
                                       img=img, palette=plte)

            check_iend(file_contents)
Beispiel #28
0
    def test_write_png_RGB(self):
        # Test creation of RGB images (color type 2), with and without
        # a `transparent` color selected, and with bit depth 8 and 16.
        w = 24
        h = 10
        np.random.seed(12345)
        for filter_type in [0, 1, 2, 3, 4, "heuristic", "auto"]:
            for transparent in [None, (0, 0, 0)]:
                for bit_depth in [8, 16]:
                    for interlace in [0, 1]:
                        dt = np.uint16 if bit_depth == 16 else np.uint8
                        maxval = 2**bit_depth
                        img = np.random.randint(0, maxval,
                                                size=(h, w, 3)).astype(dt)
                        if transparent:
                            img[2:4, 2:4] = transparent

                        f = io.BytesIO()
                        numpngw.write_png(f,
                                          img,
                                          transparent=transparent,
                                          filter_type=filter_type,
                                          interlace=interlace)

                        file_contents = f.getvalue()

                        file_contents = check_signature(file_contents)

                        file_contents = check_ihdr(file_contents,
                                                   width=w,
                                                   height=h,
                                                   bit_depth=bit_depth,
                                                   color_type=2,
                                                   interlace=interlace)

                        file_contents = check_text(file_contents,
                                                   b"Creation Time")
                        software = numpngw._software_text().encode('latin-1')
                        file_contents = check_text(file_contents, b"Software",
                                                   software)

                        if transparent:
                            file_contents = check_trns(file_contents,
                                                       color_type=2,
                                                       transparent=transparent)

                        file_contents = check_idat(file_contents,
                                                   color_type=2,
                                                   bit_depth=bit_depth,
                                                   interlace=interlace,
                                                   img=img)

                        check_iend(file_contents)
Beispiel #29
0
def dcm2png(path, savepathdir):
    lists = os.listdir(path)
    for file in lists:
        print('{} is processing'.format(file))
        dcm_path = os.path.join(path, file)
        dcm = dicom.read_file(dcm_path)
        img = _dcm2png(dcm)
        img = img.astype(np.uint16)
        name = file.split('.')[0] + '.png'
        img_path = os.path.join(savepathdir, name)
        numpngw.write_png(img_path, img)
        print('{} is processed'.format(file))
Beispiel #30
0
    def test_write_png_nbit_grayscale(self):
        # Test the creation of grayscale images for bit depths of 1, 2, 4
        # 8 and 16, with or without a `transparent` color selected.
        np.random.seed(123)
        for filter_type in [0, 1, 2, 3, 4, "heuristic", "auto"]:
            for bitdepth in [1, 2, 4, 8, 16]:
                for transparent in [None, 0]:
                    for interlace in [0, 1]:
                        dt = np.uint16 if bitdepth == 16 else np.uint8
                        maxval = 2**bitdepth
                        sz = (3, 11)
                        img = np.random.randint(0, maxval, size=sz).astype(dt)
                        if transparent is not None:
                            img[2:4, 2:] = transparent

                        f = io.BytesIO()
                        numpngw.write_png(f,
                                          img,
                                          bitdepth=bitdepth,
                                          transparent=transparent,
                                          filter_type=filter_type,
                                          interlace=interlace)

                        file_contents = f.getvalue()

                        file_contents = check_signature(file_contents)

                        file_contents = check_ihdr(file_contents,
                                                   width=img.shape[1],
                                                   height=img.shape[0],
                                                   bit_depth=bitdepth,
                                                   color_type=0,
                                                   interlace=interlace)

                        file_contents = check_text(file_contents,
                                                   b"Creation Time")
                        software = numpngw._software_text().encode('latin-1')
                        file_contents = check_text(file_contents, b"Software",
                                                   software)

                        if transparent is not None:
                            file_contents = check_trns(file_contents,
                                                       color_type=0,
                                                       transparent=transparent)

                        file_contents = check_idat(file_contents,
                                                   color_type=0,
                                                   bit_depth=bitdepth,
                                                   interlace=interlace,
                                                   img=img)

                        check_iend(file_contents)
Beispiel #31
0
def show_image(a):
    # if not uint8 we assume mean = 0 and ranges from [-1..1]
    if a.dtype != np.uint8:
        a += 1.
        a *= 127.5
        a = a.astype(np.uint8)
    png_array = io.BytesIO()
    numpngw.write_png(png_array, a)
    encoded_png_array = base64.b64encode(png_array.getvalue()).decode(
        "utf-8", "strict")
    png_array.close()
    image_seq = '\033]1337;File=[width=auto;height=auto;inline=1]:' + encoded_png_array + '\007'
    print(image_seq)
def generate_pngs(filepath, name):
  r, g, b = get_bands(filepath)
  rn = normalize(r)
  gn = normalize(g)
  bn = normalize(b)
  
  # 16 bit
  rgb16 = numpy.dstack((rn*65535,gn*65535,bn*65535)).astype('uint16')
  write_png(name + "_16.png", rgb16)
  
  # 8 bit
  rgb = numpy.dstack((rn*255, gn*255, bn*255)).astype('uint8')
  write_png(name + "_8.png", rgb)
Beispiel #33
0
def unmerge(path, l):
  try:
    array = uint8_to_uint16(path)
    new = np.empty((l[0], l[1], l[2]), dtype = "uint8")
    for matrix in range(l[0]):
      for list in range(l[1]):
        for element in range(l[2]):
          new[matrix][list][element] = unmerge_number(array[matrix][list][element])
    del array
    q = 'unmerged.png'
    numpngw.write_png(q, new)
    return q
  except KeyboardInterrupt:
    raise SystemExit
Beispiel #34
0
def merge(img1, img2):
  try:
    array1 = uint8_to_uint16(img1)
    array2 = encryptDecrypt(img2)
    for matrix in range(array2.shape[0]):
      for list in range(array2.shape[1]):
        for element in range(array2.shape[2]):
          array1[matrix][list][element] = merge_numbers(array1[matrix][list][element], array2[matrix][list][element])
    del array2
    q = 'merged.png'
    numpngw.write_png(q, array1)
    return q
  except KeyboardInterrupt:
    raise SystemExit
 def compress(self, original_path: str, compressed_path: str, original_file_info=None):
     img = enb.isets.load_array_bsq(
         file_or_path=original_path, image_properties_row=original_file_info)
     
     with tempfile.NamedTemporaryFile(suffix=".png") as tmp_file:
         numpngw.write_png(tmp_file.name, img)
         compression_results = super().compress(original_path=tmp_file.name,
                          compressed_path=compressed_path,
                          original_file_info=original_file_info)
         cr = self.compression_results_from_paths(
             original_path=original_path, compressed_path=compressed_path)
         cr.compression_time_seconds = max(
             0, compression_results.compression_time_seconds)
         return cr
Beispiel #36
0
def process_folder(f):
    global args

    dst = f.replace("_polygons.json", f"_label{args.id_type}s.png")

    # do the conversion
    try:
        json2labelImg(f, dst, args.id_type)
    except:
        tqdm.write("Failed to convert: {}".format(f))
        raise

    if args.instance:
        dst = f.replace("_polygons.json", f"_instance{args.id_type}s.png")

        # do the conversion
        # try:
        json2instanceImg(f, dst, args.id_type)
        # except:
        #     tqdm.write("Failed to convert: {}".format(f))
        #     raise

    if args.color:
        # create the output filename
        dst = f.replace("_polygons.json", f"_labelColors.png")

        # do the conversion
        try:
            json2labelImg(f, dst, 'color')
        except:
            tqdm.write("Failed to convert: {}".format(f))
            raise

    if args.panoptic and args.instance:
        dst = f.replace("_polygons.json", f"_panoptic{args.id_type}s.png")
        seg_anno = f.replace("_polygons.json", f"_label{args.id_type}s.png")
        inst_anno = f.replace("_polygons.json",
                              f"_instance{args.id_type}s.png")

        seg_tail = f"_gtFine_label{args.id_type}s.png"
        inst_tail = f"_gtFine_instance{args.id_type}s.png"
        pan_tail = f"_gtFine_panoptic{args.id_type}s.png"

        seg_img = imread(seg_anno)
        inst_img = imread(inst_anno)
        sh = (seg_img.shape[0], seg_img.shape[1], 2)
        twoch_img = np.zeros(sh, dtype=np.uint16)
        twoch_img[:, :, 0] = seg_img
        twoch_img[:, :, 1] = inst_img
        write_png(seg_anno.replace(seg_tail, pan_tail), twoch_img)
    def test_write_png_RGB(self):
        # Test creation of RGB images (color type 2), with and without
        # a `transparent` color selected, and with bit depth 8 and 16.
        w = 24
        h = 10
        np.random.seed(12345)
        for filter_type in [0, 1, 2, 3, 4, "heuristic", "auto"]:
            for transparent in [None, (0, 0, 0)]:
                for bit_depth in [8, 16]:
                    for interlace in [0, 1]:
                        dt = np.uint16 if bit_depth == 16 else np.uint8
                        maxval = 2**bit_depth
                        img = np.random.randint(0, maxval,
                                                size=(h, w, 3)).astype(dt)
                        if transparent:
                            img[2:4, 2:4] = transparent

                        f = io.BytesIO()
                        numpngw.write_png(f, img, transparent=transparent,
                                          filter_type=filter_type,
                                          interlace=interlace)

                        file_contents = f.getvalue()

                        file_contents = check_signature(file_contents)

                        file_contents = check_ihdr(file_contents,
                                                   width=w, height=h,
                                                   bit_depth=bit_depth,
                                                   color_type=2,
                                                   interlace=interlace)

                        file_contents = check_text(file_contents,
                                                   b"Creation Time")
                        software = numpngw._software_text().encode('latin-1')
                        file_contents = check_text(file_contents, b"Software",
                                                   software)

                        if transparent:
                            file_contents = check_trns(file_contents,
                                                       color_type=2,
                                                       transparent=transparent)

                        file_contents = check_idat(file_contents, color_type=2,
                                                   bit_depth=bit_depth,
                                                   interlace=interlace,
                                                   img=img)

                        check_iend(file_contents)
    def test_write_png_nbit_grayscale(self):
        # Test the creation of grayscale images for bit depths of 1, 2, 4
        # 8 and 16, with or without a `transparent` color selected.
        np.random.seed(123)
        for filter_type in [0, 1, 2, 3, 4, "heuristic", "auto"]:
            for bitdepth in [1, 2, 4, 8, 16]:
                for transparent in [None, 0]:
                    for interlace in [0, 1]:
                        dt = np.uint16 if bitdepth == 16 else np.uint8
                        maxval = 2**bitdepth
                        sz = (3, 11)
                        img = np.random.randint(0, maxval, size=sz).astype(dt)
                        if transparent is not None:
                            img[2:4, 2:] = transparent

                        f = io.BytesIO()
                        numpngw.write_png(f, img, bitdepth=bitdepth,
                                          transparent=transparent,
                                          filter_type=filter_type,
                                          interlace=interlace)

                        file_contents = f.getvalue()

                        file_contents = check_signature(file_contents)

                        file_contents = check_ihdr(file_contents,
                                                   width=img.shape[1],
                                                   height=img.shape[0],
                                                   bit_depth=bitdepth,
                                                   color_type=0,
                                                   interlace=interlace)

                        file_contents = check_text(file_contents,
                                                   b"Creation Time")
                        software = numpngw._software_text().encode('latin-1')
                        file_contents = check_text(file_contents, b"Software",
                                                   software)

                        if transparent is not None:
                            file_contents = check_trns(file_contents,
                                                       color_type=0,
                                                       transparent=transparent)

                        file_contents = check_idat(file_contents, color_type=0,
                                                   bit_depth=bitdepth,
                                                   interlace=interlace,
                                                   img=img)

                        check_iend(file_contents)
Beispiel #39
0
    def save(self, filename, **kwargs):
        """

        :param filename:
        :param kwargs:
        :return:
        @type filename: str
        """
        self.filename = filename
        if 'format' in kwargs:
            image_format = kwargs['format']
        elif getFromWriterRegistry(self.mode.lower()):
            image_format = self.mode.lower()
        else:
            image_format = 'TIFF' if filename.lower().endswith('tif') or filename.lower().endswith('tiff') else 'PNG'
        newargs = dict(kwargs)
        newargs['format'] = image_format
        img_array = self.image_array
        file_writer = getFromWriterRegistry(image_format.lower())
        if file_writer is not None:
            file_writer(filename, img_array)
            return
        if self.mode == 'F':
            img_array = img_array * 256
            img_array = img_array.astype('uint8')
        if img_array.dtype == 'uint8' and self.mode == 'L':
            if image_format == 'PDF':
                self.convert('RGB').save(filename, **newargs)
            else:
                Image.fromarray(img_array).save(filename, **newargs)
            return
        newargs.pop('format')
        if image_format == 'PNG':
            if img_array.dtype == 'uint16':
               write_png(filename, img_array)
               return
            elif self.mode not in ('RGB','RGBA','L','LA'):
                img_array = ImageWrapper(img_array.astype('uint8')).convert('RGB').image_array
            Image.fromarray(img_array.astype('uint8')).save(filename, **newargs)
        elif image_format not in ['TIFF','TIF']:
            Image.fromarray(img_array.astype('uint8')).save(filename, **newargs)
        else:
            imsave(filename, img_array, **tiff_masssage_args(**newargs))
        if os.path.exists(filename):
            with image_lock:
                image_cache[filename] = (self, os.stat(filename).st_mtime)
Beispiel #40
0
    def test_write_png_with_alpha(self):
        # Test creation of grayscale+alpha and RGBA images (color types 4
        # and 6, resp.), with bit depths 8 and 16.
        w = 25
        h = 15
        np.random.seed(12345)
        for filter_type in [0, 1, 2, 3, 4, "heuristic", "auto"]:
            for color_type in [4, 6]:
                num_channels = 2 if color_type == 4 else 4
                for bit_depth in [8, 16]:
                    for interlace in [0, 1]:
                        dt = np.uint8 if bit_depth == 8 else np.uint16
                        sz = (h, w, num_channels)
                        img = np.random.randint(0, 2**bit_depth,
                                                size=sz).astype(dt)
                        f = io.BytesIO()
                        numpngw.write_png(f,
                                          img,
                                          filter_type=filter_type,
                                          interlace=interlace)

                        file_contents = f.getvalue()

                        file_contents = check_signature(file_contents)

                        file_contents = check_ihdr(file_contents,
                                                   width=w,
                                                   height=h,
                                                   bit_depth=bit_depth,
                                                   color_type=color_type,
                                                   interlace=interlace)

                        file_contents = check_text(file_contents,
                                                   b"Creation Time")
                        software = numpngw._software_text().encode('latin-1')
                        file_contents = check_text(file_contents, b"Software",
                                                   software)

                        file_contents = check_idat(file_contents,
                                                   color_type=color_type,
                                                   bit_depth=bit_depth,
                                                   interlace=interlace,
                                                   img=img)

                        check_iend(file_contents)
Beispiel #41
0
    def test_write_png_sbit(self):
        # Test creation of sBIT chunks for color_type 0 and 2.
        w = 7
        h = 5
        np.random.seed(123)
        for bit_depth in [8, 16]:
            for size in [(h, w), (h, w, 3)]:
                maxval = 2**bit_depth
                dt = np.uint16 if bit_depth == 16 else np.uint8
                img = np.random.randint(0, maxval, size=size).astype(dt)

                color_type = 0 if len(size) == 2 else 2

                sbit = (bit_depth - 1,)
                if color_type == 2:
                    sbit = sbit * 3

                f = io.BytesIO()
                numpngw.write_png(f, img, sbit=sbit)

                file_contents = f.getvalue()

                file_contents = check_signature(file_contents)


                file_contents = check_ihdr(file_contents, width=w, height=h,
                                           bit_depth=bit_depth,
                                           color_type=color_type,
                                           interlace=0)

                file_contents = check_text(file_contents, b"Creation Time")
                software = numpngw._software_text().encode('latin-1')
                file_contents = check_text(file_contents, b"Software",
                                           software)

                file_contents = check_sbit(file_contents, sbit=sbit,
                                           color_type=color_type)

                file_contents = check_idat(file_contents,
                                           color_type=color_type,
                                           bit_depth=bit_depth,
                                           interlace=0,
                                           img=img)

                check_iend(file_contents)
Beispiel #42
0
def numpy_to_png(im, fp_out, bitdepth=8):
    from numpngw import write_png
    assert isinstance(im, (np.ndarray, np.generic))
    # ensure extenion

    Fp = Path(fp_out).with_suffix(".png")
    logging.info(f"saving array to png..{Fp}")
    # Image.fromarray(img_as_ubyte(im)).save(fp_out)

    if bitdepth == 8:
        im = img_as_ubyte(im)
    elif bitdepth == 16:
        im = img_as_uint(im)  # accept float
    else:
        raise Exception(f"unupported bitdepth {bitdepth}")

    write_png(Fp, im, bitdepth=bitdepth)
    logging.debug(f"...saved: {fp_out}")
    def test_write_png_with_alpha(self):
        # Test creation of grayscale+alpha and RGBA images (color types 4
        # and 6, resp.), with bit depths 8 and 16.
        w = 25
        h = 15
        np.random.seed(12345)
        for filter_type in [0, 1, 2, 3, 4, "heuristic", "auto"]:
            for color_type in [4, 6]:
                num_channels = 2 if color_type == 4 else 4
                for bit_depth in [8, 16]:
                    for interlace in [0, 1]:
                        dt = np.uint8 if bit_depth == 8 else np.uint16
                        sz = (h, w, num_channels)
                        img = np.random.randint(0, 2**bit_depth,
                                                size=sz).astype(dt)
                        f = io.BytesIO()
                        numpngw.write_png(f, img, filter_type=filter_type,
                                          interlace=interlace)

                        file_contents = f.getvalue()

                        file_contents = check_signature(file_contents)

                        file_contents = check_ihdr(file_contents,
                                                   width=w, height=h,
                                                   bit_depth=bit_depth,
                                                   color_type=color_type,
                                                   interlace=interlace)

                        file_contents = check_text(file_contents,
                                                   b"Creation Time")
                        software = numpngw._software_text().encode('latin-1')
                        file_contents = check_text(file_contents, b"Software",
                                                   software)

                        file_contents = check_idat(file_contents,
                                                   color_type=color_type,
                                                   bit_depth=bit_depth,
                                                   interlace=interlace,
                                                   img=img)

                        check_iend(file_contents)
    def test_write_png_max_chunk_len(self):
        # Create an 8-bit grayscale image.
        w = 250
        h = 150
        max_chunk_len = 500
        img = np.random.randint(0, 256, size=(h, w)).astype(np.uint8)
        f = io.BytesIO()
        numpngw.write_png(f, img, max_chunk_len=max_chunk_len)

        file_contents = f.getvalue()

        file_contents = check_signature(file_contents)

        file_contents = check_ihdr(file_contents,
                                   width=w, height=h,
                                   bit_depth=8, color_type=0, interlace=0)

        file_contents = check_text(file_contents, b"Creation Time")
        file_contents = check_text(file_contents, b"Software",
                                   numpngw._software_text().encode('latin-1'))

        zstream = b''
        while True:
            chunk_type, chunk_data, file_contents = next_chunk(file_contents)
            if chunk_type != b"IDAT":
                break
            self.assertEqual(chunk_type, b"IDAT")
            zstream += chunk_data
            self.assertLessEqual(len(chunk_data), max_chunk_len)
        data = zlib.decompress(zstream)
        b = np.fromstring(data, dtype=np.uint8)
        lines = b.reshape(h, w + 1)
        img2 = lines[:, 1:].reshape(h, w)
        assert_array_equal(img2, img)

        # Check the IEND chunk; chunk_type and chunk_data were read
        # in the loop above.
        self.assertEqual(chunk_type, b"IEND")
        self.assertEqual(chunk_data, b"")

        self.assertEqual(file_contents, b"")
Beispiel #45
0
import numpy as np
from numpngw import write_png


# Example 3
#
# Create a 16-bit RGB image, with (0, 0, 0) indicating a transparent pixel.

# Create some interesting data.
w = 32
nrows = 3*w
ncols = 5*w
kernel = np.exp(-np.linspace(-2, 2, 35)**2)
kernel = kernel/kernel.sum()
np.random.seed(123)
x = np.random.randn(nrows, ncols, 3)
x = np.apply_along_axis(lambda z: np.convolve(z, kernel, mode='same'), 0, x)
x = np.apply_along_axis(lambda z: np.convolve(z, kernel, mode='same'), 1, x)

# Convert to 16 bit unsigned integers.
z = (65535*((x - x.max())/x.ptp())).astype(np.uint16)

# Create two squares containing (0, 0, 0).
z[w:2*w, w:2*w] = 0
z[w:2*w, -2*w:-w] = 0

# Write the PNG file, and indicate that (0, 0, 0) should be transparent.
write_png('example3.png', z, transparent=(0, 0, 0))
Beispiel #46
0
	er1 += end_point_error(gth,out)
	#out = cv2.resize(out1,gth.shape[::-1])
	er2 += D1_error(gth,out,(3,0.05))
	print 'batch:%04d' %i

time2 = time.time()
er1 /= N
er2 /= N

print r'EPE:',er1
print r'D1:', er2
print time2 - time1, 'seconds'

out = np.uint16(out*256)
gth = np.uint16(gth*256) 
numpngw.write_png('gthk.png',gth)
numpngw.write_png('outk.png',out)

get outk.png gthk.png
net.forward()
gth = net.blobs['scaled_disp_gt'].data[0,0,:,:]
out = net.blobs['predict_disp0'].data[0,0,:,:]
out[out<0] = 0
out = np.uint16(out*256)
gth = np.uint16(gth*256) 
numpngw.write_png('gthk.png',gth)
numpngw.write_png('outk.png',out)
'''
net.blobs['img0'].reshape(1,3,384, 1280) 
net.blobs['img1'].reshape(1,3,384, 1280)
net.blobs['scaled_disp_gt'].reshape(1,1,384, 1280)
Beispiel #47
0
import numpy as np
from numpngw import write_png


# Example 2
#
# Create a 1-bit grayscale image.

mask = np.zeros((48, 48), dtype=np.uint8)
mask[:2, :] = 1
mask[:, -2:] = 1
mask[4:6, :-4] = 1
mask[4:, -6:-4] = 1
mask[-16:, :16] = 1
mask[-32:-16, 16:32] = 1

write_png('example2.png', mask, bitdepth=1)
    def test_write_png_8bit_RGB_palette(self):
        for interlace in [0, 1]:
            for transparent in [None, (0, 1, 2)]:
                for bitdepth in [1, 2, 4, 8]:
                    w = 13
                    h = 4
                    ncolors = min(2**bitdepth, w*h)
                    idx = np.arange(w*h).reshape(h, w) % ncolors
                    colors = np.arange(ncolors*3).reshape(ncolors, 3)
                    colors = colors.astype(np.uint8)
                    img = colors[idx]
                    f = io.BytesIO()
                    numpngw.write_png(f, img, use_palette=True,
                                      transparent=transparent,
                                      interlace=interlace,
                                      bitdepth=bitdepth)

                    file_contents = f.getvalue()

                    file_contents = check_signature(file_contents)

                    file_contents = check_ihdr(file_contents,
                                               width=img.shape[1],
                                               height=img.shape[0],
                                               bit_depth=bitdepth,
                                               color_type=3,
                                               interlace=interlace)

                    file_contents = check_text(file_contents, b"Creation Time")
                    software = numpngw._software_text().encode('latin-1')
                    file_contents = check_text(file_contents, b"Software",
                                               software)

                    # Check the PLTE chunk.
                    chunk_type, chunk_data, file_contents = \
                        next_chunk(file_contents)
                    self.assertEqual(chunk_type, b"PLTE")
                    p = np.fromstring(chunk_data,
                                      dtype=np.uint8).reshape(-1, 3)
                    n = ncolors*3
                    expected = np.arange(n, dtype=np.uint8).reshape(-1, 3)
                    assert_array_equal(p, expected)

                    if transparent is not None:
                        file_contents = check_trns(file_contents,
                                                   color_type=3,
                                                   transparent=transparent,
                                                   palette=p)

                    # Check the IDAT chunk.
                    chunk_type, chunk_data, file_contents = \
                        next_chunk(file_contents)
                    self.assertEqual(chunk_type, b"IDAT")
                    decompressed = zlib.decompress(chunk_data)
                    stream = np.fromstring(decompressed, dtype=np.uint8)
                    height, width = img.shape[:2]
                    img2 = stream_to_array(stream, width, height, color_type=3,
                                           bit_depth=bitdepth,
                                           interlace=interlace)
                    expected = idx
                    assert_array_equal(img2, expected)

                    check_iend(file_contents)
Beispiel #49
0
import numpy as np
from numpngw import write_png


# Example 4
#
# Create an 8-bit indexed RGB image that uses a palette.

img_width = 300
img_height = 200
img = np.zeros((img_height, img_width, 3), dtype=np.uint8)

np.random.seed(222)
for _ in range(40):
    width = np.random.randint(5, img_width // 5)
    height = np.random.randint(5, img_height // 5)
    row = np.random.randint(5, img_height - height - 5)
    col = np.random.randint(5, img_width - width - 5)
    color = np.random.randint(80, 256, size=2)
    img[row:row+height, col:col+width, 1:] = color

write_png('example4.png', img, use_palette=True)
Beispiel #50
0
import numpy as np
from numpngw import write_png


# Example 1
#
# Create an 8-bit RGB image.

img = np.zeros((80, 128, 3), dtype=np.uint8)

grad = np.linspace(0, 255, img.shape[1])

img[:16, :, :] = 127
img[16:32, :, 0] = grad
img[32:48, :, 1] = grad[::-1]
img[48:64, :, 2] = grad
img[64:, :, :] = 127

write_png('example1.png', img)