예제 #1
0
파일: train.py 프로젝트: thouis/sparselabel
def load_image_volume(image_directory, h5, extension='tif'):
    filenames = sorted(glob.glob(os.path.join(image_directory, '*.' + extension)))
    size = imread.imread(filenames[0]).shape
    images = h5.require_dataset('images', shape=((len(filenames),) + size), dtype=np.uint8)
    for idx, f in enumerate(filenames):
        images[idx, ...] = imread.imread(f)
    return images
예제 #2
0
def load_images(image_dir):
    filenames = sorted(glob.glob(os.path.join(image_dir, '*.tif')))
    for f in filenames:
        imread.imread(f)
    ims = [imread.imread(f) for f in filenames]
    print("read images", len(ims))
    return ims
예제 #3
0
def append_images(orig):
    def scale(out, sz):
        subprocess.check_call(["convert", orig,
                               "-scale", sz,
                               out])
        subprocess.check_call(["convert", out,
                               "-background", "none",
                               "-gravity", "center",
                               "-extent", sz,
                               out])
    def append(f1, f2):
        subprocess.check_call(["convert",
                               f1, f2,
                               "-append", f1])

    tmpdir = tempfile.mkdtemp()
    out_16 = os.path.join(tmpdir, "16.png")
    out_32 = os.path.join(tmpdir, "32.png")
    scale(out_16, "16x16")
    scale(out_32, "32x32")
    append("images/flags16.png", out_16)
    append("images/flags32.png", out_32)

    # sanity checks
    sh16 = imread.imread("images/flags16.png").shape
    assert sh16[0] % 16 == 0
    assert sh16[1] == 16
    sh32 = imread.imread("images/flags32.png").shape
    assert sh32[0] % 32 == 0
    assert sh32[1] == 32
    return sh16[0] - 16, sh32[0] - 32
예제 #4
0
def append_images(orig):
    def scale(out, sz):
        subprocess.check_call(["convert", orig, "-scale", sz, out])
        subprocess.check_call([
            "convert", out, "-background", "none", "-gravity", "center",
            "-extent", sz, out
        ])

    def append(f1, f2):
        subprocess.check_call(["convert", f1, f2, "-append", f1])

    tmpdir = tempfile.mkdtemp()
    out_16 = os.path.join(tmpdir, "16.png")
    out_32 = os.path.join(tmpdir, "32.png")
    scale(out_16, "16x16")
    scale(out_32, "32x32")
    append("images/flags16.png", out_16)
    append("images/flags32.png", out_32)

    # sanity checks
    sh16 = imread.imread("images/flags16.png").shape
    assert sh16[0] % 16 == 0
    assert sh16[1] == 16
    sh32 = imread.imread("images/flags32.png").shape
    assert sh32[0] % 32 == 0
    assert sh32[1] == 32
    return sh16[0] - 16, sh32[0] - 32
예제 #5
0
def test_horizontal_predictor():
    im = imread(file_path('arange512_16bit.png'))
    im2 = im.copy()
    imsave(_filename, im, opts={'tiff:horizontal-predictor': True})
    assert np.all(im == im2)

    im3 = imread(_filename)
    assert np.all(im == im3)
예제 #6
0
def test_horizontal_predictor():
    im = imread(file_path('arange512_16bit.png'))
    im2 = im.copy()
    imsave(_filename, im, opts={'tiff:horizontal-predictor': True})
    assert np.all(im == im2)

    im3 = imread(_filename)
    assert np.all(im == im3)
예제 #7
0
def parse_segments_from_outlines(outline_path, dataset):
    if dataset == 'BBBC006':
        import imread
        masks = imread.imread(outline_path)
        rles = []
        for idx in range(1, masks.max() + 1):
            rles.append(mask_util.encode(np.asarray(masks == idx, dtype=np.uint8, order='F')))
        return rles

    if dataset == 'BBBC020':
        out_dir, prefix = outline_path.rsplit('/', 1)
        files = os.listdir(out_dir)
        masks = []
        for f_name in files:
            if prefix in f_name:
                m = imageio.imread(os.path.join(out_dir, f_name))
                m[m > 0] = 1

                m = scipy.ndimage.zoom(m, (0.4, 0.4), order=1)
                masks.append(m)
        rles = []
        for m in masks:
            rles.append(mask_util.encode(np.asarray(m, dtype=np.uint8, order='F')))
        return rles

    if dataset == '2009_ISBI_2DNuclei':
        import imread
        outlines = imread.imread(outline_path)
    else:
        outlines = imageio.imread(outline_path)

    if dataset == 'cluster_nuclei' or dataset == '2009_ISBI_2DNuclei':
        outlines[outlines != [255, 0, 0]] = 0
        imgray = cv2.cvtColor(outlines, cv2.COLOR_RGB2GRAY)
        ret, thresh = cv2.threshold(imgray, 0, 255, 0)
    elif dataset == 'BBBC007':
        thresh = np.asarray(outlines, np.uint8)
    elif dataset == 'BBBC018':
        thresh = outlines

    thresh[0, :] = 1
    thresh[:, 0] = 1
    thresh[:, -1] = 1
    thresh[-1, :] = 1

    im, contours, hierarchy = cv2.findContours(thresh,
                                               cv2.RETR_CCOMP,
                                               cv2.CHAIN_APPROX_SIMPLE)

    seg = [[float(x) for x in c.flatten()] for c in contours]
    seg = [cont for cont in seg if len(cont) > 4]  # filter all polygons that are boxes
    if not seg:
        return []

    rles = mask_util.frPyObjects(seg, outlines.shape[0], outlines.shape[1])
    rles = dedupe_contours(rles, dataset)
    return rles
예제 #8
0
파일: train.py 프로젝트: thouis/sparselabel
def load_label_volume(label_directory, num_labels, h5):
    filenames = [os.path.join(label_directory, 'labels_{:06d}.png'.format(idx + 1)) for idx in range(num_labels)]
    size = imread.imread(filenames[0]).shape
    labels = h5.require_dataset('labels', shape=((len(filenames),) + size), dtype=np.int32)
    for idx, f in enumerate(filenames):
        if os.path.exists(f):
            labels[idx, ...] = imread.imread(f)

    # use skimage to label individual objects
    relabel = skimage.measure.label(labels[...], background=0)
    labels[...] = relabel
    return labels
예제 #9
0
파일: test_jpeg.py 프로젝트: thouis/imread
def test_quality():
    def pixel_diff(a):
        return np.mean(np.abs(a.astype(float) - data))

    data = np.arange(256*256*3)
    data %= 51
    data = data.reshape((256,256,3))
    data = data.astype(np.uint8)
    imsave('imread_def.jpg', data)
    imsave('imread_def91.jpg', data, opts={'jpeg:quality': 91} )
    readback    = imread('imread_def.jpg')
    readback91  = imread('imread_def91.jpg')
    assert pixel_diff(readback91) < pixel_diff(readback)
예제 #10
0
파일: test_jpeg.py 프로젝트: qbbian/imread
def test_quality():
    def pixel_diff(a):
        return np.mean(np.abs(a.astype(float) - data))

    data = np.arange(256 * 256 * 3)
    data %= 51
    data = data.reshape((256, 256, 3))
    data = data.astype(np.uint8)
    imsave("imread_def.jpg", data)
    imsave("imread_def91.jpg", data, opts={"jpeg:quality": 91})
    readback = imread("imread_def.jpg")
    readback91 = imread("imread_def91.jpg")
    assert pixel_diff(readback91) < pixel_diff(readback)
예제 #11
0
 def _read_png_matrix(cls, name):
     print "Reading LUT image: %s" % name
     return imread.imread(
         AppDirectoriesFinder().storages.get(
             'django_instakit').path(join(
                 'django_instakit', 'lut',
                 "%s.png" % name)))
예제 #12
0
파일: test_tiff.py 프로젝트: vitasam/imread
def test_read_back_colour_16bit():
    im = np.random.random((16, 8, 3)) * 65535.0
    im = im.astype(np.uint16)
    imsave(_filename, im)
    im2 = imread(_filename)
    assert im.shape == im2.shape
    assert np.all(im == im2)
예제 #13
0
def readxcf(xcf_filename, formatstr, _flags):
    '''
    im = readxcf(xcf_filename, formatstr)

    Returns a numpy array with the (flattened) XCF file.

    Depends on `xcf2png` being available.

    Parameters
    ----------
    xcf_filename : str
        Filename

    formatstr : str
        format. Must be 'xcf'

    Returns
    -------
    im : ndarray
    '''
    from os import system, unlink
    from tempfile import NamedTemporaryFile
    if formatstr != 'xcf':
        raise ValueError('imread.imread.readxcf: Format string must be \'xcf\'')

    N = NamedTemporaryFile(suffix='.png')
    output = system('xcf2png %s >%s' % (xcf_filename,N.name))
    if output:
        raise OSError('imread.readxcf: xcf format is only supported through the xcf2png utility, which imread could not run')
    return imread.imread(N.name, return_metadata=True)
예제 #14
0
def readxcf(xcf_filename, formatstr):
    '''
    im = readxcf(xcf_filename, formatstr)

    Returns a numpy array with the (flattened) XCF file.

    Depends on `xcf2png` being available.

    Parameters
    ----------
    xcf_filename : str
        Filename

    formatstr : str
        format. Must be 'xcf'

    Returns
    -------
    im : ndarray
    '''
    from os import system, unlink
    from tempfile import NamedTemporaryFile
    if formatstr != 'xcf':
        raise ValueError(
            'imread.imread.readxcf: Format string must be \'xcf\'')

    N = NamedTemporaryFile(suffix='.png')
    output = system('xcf2png %s >%s' % (xcf_filename, N.name))
    if output:
        raise OSError(
            'imread.readxcf: xcf format is only supported through the xcf2png utility, which imread could not run'
        )
    return imread.imread(N.name)
예제 #15
0
def test_indexed():
    im = imread(file_path('py-installer-indexed.bmp'))
    assert np.any(im)
    assert im.shape == (352, 162, 3)
    assert np.any(im[:, :, 0])
    assert np.any(im[:, :, 1])
    assert np.any(im[:, :, 2])
예제 #16
0
def test_read_back_colour():
    im = np.arange(256).astype(np.uint8).reshape((32, -1))
    im = np.dstack([im, im * 0, 255 - im])
    imsave(_filename, im)
    im2 = imread(_filename)
    assert im.shape == im2.shape
    assert np.all(im == im2)
예제 #17
0
파일: special.py 프로젝트: fish2000/imread
def readxcf(xcf_filename, formatstr, _flags):
    '''
    im = readxcf(xcf_filename, formatstr)

    Returns a numpy array with the (flattened) XCF file.

    Depends on `xcf2png` being available.

    Parameters
    ----------
    xcf_filename : str
        Filename

    formatstr : str
        format. Must be 'xcf'

    Returns
    -------
    im : ndarray
    '''
    from os import system
    from tempfile import NamedTemporaryFile
    from distutils.spawn import find_executable as which

    if formatstr != 'xcf':
        raise ValueError('imread.imread.readxcf: Format string must be \'xcf\'')

    if not which('xcf2png'):
        raise OSError('imread.readxcf: xcf format is only supported through the xcf2png utility, which imread could not find')

    N = NamedTemporaryFile(suffix='.png')
    output = system('xcf2png %s >%s' % (xcf_filename,N.name))
    if output:
        raise OSError('imread.readxcf: xcf format is only supported through the xcf2png utility, which failed to run')
    return imread.imread(N.name, return_metadata=True)
예제 #18
0
파일: test_bmp.py 프로젝트: DomiR/imread
def test_indexed():
    im = imread('imread/tests/data/py-installer-indexed.bmp')
    assert np.any(im)
    assert im.shape == (352, 162, 3)
    assert np.any(im[:,:,0])
    assert np.any(im[:,:,1])
    assert np.any(im[:,:,2])
예제 #19
0
파일: test_jpeg.py 프로젝트: qbbian/imread
def test_jpeg():
    f = np.arange(64 * 16).reshape((64, 16))
    f %= 16
    f = f.astype(np.uint8)
    imsave(_filename, f, "jpeg")
    g = imread(_filename).squeeze()
    assert np.mean(np.abs(f.astype(float) - g)) < 1.0
예제 #20
0
def test_read_back_colour():
    im = np.arange(256).astype(np.uint8).reshape((32,-1))
    im = np.dstack([im, im*0, 255-im])
    imsave(_filename, im)
    im2 = imread(_filename)
    assert im.shape == im2.shape
    assert np.all(im == im2)
예제 #21
0
 def changeindexcombo5(self):
     """méthode exécutée en cas de changement d'affichage du combo5
     """
     #self.combo5.clear()#surtout pas!!
     #quel le parent?
     #recup l'item actif de combo4
     print "combo5 cur Index", self.combo5.currentIndex()
     #identifier le node correspondant4
     ## suppossons que ce soit==self.combo1.currentIndex()
     ##parent est un etree.Element, son nom devrait être l'item courant de combo1
     #parent=self.node5[self.combo5.currentIndex()]
     #demander ses enfants,
     ##demander le nom des enfants
     #        childrenlist=self.GetChildrenName(parent)
     #        print "from changeindex combo5",childrenlist
     #        self.combo5.addItems(QtCore.QStringList(childrenlist))
     pathto=os.path.join(str(self.combo1.currentText()),\
                         str(self.combo2.currentText()),\
                         str(self.combo3.currentText()),\
                         str(self.combo4.currentText()),\
                         str(self.combo5.currentText()))
     self.lbl.setText(str(pathto))
     workdir = "/home/simon/MFISH/"
     ndimage = imread.imread(workdir + str(pathto))
     convert = qnd.array2qimage(ndimage[::2, ::2], normalize=True)
     qpix = QtGui.QPixmap(convert)
     image = QtGui.QLabel(self)
     image.setPixmap(qpix)
     #posit = QtGui.QGridLayout()
     self.posit.addWidget(image, 2, 0)
     self.setLayout(self.posit)
     self.setWindowTitle('Cascade Menus')
     self.show()
예제 #22
0
파일: test_bmp.py 프로젝트: thouis/imread
def test_indexed():
    im = imread('imread/tests/data/py-installer-indexed.bmp')
    assert np.any(im)
    assert im.shape == (352, 162, 3)
    assert np.any(im[:, :, 0])
    assert np.any(im[:, :, 1])
    assert np.any(im[:, :, 2])
예제 #23
0
def main(pth):
    from pylire.compatibility.utils import timecheck
    from pylire.process.channels import RGB
    from imread import imread
    
    (R, G, B) = RGB(imread(pth))
    
    '''@timecheck
    def timetest_scalar(R, G, B):
        histogram_keys = opponent_histogram_scalar_keys(R, G, B)
        hh = histogram_normalize(
            histogram_count(
                histogram_keys))
        print "\tvectorized scalar func:"
        print oh_str(h)
        print ""
        print "\tbinary hash:"
        print oh_bithash_str(h)
        print "\t"
        
        return hh
    
    timetest_scalar(R, G, B)
    '''
    
    @timecheck
    def timetest_vector(R, G, B):
        histogram_key_vec = opponent_histogram_key_vector_ORIG(R, G, B)
        hh = histogram_normalize(
            histogram_count(
                histogram_key_vec))
        
        print "\tpure-python vector func:"
        print oh_str(hh)
        print ""
        print "\tbinary hash:"
        print oh_bithash_str(hh)
        print "\t"
        
        return hh
    
    timetest_vector(R, G, B)
    
    @timecheck
    def timetest_vector(R, G, B):
        histogram_key_vec_inline = opponent_histogram_key_vector(R, G, B)
        hh = histogram_normalize(
            histogram_count(
                histogram_key_vec_inline))
        
        print "\tnative (inlined and cythonized) vector func:"
        print oh_str(hh)
        print ""
        print "\tbinary hash:"
        print oh_bithash_str(hh)
        print "\t"
        
        return hh
        
    timetest_vector(R, G, B)
예제 #24
0
 def changeindexcombo4(self):
     """méthode exécutée en cas de changement d'affichage du combo4
     """
     self.combo5.clear()
     print "combo4 cur Index", self.combo4.currentIndex()
     self.node4 = self.node3[self.combo3.currentIndex()].getchildren()
     parent = self.node4[self.combo4.currentIndex()]
     #demander ses enfants,
     ##demander le nom des enfants
     childrenlist = self.GetChildrenName(parent)
     self.combo5.addItems(QtCore.QStringList(childrenlist))
     pathto=os.path.join(str(self.combo1.currentText()),\
                         str(self.combo2.currentText()),\
                         str(self.combo3.currentText()),\
                         str(self.combo4.currentText()),\
                         str(self.combo5.currentText()))
     self.lbl.setText(str(pathto))
     workdir = "/home/simon/MFISH/"
     ndimage = imread.imread(workdir + str(pathto))
     convert = qnd.array2qimage(ndimage[::2, ::2], normalize=True)
     qpix = QtGui.QPixmap(convert)
     image = QtGui.QLabel(self)
     image.setPixmap(qpix)
     #posit = QtGui.QGridLayout()
     self.posit.addWidget(image, 2, 0)
     self.setLayout(self.posit)
     self.setWindowTitle('Cascade Menus')
     self.show()
예제 #25
0
def load_letter(folder, min_num_images):
    image_files = os.listdir(folder)
    dataset = np.ndarray(shape=(len(image_files), image_size, image_size))
    print(folder)

    num_images = 0
    for image in image_files:
        image_file = os.path.join(folder, image)
        try:
            image_data = (imread.imread(image_file, as_grey=True).astype(float)
                          - pixel_depth / 2) / pixel_depth
            if image_data.shape != (image_size, image_size):
                raise Exception("Unexpected Image Shape %s" % image_data.shape)
            dataset[num_images, :, :] = image_data
            num_images += 1
        except (IOError, RuntimeError) as e:
            print("Could not read file :", image_file, " : ", e,
                  "Skipping this file.")

    dataset = dataset[0:num_images, :, :]
    if num_images < min_num_images:
        raise Exception("Count of images less than expected: %d < %d" %
                        (num_images, min_num_images))

    print("Full Dataset Tensor: ", dataset.shape)
    print("Mean : ", np.mean(dataset))
    print("Standard Deviation: ", np.std(dataset))
    return dataset
예제 #26
0
    def changeindexcombo5(self):
        """méthode exécutée en cas de changement d'affichage du combo5
        """
        #self.combo5.clear()#surtout pas!!
        #quel le parent?
        #recup l'item actif de combo4
        print "combo5 cur Index",self.combo5.currentIndex()
        #identifier le node correspondant4
        ## suppossons que ce soit==self.combo1.currentIndex()
        ##parent est un etree.Element, son nom devrait être l'item courant de combo1
        #parent=self.node5[self.combo5.currentIndex()]
        #demander ses enfants,
        ##demander le nom des enfants
#        childrenlist=self.GetChildrenName(parent)
#        print "from changeindex combo5",childrenlist
#        self.combo5.addItems(QtCore.QStringList(childrenlist))
        pathto=os.path.join(str(self.combo1.currentText()),\
                            str(self.combo2.currentText()),\
                            str(self.combo3.currentText()),\
                            str(self.combo4.currentText()),\
                            str(self.combo5.currentText()))
        self.lbl.setText(str(pathto))
        workdir="/home/simon/MFISH/"
        ndimage=imread.imread(workdir+str(pathto))
        convert=qnd.array2qimage(ndimage[::2,::2],normalize=True)
        qpix = QtGui.QPixmap(convert)
        image = QtGui.QLabel(self)
        image.setPixmap(qpix)
        #posit = QtGui.QGridLayout()
        self.posit.addWidget(image, 2, 0)
        self.setLayout(self.posit)
        self.setWindowTitle('Cascade Menus')
        self.show()
예제 #27
0
 def changeindexcombo4(self):
     """méthode exécutée en cas de changement d'affichage du combo4
     """
     self.combo5.clear()
     print "combo4 cur Index",self.combo4.currentIndex()
     self.node4=self.node3[self.combo3.currentIndex()].getchildren()
     parent=self.node4[self.combo4.currentIndex()]
     #demander ses enfants,
     ##demander le nom des enfants
     childrenlist=self.GetChildrenName(parent)
     self.combo5.addItems(QtCore.QStringList(childrenlist))
     pathto=os.path.join(str(self.combo1.currentText()),\
                         str(self.combo2.currentText()),\
                         str(self.combo3.currentText()),\
                         str(self.combo4.currentText()),\
                         str(self.combo5.currentText()))
     self.lbl.setText(str(pathto))
     workdir="/home/simon/MFISH/"
     ndimage=imread.imread(workdir+str(pathto))
     convert=qnd.array2qimage(ndimage[::2,::2],normalize=True)
     qpix = QtGui.QPixmap(convert)
     image = QtGui.QLabel(self)
     image.setPixmap(qpix)
     #posit = QtGui.QGridLayout()
     self.posit.addWidget(image, 2, 0)
     self.setLayout(self.posit)
     self.setWindowTitle('Cascade Menus')
     self.show()
예제 #28
0
파일: test_jpeg.py 프로젝트: thouis/imread
def test_jpeg():
    f = np.arange(64*16).reshape((64,16))
    f %= 16
    f = f.astype(np.uint8)
    imsave(_filename, f, 'jpeg')
    g = imread(_filename).squeeze()
    assert np.mean(np.abs(f.astype(float)-g)) < 1.
예제 #29
0
def _hela_load_function(path):
    from imread import imread
    import numpy as np
    im = imread(path)
    if im.dtype == np.bool_:
        return im.astype(np.uint8)
    return im
예제 #30
0
def loadimgs(path, n=0):

    X = []
    y = []
    cat_dict = {}
    lang_dict = {}
    curr_y = n

    for alphabet in os.listdir(path):

        print("loading alphabet: " + alphabet)
        lang_dict[alphabet] = [curr_y, None]
        alphabet_path = os.path.join(path, alphabet)

        for letter in os.listdir(alphabet_path):
            cat_dict[curr_y] = (alphabet, letter)
            category_images = []
            letter_path = os.path.join(alphabet_path, letter)

            for filename in os.listdir(letter_path):
                image_path = os.path.join(letter_path, filename)
                image = imread(image_path)
                category_images.append(image)
                y.append(curr_y)
            try:
                X.append(np.stack(category_images))
            except ValueError as e:
                print(e)
                print("error - category_images: ", category_images)

            lang_dict[alphabet][1] = curr_y
            curr_y += 1
    y = np.vstack(y)
    X = np.stack(X)
    return X, y, lang_dict
예제 #31
0
def make_neume_chart(times, pitches, basename):

    # background_file = 'images/neumy A.bmp'
    # background_file = 'images/neumy text 3.bmp'
    # background_file = 'images/neumy neumy neumy.bmp'
    # background_file = 'images/neumy uni.bmp'
    background_file = 'images/big uni.bmp'
    manuscript = imread.imread(background_file)

    # small version: works
    # my_dpi = 30
    # plt.figure(figsize=(577/my_dpi,216/my_dpi), dpi=my_dpi, frameon=False)
    # plt.imshow(manuscript)
    # note_start = 100
    # note_end = 520
    # pitch_offset = 220
    # pitch_scale = 2.5
    # # plt.plot([note_start, note_start],[100,150],'r')
    # # plt.plot([note_end, note_end],[100,150],'r')

    my_dpi = 72
    plt.figure(figsize=(2401/my_dpi,901/my_dpi), dpi=my_dpi, frameon=False)
    plt.imshow(manuscript)
    note_start = 350
    note_end = 2100
    pitch_offset = 220
    pitch_scale = 8
    # plt.plot([note_start, note_start],[100,500],'r')
    # plt.plot([note_end, note_end],[100,500],'r')

    pitch_time_range = times[-1] - times[0]
    manuscript_time_range = note_end - note_start

    times_scaled = (times - times[0]) * (manuscript_time_range/pitch_time_range) + note_start

    # E (lowest line is pitch value 26)

    # small works
    # pitches_scaled = 136 - (np.array(pitches)-26) * pitch_scale

    pitches_scaled = 565 - (np.array(pitches)-26) * pitch_scale

    # small works
    # plt.plot(times_scaled, pitches_scaled, 'ks', markersize=12)

    plt.plot(times_scaled, pitches_scaled, 'ks', markersize=24)

    # plt.plot([100, 200],[136,136],'r')
    # plt.plot([100, 200],[127,127],'r')

    # plt.show()

    plt.axis([0,2400,900,0])
    plt.axis('off')
    plt.tight_layout()


    # plt.savefig('images/generated/' + basename.replace('csv','png'), dpi=my_dpi * 10)
    plt.savefig('images/generated/' + basename.replace('csv','png'), dpi=my_dpi)
예제 #32
0
파일: test_tiff.py 프로젝트: DomiR/imread
def test_read_back_16():
    np.random.seed(21)
    simple = np.random.random_sample((128,128))
    simple *= 8192
    simple = simple.astype(np.uint16)
    imsave(_filename, simple)
    back = imread(_filename)
    assert np.all(simple == back)
예제 #33
0
def test_read_back_with_metadata():
    simple = np.arange(16*16).reshape((16,16))
    simple = simple.astype(np.uint8)
    meta = b'123qwe'
    imsave(_filename, simple, metadata=meta)
    back,meta_read = imread(_filename, return_metadata=True)
    assert np.all(simple == back)
    assert meta == meta_read
예제 #34
0
def test_read_back_16():
    np.random.seed(21)
    simple = np.random.random_sample((128, 128))
    simple *= 8192
    simple = simple.astype(np.uint16)
    imsave(_filename, simple)
    back = imread(_filename)
    assert np.all(simple == back)
예제 #35
0
def _img():
    if IMG_CACHED[0] is None:
        i = imread.imread("images/gelface.jpg") / 255.0
        i = i[::4, ::4]
        i[0] = 0.0  # ensure we get all black
        i[1] = 1.0  # ensure we get all white
        IMG_CACHED[0] = np.ascontiguousarray(i)
    return IMG_CACHED[0]
예제 #36
0
def test_read_back_with_metadata():
    simple = np.arange(16 * 16).reshape((16, 16))
    simple = simple.astype(np.uint8)
    meta = b'123qwe'
    imsave(_filename, simple, metadata=meta)
    back, meta_read = imread(_filename, return_metadata=True)
    assert np.all(simple == back)
    assert meta == meta_read
예제 #37
0
def nda_from_path(image_file):
    try:
        from imread import imread
    except ImportError:
        from PIL import Image
        import numpy
        return numpy.array(Image.open(image_file))
    else:
        return imread(os.path.abspath(image_file))
예제 #38
0
파일: test_tiff.py 프로젝트: vitasam/imread
def test_imsave_multi():
    im = imread(file_path('arange512_16bit.png'))
    im2 = im[::4, ::4]
    ims = [im, im2]
    imsave_multi(_filename, ims)
    ims2 = imread_multi(_filename)
    assert len(ims) == len(ims2)
    for a, b in zip(ims, ims2):
        assert np.all(a == b)
예제 #39
0
파일: storage.py 프로젝트: 0x68/h5dj
def nda_from_path(image_file):
    try:
        from imread import imread
    except ImportError:
        from PIL import Image
        import numpy
        return numpy.array(Image.open(image_file))
    else:
        return imread(os.path.abspath(image_file))
예제 #40
0
def test_non_carray():
    np.random.seed(87)
    simple = np.random.random_sample((128, 128, 3))
    simple *= 255
    simple = simple.astype(np.uint8)
    simple = simple[32:64, 32::2]
    imsave(_filename, simple, 'png')
    back = imread(_filename)
    assert np.all(simple == back)
예제 #41
0
파일: test_tiff.py 프로젝트: qbbian/imread
def test_imsave_multi():
    im = imread(file_path('arange512_16bit.png'))
    im2 = im[::4, ::4]
    ims = [im, im2]
    imsave_multi(_filename, ims)
    ims2 = imread_multi(_filename)
    assert len(ims) == len(ims2)
    for a,b in zip(ims, ims2):
        assert np.all(a == b)
예제 #42
0
파일: test_png.py 프로젝트: mschuene/imread
def test_non_carray():
    np.random.seed(87)
    simple = np.random.random_sample((128,128,3))
    simple *= 255
    simple = simple.astype(np.uint8)
    simple = simple[32:64,32::2]
    imsave(_filename, simple, 'png')
    back = imread(_filename)
    assert np.all(simple == back)
예제 #43
0
 def compare_with_blob(filename, formatstr):
     from os import path
     filename = path.join(
                     path.dirname(__file__),
                     'data',
                     filename)
     fromfile= imread.imread(filename)
     fromblob = imread_from_blob(open(filename, 'rb').read(), formatstr)
     assert np.all(fromblob == fromfile)
예제 #44
0
def readxcf(xcffilename):
    '''
    img = readxcf(xcf_filename)

    Returns a numpy array with the (flattened) XCF file.
    '''
    from os import unlink
    print 'readxcf(%s)' % xcffilename
    N=tempfile.NamedTemporaryFile(suffix='.png')
    system('xcf2png %s >%s' % (xcffilename,N.name))
    return imread(N.name)
예제 #45
0
파일: test_png.py 프로젝트: mschuene/imread
def test_random():
    np.random.seed(23)
    for i in range(8):
        simple = np.random.random_sample((64,64,3))
        simple *= 255
        simple = simple.astype(np.uint8)
        if i < 3:
            simple[:,:,i] = 0
        imsave(_filename, simple, 'png')
        back = imread(_filename)
        assert np.all(simple == back)
예제 #46
0
def test_random():
    np.random.seed(23)
    for i in range(8):
        simple = np.random.random_sample((64, 64, 3))
        simple *= 255
        simple = simple.astype(np.uint8)
        if i < 3:
            simple[:, :, i] = 0
        imsave(_filename, simple, 'png')
        back = imread(_filename)
        assert np.all(simple == back)
예제 #47
0
def test_image(model):
    yes_no = True
    while yes_no:
        path = input("Please enter the path: ")
        im = imread(path)
        im = im.astype("float32")
        im = im / 255
        pr = model.predict_classes(im.reshape((28, 28, 1, 1)))
        print("Result: ", pr)

        yes_no = True if (input("Would you like to continue? [Y/n] ") == "y"
                          or "Y") else False
예제 #48
0
def open_hsv_image(path):
    rgb = imread.imread(path)
    hsv_image = color.rgb2hsv(rgb)

    hsv_image *= 255
    hsv_image = hsv_image.astype(np.uint8)

    h = hsv_image[:, :, 0]
    s = hsv_image[:, :, 1]
    v = hsv_image[:, :, 2]

    return HsvImage(h=h, s=s, v=v)
예제 #49
0
    def __init__(self, json, dim, flatten=True, rot=''):
        #self.base = json['base']
        self.full = json['full']
        self.tags = json['tags']
        self.base = inferBase(self.full)
        self.filePath = thumbBase(self.base, dim, rot)
        if not os.path.exists(self.filePath):
            raise Exception('file does not exist: %s' % self.filePath)

        self.np_data = imread(self.filePath)
        if flatten:
            self.np_data = np.array(self.np_data).flatten()
        self.np_label = np.array([tag2n(json, t) for t in TAGS])
예제 #50
0
def imread(fname, dtype=None):
    """Load an image from file.

    Parameters
    ----------
    fname : str
        Name of input file

    """
    im = _imread.imread(fname)
    if dtype is not None:
        im = convert(im, dtype)
    return im
예제 #51
0
def imread(fname, dtype=None):
    """Load an image from file.

    Parameters
    ----------
    fname : str
        Name of input file

    """
    im = _imread.imread(fname)
    if dtype is not None:
        im = _convert(im, dtype)
    return im
예제 #52
0
def main(pth):
    from pylire.compatibility.utils import timecheck
    from imread import imread

    ndim = imread(pth)
    #ndim_shape = shape_from_image(ndim)

    @timecheck
    def timetest_FDCT_python(ndim_shape):
        FDCT(ndim_shape[0])
        FDCT(ndim_shape[1])
        FDCT(ndim_shape[2])
        #print(ndim_shape)
        return ndim_shape

    @timecheck
    def timetest_FDCT_cython(ndim_shape):
        C_FDCT(ndim_shape[0])
        C_FDCT(ndim_shape[1])
        C_FDCT(ndim_shape[2])
        #print(ndim_shape)
        return ndim_shape

    ns1 = shape_from_image(ndim)
    out_py = timetest_FDCT_python(ns1)
    ns2 = shape_from_image(ndim)
    out_cy = timetest_FDCT_cython(ns2)
    print("")
    print("RESULTS EQUAL:")
    print(numpy.equal(out_py, out_cy))
    print("")

    @timecheck
    def timetest_color_layout_shape(ndim):
        shape = shape_from_image(ndim)
        print("image shape:")
        print(ndim.shape)
        print("")
        # print("image 'shape':")
        # print(shape)
        # print("")
        print("image 'shape' shape:")
        print(shape.shape)
        print("")

    #timetest_color_layout_shape(ndim)

    @timecheck
    def timetest_color_layout(ndim):
        (cY, cCb, cCr) = color_layout(ndim)
예제 #53
0
def old_main():
    
    #imfuckingshowalready = lambda mx: Image.fromarray(mx).show()

    old_identity = AppDirectoriesFinder().storages.get(
           'django_instakit').path(join(
               'django_instakit', 'lut', 'identity.png'))

    im_old_identity = imread.imread(old_identity)
    im_identity = numpy.zeros_like(im_old_identity)

    for bx in xrange(0, 8):
        for by in xrange(0, 8):
            for r in xrange(0, 64):
                for g in xrange(0, 64):
                    im_identity[
                        int(g + by * 64),
                        int(r + bx * 64)] = numpy.array((
                            int(r * 255.0 / 63.0 + 0.5),
                            int(g * 255.0 / 63.0 + 0.5),
                                int((bx + by * 8.0) * 255.0 / 63.0 + 0.5)),
                                dtype=numpy.uint8)
    
    print "THE OLD: %s, %s, %s" % (
        im_old_identity.size, im_old_identity.shape,
        str(im_old_identity.dtype))
    #print im_old_identity
    print ""
    
    print "THE NEW: %s, %s, %s" % (
        im_identity.size, im_identity.shape,
        str(im_identity.dtype))
    #print im_identity
    print ""
    
    
    
    print "THE END: %s" % bool(im_old_identity.shape == im_identity.shape)
    #print im_old_identity == im_identity
    
    #imfuckingshowalready(im_identity)
    #imfuckingshowalready(im_old_identity)
    
    pil_im_old_identity = Image.fromarray(im_old_identity)
    pil_im_old_identity.save('/tmp/im_old_identity.jpg',
        format="JPEG")
    
    pil_im_identity = Image.fromarray(im_identity)
    pil_im_identity.save('/tmp/im_identity.jpg',
        format="JPEG")
예제 #54
0
파일: tests.py 프로젝트: 0x68/h5dj
 def test_store_image(self):
     #img = random.choice(os.listdir(settings.testimages))
     
     print('', file=sys.stderr)
     for img in os.listdir(settings.testimages):
         
         print("Reading image:", img, file=sys.stderr)
         nda = imread.imread(os.path.join(settings.testimages, img))
         self.h5.save('%s.nda' % img, nda)
         
         print("Repacking HDF5 storage...", file=sys.stderr)
         self.h5._repack()
         nda2 = self.h5.open('/%s.nda' % img)
         self.assertEqual(nda.sum(), nda2.sum())
         self.assertTrue(numpy.equal(nda, nda2).all())
예제 #55
0
    def test_store_image(self):
        #img = random.choice(os.listdir(settings.testimages))

        print('', file=sys.stderr)
        for img in os.listdir(settings.testimages):

            print("Reading image:", img, file=sys.stderr)
            nda = imread.imread(os.path.join(settings.testimages, img))
            self.h5.save('%s.nda' % img, nda)

            print("Repacking HDF5 storage...", file=sys.stderr)
            self.h5._repack()
            nda2 = self.h5.open('/%s.nda' % img)
            self.assertEqual(nda.sum(), nda2.sum())
            self.assertTrue(numpy.equal(nda, nda2).all())
예제 #56
0
    def on_post(self, req, resp, **kwargs):
        image = req.get_param('imagefile')
        raw = image.file.read()
        filename = image.filename
        say('read file:', filename, 'len:', len(raw))

        tmpfile = tempfile.mktemp()
        say('writing to file %s' % tmpfile)
        with open(tmpfile, 'wb') as tmp:
            tmp.write(raw)
            tmp.close()
            data = np.array([imread(tmpfile)])
            say('upload numpy shape: %s' % str(data.shape))
            os.remove(tmpfile)

        if self.model is None:
            say('on_get, loading model')
            self.model = loadModel()
            say('on_get, loaded model')

        # verify the shape of the data
        # FIXME: this assumes unflattened data for 'mnist' model from ml-keras-plates.py
        # If it ever tries to run on flattened data, the below will need to be smarter
        if len(data.shape) != 4 or self.width != data.shape[
                1] or self.height != data.shape[2] or data.shape[3] != 3:
            logger.debug('data dimensions', len(data.shape), data.shape[1],
                         data.shape[2], data.shape[3])
            msg = 'expect %dx%d image size, got shape %s' % (
                self.width, self.height, str(data.shape))
            logger.error('tag resource post:', msg)
            raise falcon.HTTPError(falcon.HTTP_400, msg)

        try:
            #faulthandler.dump_traceback_later(4, repeat=True)
            predicts = self.model.predict(data)
        except:
            print('EXCEPTION in predicts')
            traceback.print_exc()
            raise falcon.HTTPError(falcon.HTTP_500, 'internal error')

        say('ran predictions: %s' % str(predicts))
        colors = ['blue', 'gray', 'white']
        say(', '.join(
            ['%s=%f' % (colors[i], predicts[0][i]) for i in range(0, 3)]))

        body = {'tags': [n2c(predicts[0])]}
        resp.body = json.dumps(body)
        say('returning predictions %s' % str(resp.body))
예제 #57
0
def open_lab_image(path):
    # The 1 tells openCV imread to get rgb channels
    rgb = imread.imread(path)
    lab_image = color.rgb2lab(rgb)

    # NOTE the maximum values of l, a, b are 100, +/- 128, +/- 128
    lab_image[:, :, 0] *= (2.55)
    lab_image[:, :, 1] += 128.0
    lab_image[:, :, 2] += 128.0

    # Convert to 8bit so algorithms can work with it easily
    lab_8bit = lab_image.astype(np.uint8)
    return LabImage(
        l=lab_8bit[:, :, 0],
        a=lab_8bit[:, :, 1],
        b=lab_8bit[:, :, 2]
    )
예제 #58
0
def main(pth):
    from pylire.compatibility.utils import timecheck
    from pylire.process.channels import RGB
    from imread import imread
    
    im = imread(pth)
    (R, G, B) = RGB(im)
    
    @timecheck
    def timetest_cythonized_HOG(ndim):
        hogg = hog(ndim)
        print("Cythonized HOG() function:")
        print_array_info(hogg)
        print("")
    
    timetest_cythonized_HOG(im)
    
    '''