def chip_images():
    print("\nStarting to chip the xView dataset.\n")
    thechips = []
    theclasses = []
    thecoords = []
    thecoords, thechips, theclasses = get_labels()
    per = 1
    X_data = []
    files2 = glob.glob ("/home/ubuntu/8x8_chips/*.tif")#                     Change this to ur own directory
    files = glob.glob ("/home/ubuntu/downsampling_testing/*.tif")#                     Change this to ur own directory
    for myFile in files:
        t = 0
        print('\nChipping image at this location: ', myFile)
        image = cv2.imread (myFile)
        #X_data.append (image) #                                                         https://stackoverflow.com/questions/37747021/create-numpy-array-of-images
        chipped_img, chipped_box, chipped_classes = wv.chip_image(img = image, coords = thecoords, classes=theclasses, shape=(8, 8))
        numberOfChips = chipped_img.shape[0]
        print("This image created %d chips." % chipped_img.shape[0]) 
        while t < numberOfChips:
            #print(t + 1)
            os.chdir(r"/home/ubuntu/8x8_chips") #       Change this to ur own directory
            mh.imsave('%d.tif' % per, chipped_img[t])
            os.chdir(r"/home/ubuntu/") #                     Change this to ur own directory
            t += 1
            per += 1
    def resample(self, sample_distance_m = 1.5):
        '''Resample the image at every 1.5 meters using a nearest-neighbor approach.
        This filters out "standing still" portions of each traverse, and makes the
        standard deviation convolutions span consistent distances.  Save the file
        when finished.'''
        infilename  = self.img_filename
        outfilename = self.img_filename_resampled
        corobject = GPR_Coords(self.corfilename)

        # First, concentrate on the points themselves, from the corfile.
        trace_resamples_i = corobject.resample(verbose=False)

        # Read data
        traces = self.img_data(fignum=1) # Use the de-striped (but not stddev) image

        print os.path.split(infilename)[-1], traces.shape, "-->", len(trace_resamples_i)
        resampled_traces = numpy.empty([traces.shape[0], len(trace_resamples_i)], dtype=traces.dtype)

        # i refers to the new (resampled) trace index
        # j refers to the old (original) trace index
        for i,old_tracenum in enumerate(trace_resamples_i):
            j = old_tracenum - 1
            resampled_traces[:,i] = traces[:,j]

        print "Writing", os.path.split(outfilename)[-1]
        mahotas.imsave(outfilename, resampled_traces)

        return
def create_fullContour_labels():
    for purpose in ['train','validate','test']:
        img_search_string = '/media/vkaynig/Data1/Cmor_paper_data/labels/' + purpose + '/*.tif'
        img_files = sorted( glob.glob( img_search_string ) )
        
        for img_index in xrange(np.shape(img_files)[0]):
            print 'reading image ' + img_files[img_index] + '.'
            label = mahotas.imread(img_files[img_index])
            
            #membranes = np.logical_and(label[:,:,0]==0, label[:,:,1]==255)
            boundaries = label == -1
            boundaries[0:-1,:] = np.logical_or(boundaries[0:-1,:], np.diff(label, axis=0)!=0)
            boundaries[:,0:-1] = np.logical_or(boundaries[:,0:-1], np.diff(label, axis=1)!=0)

            membranes = np.logical_or(boundaries, label[:,:]==0) 

            shrink_radius=5
            y,x = np.ogrid[-shrink_radius:shrink_radius+1, -shrink_radius:shrink_radius+1]
            disc = x*x + y*y <= (shrink_radius ** 2)
            non_membrane = 1-mahotas.dilate(membranes, disc)

            img_file_name = os.path.basename(img_files[img_index])[:-4]+ '.tif'         
            outputPath = '/media/vkaynig/Data1/Cmor_paper_data/labels/'
            
            print 'writing image: ' + img_file_name
            mahotas.imsave(outputPath + 'background_fullContour/' + purpose + '/' + img_file_name, np.uint8(non_membrane*255))
            mahotas.imsave(outputPath + 'membranes_fullContour/' + purpose + '/' + img_file_name, np.uint8(membranes*255))
def normalize_all_input(img_search_string = '/media/vkaynig/NewVolume/IAE_ISBI2012/images/images/*.tif'):
    img_files = sorted( glob.glob( img_search_string ) )
    for fileName in img_files:
        img = mahotas.imread(fileName)
        clahe.clahe(img, img, 2.0)
 #       img = normalizeImage(img, saturation_level=0.05)
        mahotas.imsave(fileName, np.uint8(img))
def create_fullContour_labels():
    #img_search_string = '/media/vkaynig/NewVolume/IAE_ISBI2012/fullContours/I*_train.tif'
    img_search_string = '/media/vkaynig/NewVolume/Cmor_paper_data/labels/*.tif'
    img_files = sorted(glob.glob(img_search_string))

    for img_index in xrange(np.shape(img_files)[0]):
        print 'reading image ' + img_files[img_index] + '.'
        label = mahotas.imread(img_files[img_index])

        #membranes = np.logical_and(label[:,:,0]==0, label[:,:,1]==255)
        membranes = label[:, :] == 0

        shrink_radius = 5
        y, x = np.ogrid[-shrink_radius:shrink_radius + 1,
                        -shrink_radius:shrink_radius + 1]
        disc = x * x + y * y <= (shrink_radius**2)
        non_membrane = 1 - mahotas.dilate(membranes, disc)

        #fileName = "/media/vkaynig/NewVolume/IAE_ISBI2012/fullContours/"
        fileName = "/media/vkaynig/NewVolume/Cmor_paper_data/labels/"
        fileName_label = fileName + (
            img_files[img_index])[52:58] + "_fullContour.tif"
        fileName_background = fileName + (
            img_files[img_index])[52:58] + "_background.tif"

        print 'writing image' + fileName_label
        mahotas.imsave(fileName_label, np.uint8(membranes * 255))
        mahotas.imsave(fileName_background, np.uint8(non_membrane * 255))
示例#6
0
 def __init__(self, name):
     super(ImageThreshold, self).__init__(name)
     self._gray_image     = mh.colors.rgb2gray(self._image, dtype=np.uint8)
     self._otsu_thresh    = 0
     self._rc_thresh      = 0
     self._gaussian_image = None
     mh.imsave("threshold-base.jpeg", self._image)
def write_image (output_path, data, image_num=0, downsample=1):
    if downsample != 1:
        data = np.float32(mahotas.imresize(data, downsample))
    maxdata = np.max(data)
    mindata = np.min(data)
    normdata = (np.float32(data) - mindata) / (maxdata - mindata)
    mahotas.imsave(output_path, np.uint16(normdata * 65535))
示例#8
0
    def view(array,
             color=True,
             large=False,
             crop=False,
             text=None,
             no_axis=True,
             file=''):

        if large:
            figsize = (10, 10)
        else:
            figsize = (3, 3)

        fig = plt.figure(figsize=figsize)

        if crop:
            array = mh.croptobbox(array)

        if text:
            text = '\n\n\n' + str(text)
            fig.text(0, 1, text)

        if no_axis:
            plt.axis('off')

        if color:
            plt.imshow(Util.colorize(array), picker=True)
            iii = Util.colorize(array)
        else:
            plt.imshow(array, cmap='gray', picker=True)
            iii = array

        if file != '':
            mh.imsave(file, iii.astype(np.uint8))
示例#9
0
def write_image(output_path, data, image_num=0, downsample=1):
    if downsample != 1:
        data = np.float32(mahotas.imresize(data, downsample))
    maxdata = np.max(data)
    mindata = np.min(data)
    normdata = (np.float32(data) - mindata) / (maxdata - mindata)
    mahotas.imsave(output_path, np.uint16(normdata * 65535))
 def output_image (data, layer, index, unpad_by, image_num=0, downsample=1):
     data = data[unpad_by:data.shape[0]-unpad_by,unpad_by:data.shape[1]-unpad_by]
     if downsample != 1:
         data = np.float32(mahotas.imresize(data, downsample))
     maxdata = np.max(data)
     mindata = np.min(data)
     normdata = (np.float32(data) - mindata) / (maxdata - mindata)
     mahotas.imsave(output_path + '/{0:04d}_classify_output_layer{1}_{2}.tif'.format(image_num, layer, index), np.uint16(normdata * 65535))
示例#11
0
def processImage(im):
	imb = m.overlay(im)
	mahotas.imsave("before.png",imb)
	print imb.max()
	f = FingerProcess()
	b3 = f.process(im)
	imgout = m.overlay(im,b3)

	mahotas.imsave("lol.png", imgout)
示例#12
0
def save_image(pathpart1, pathpart2, imagefile):
    """
    Method for GUI display, save an image somewhere
    :param path: where to save the image
    :param imagefile: the actual image
    """

    joined_path = join_path(pathpart1, pathpart2)
    mahotas.imsave(joined_path, imagefile)
示例#13
0
文件: image.py 项目: tomachalek/marg
def save_greyscale(path, image):
    out = []
    for i in range(len(image)):
        row = []
        for j in range(len(image[i])):
            row.append((np.uint8(image[i][j]), np.uint8(image[i][j]), np.uint8(image[i][j])))
        out.append(row)
    out = np.array(out)
    mahotas.imsave(path, out)
示例#14
0
def volume_to_folder(data, outp, ext='.tif', typ='float', min_digit=5):
    """ Outputs the given volume of data into the path. Extension is 'tif' by default
    and output type 'float' """
    create_dir(outp)
    digits = max(len(str(data.shape[0])), min_digit)
    for i in range(0, data.shape[0]):
        print('Saving image {}'.format(str(i)))
        to_save = data[i, ...].astype(typ)
        mh.imsave(os.path.join(outp, str(i).zfill(digits) + ext), to_save)
def normalize_all_input(
    img_search_string='/media/vkaynig/NewVolume/IAE_ISBI2012/images/images/*.tif'
):
    img_files = sorted(glob.glob(img_search_string))
    for fileName in img_files:
        img = mahotas.imread(fileName)
        clahe.clahe(img, img, 2.0)
        #       img = normalizeImage(img, saturation_level=0.05)
        mahotas.imsave(fileName, np.uint8(img))
示例#16
0
def processImage(im):
    imb = m.overlay(im)
    mahotas.imsave("before.png", imb)
    print imb.max()
    f = FingerProcess()
    b3 = f.process(im)
    imgout = m.overlay(im, b3)

    mahotas.imsave("lol.png", imgout)
示例#17
0
文件: image.py 项目: tomachalek/marg
def save_greyscale(path, image):
    out = []
    for i in range(len(image)):
        row = []
        for j in range(len(image[i])):
            row.append((np.uint8(image[i][j]), np.uint8(image[i][j]),
                        np.uint8(image[i][j])))
        out.append(row)
    out = np.array(out)
    mahotas.imsave(path, out)
 def output_image(data, layer, index, unpad_by, image_num=0, downsample=1):
     data = data[unpad_by:data.shape[0] - unpad_by,
                 unpad_by:data.shape[1] - unpad_by]
     if downsample != 1:
         data = np.float32(mahotas.imresize(data, downsample))
     maxdata = np.max(data)
     mindata = np.min(data)
     normdata = (np.float32(data) - mindata) / (maxdata - mindata)
     mahotas.imsave(
         output_path + '/{0:04d}_classify_output_layer{1}_{2}.tif'.format(
             image_num, layer, index), np.uint16(normdata * 65535))
示例#19
0
    def readfile_process_on_click(self):
        # Get the path choosed by the user""

        self.path = self.pathchooserinput_3.cget('path')

        # show the path
        if self.path:
            tkMessageBox.showinfo('You choosed', str(self.path))

            # get the file name and exclude the rest of the path
            matchedpattern = [x.start()
                              for x in re.finditer(str(os.sep), self.path)]
            matchedpattern1 = [x.start()
                               for x in re.finditer(r'[.]', self.path)]
            # construct the file name
            self.getFIleName = str(
                self.path[matchedpattern[-1] + 1:  matchedpattern1[-1]])
            self.getFIleName = path.join(path.expanduser(
                '~'), 'Documents', self.getFIleName)

            self.segmentPreview_dir = path.join(
                self.getFIleName, 'segment preview')
            self.rawimg_dir = path.join(self.getFIleName, 'raw files')

            self.getFIleName = self.getFIleName
            if os.path.exists(self.getFIleName) is False:
                os.makedirs(self.getFIleName)
                os.makedirs(self.rawimg_dir)
                os.makedirs(self.segmentPreview_dir)

            # Read input data files
            self.frames, self.timestamp = Filesprocessor.readFile(
                self.path, str(self.rawimg_dir), self.progressdialog)

            # now display a sample of the input data to the panel
            tmp_img = self.frames[0]

            resized = cv2.resize(tmp_img, (600, 350))

            if os.path.exists(path.join(self.getFIleName, 'displayImg.gif')):
                os.remove(path.join(self.getFIleName, 'displayImg.gif'))

            mahotas.imsave(path.join(self.getFIleName,
                                     'displayImg.gif'), resized)
            # image1 = img2.open(path.join(self.getFIleName, 'displayImg.gif'))

            image1 = tk.PhotoImage(
                file=str(path.join(self.getFIleName, 'displayImg.gif')))
            root.image1 = image1
            _ = self.convax1.create_image(300, 185, image=image1)
示例#20
0
def save_as_random_color_img(_dataarr, filepath):
    rows, cols = _dataarr.shape
    re = np.zeros((rows, cols, 3),dtype=np.uint8)
    colormap = dict()
    colormap[0.0] = [0, 0, 0]
    for row in range(rows):
        for col in range(cols):
            if _dataarr[row][col] in colormap:
                re[row, col, :] = colormap[_dataarr[row][col]]
            else:
                color = [random.randint(0, 255),random.randint(0, 255),random.randint(0, 255)]
                re[row, col, :] = color
                colormap[_dataarr[row][col]] = color
    mahotas.imsave(filepath, re)
示例#21
0
def merge_dataset(folder, histories, thresh, outp):
    """ Thresholds images by merging all supervoxels up to a given threshold 
    :param folder: Folder containing superpixel images
    :param histories: Folder containing the corresponding merge tree histories
    :param thresh: Merge threshold up to which merge regions
    :param outp: Folder where to store resulting images 
    """ 
    dataio.create_dir(outp)
    # Read superpixels and histories
    sps = dataio.FileReader(folder).extract_files()
    hists = dataio.FileReader(histories, exts=['.txt', '.dat', '.data']).extract_files()

    for (s, h) in zip(sps, hists):
        img = merge_superpixels(s, h, thresh)
        name, ext = os.path.splitext(s)
        mh.imsave(os.path.join(outp, os.path.basename(name) + ext), img.astype(float))
def test_upload(request):
    file_object = request.FILES['foto']
    file_name = file_object.name
    nama_gambar = "001_01.jpg"
    with open("ladun/data_pengujian/" + nama_gambar, "wb+") as f:
        for chunk in file_object.chunks():
            f.write(chunk)
    img_uji = mahotas.imread("ladun/data_pengujian/" + nama_gambar)
    img_uji = img_uji[:, :, 0]
    img_uji = mahotas.gaussian_filter(img_uji, 1)
    img_uji = (img_uji > img_uji.mean())
    radius = 10
    mahotas.imsave('ladun/data_zernike/' + nama_gambar, img_uji)
    value_zernike = mahotas.features.zernike_moments(img_uji, radius)
    value_to_list = value_zernike.tolist()
    context = {'nama_file': file_name, 'nilai_zernike': value_to_list}
    return JsonResponse(context, safe=False)
示例#23
0
def get_chips():
    print("\nStarting to chip the xView dataset.\n")
    thechips = []
    theclasses = []
    thecoords = []
    thecoords, thechips, theclasses = get_labels()
    per = 1
    X_data = []
    files2 = glob.glob("/media/root/New Volume/chipped_images1/*.tif"
                       )  #                     Change this to ur own directory
    files = glob.glob("/media/root/New Volume/*.tif"
                      )  #                     Change this to ur own directory
    for myFile in files:
        t = 0
        print('\nChipping image at this location: ', myFile)
        image = cv2.imread(myFile)
        #X_data.append (image) #                                                         https://stackoverflow.com/questions/37747021/create-numpy-array-of-images
        chipped_img, chipped_box, chipped_classes = wv.chip_image(
            img=image, coords=thecoords, classes=theclasses, shape=(256, 256))
        numberOfChips = chipped_img.shape[0]
        print("This image created %d chips." % chipped_img.shape[0])
        while t < numberOfChips:
            #print(t + 1)
            os.chdir(r"/media/root/New Volume/chipped_images1"
                     )  #       Change this to ur own directory
            mh.imsave('%d.tif' % per, chipped_img[t])
            os.chdir(r"/media/root/New Volume"
                     )  #                     Change this to ur own directory
            t += 1
            per += 1

    os.chdir(r"/media/root/New Volume/chipped_images1"
             )  #        Change this to ur own directory
    for myFile in files2:
        chipimage = mh.imread(myFile)
        X_data.append(chipimage)

    npchipped = np.array(
        [np.array(Image.open(myFile)) for myFile in files2]
    )  ### This puts all of the images in to one nparray, ( i think the block of code above does the same thing)
    #                                                                   https://stackoverflow.com/questions/39195113/how-to-load-multiple-images-in-a-numpy-array

    npchipped2 = np.array(
        X_data)  #  nchipped2 is the numpy array, I use it down below
    #npchipped and npchipped are the same
    return npchipped2, numberOfChips
示例#24
0
    def subtract_horizontal_mean_transform(self):
        '''This helps "destripe" the image from horizontal stripes that still exist
        after the REFLEXW de-wow filter is applied.  It is important to get rid of these
        stripes in order not to have them affect our measurements.  Problem is, this
        "smooths out" sections of the data that would otherwise be noisy enough to NOT
        be ice lenses, such as the surface snow.  What combination of filters needs to be
        applied to detect both?  However, for now, keep it a simple mean subtraction.

        This function takes the base image, subtracts the mean, and saves it as a secondary processed image.'''
        self.open_image()

        trace_means = numpy.mean(self.traces,axis=1)
        traces_mean_corrected = numpy.copy(self.traces)
        for i in range(self.traces.shape[0]):
            traces_mean_corrected[i,:] = self.traces[i,:] - trace_means[i]

        print "Saving", os.path.split(self.img_filename_2)[1]
        mahotas.imsave(self.img_filename_2, traces_mean_corrected)
def create_membrane_and_background_images():
    for purpose in ['train', 'validate', 'test']:
        #img_search_string = '/media/vkaynig/NewVolume/IAE_ISBI2012/ground_truth/' + purpose + '/*.tif'
        img_search_string = '/media/vkaynig/NewVolume/Cmor_paper_data/labels/' + purpose + '/*.tif'
        #        img_gray_search_string = '/media/vkaynig/NewVolume/IAE_ISBI2012/images/' + purpose + '/*.tif'
        #        img_gray_search_string = '/media/vkaynig/NewVolume/Cmor_paper_data/images/' + purpose + '/*.tif'

        img_files = sorted(glob.glob(img_search_string))
        #        img_gray_files = sorted( glob.glob( img_gray_search_string ) )

        for img_index in xrange(np.shape(img_files)[0]):
            print 'reading image ' + img_files[img_index] + '.'
            label_img = mahotas.imread(img_files[img_index])

            #            gray_img =  mahotas.imread(img_gray_files[img_index])
            boundaries = label_img == 0
            #            boundaries = label_img == -1
            boundaries[0:-1, :] = np.logical_or(
                boundaries[0:-1, :],
                np.diff(label_img, axis=0) != 0)
            boundaries[:,
                       0:-1] = np.logical_or(boundaries[:, 0:-1],
                                             np.diff(label_img, axis=1) != 0)
            boundaries = 1 - boundaries

            shrink_radius = 1
            y, x = np.ogrid[-shrink_radius:shrink_radius + 1,
                            -shrink_radius:shrink_radius + 1]
            disc = x * x + y * y <= (shrink_radius**2)
            background = mahotas.erode(boundaries, disc) + 1

            membranes = 1 - background

            img_file_name = os.path.basename(img_files[img_index])
            #outputPath = '/media/vkaynig/NewVolume/IAE_ISBI2012/labels/'
            outputPath = '/media/vkaynig/NewVolume/Cmor_paper_data/labels/'

            print 'writing image' + img_file_name
            mahotas.imsave(
                outputPath + 'background/' + purpose + '/' + img_file_name,
                np.uint8(background * 255))
            mahotas.imsave(
                outputPath + 'membranes/' + purpose + '/' + img_file_name,
                np.uint8(membranes * 255))
示例#26
0
    def save_as_image(patch):

        figsize = (2, 2)

        for s in patch.keys():

            if type(patch[s]) == type(np.zeros((1, 1))) and patch[s].ndim == 2:
                # fig = plt.figure(figsize=figsize)
                # plt.imshow(patch[s], cmap='gray')
                # plt.savefig('/tmp/'+s+'.png')
                if patch[s].dtype == np.bool or s == 'dyn_obj':

                    mh.imsave('/tmp/' + s + '.tif',
                              (patch[s] * 255).astype(np.uint8))

                else:

                    mh.imsave('/tmp/' + s + '.tif',
                              (patch[s]).astype(np.uint8))
示例#27
0
def file_writer(filename,
                signal,
                _rescale=True,
                file_format='tif',
                only_view=False,
                **kwds):
    '''Writes data to any format supported by PIL or freeimage if mahotas is 
        installed
        
        Note that only when mahotas and freeimage are installed it is possible 
        to write 16-bit tiff files.
        
        Parameters
        ----------
        filename: str
        signal: a Signal instance
        rescale: bool
            Rescales the data to use the full dynamic range available in the 
            chosen encoding. Note that this operation (obviously) affects the 
            scale of the data what might not always be a good idea
        file_format : str
            The fileformat defined by its extension that is any one supported by 
            PIL of mahotas if installed.  
    '''
    if only_view is True and signal.axes_manager.signal_dimension == 2:
        dc = signal()
    elif only_view is False and len(signal.data.squeeze().shape) == 2:
        dc = signal.data.squeeze()
    else:
        raise IOError("This format also support writing of 2D data")

    if file_format in ('tif', 'tiff') and mahotas_installed is True:

        bits = 16
    else:
        # Only tiff supports 16-bits
        bits = 8

    if _rescale is True:
        dc = rescale(dc, bits)

    imsave(filename, dc.astype('uint%s' % bits))
    print "Image saved"
示例#28
0
    def process(self, im):
        #single pixel restructure element
        elem = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])

        print "starting img process.. binarizing"
        b1 = im > 205  #binarize
        print "removing single pixels"
        #remove single pixels
        singpix = mahotas.morph.hitmiss(b1, elem)
        b1 = (b1 - singpix) > 0
        print "closing holes"
        b1 = m.close_holes(b1)

        print "thinning"
        #b2 = m.thin(b1) #thin
        b2 = self.shitthin(b1)  #thin
        print "pruning"
        b3 = m.thin(b2, m.endpoints('homotopic'), 8)

        #remove single pixels
        singpix = mahotas.morph.hitmiss(b3, elem)
        b3 = b3 - singpix
        b3 = b3 > 0
        struct = np.ndarray((4, 3, 3), dtype=np.uint8)
        struct[0, :, :] = [[1, 2, 1], [0, 1, 0], [0, 1, 0]]
        for i in range(1, 4):
            print "gen %i structure.." % (i)
            struct[i, :, :] = np.rot90(struct[0], i)

        #struct = struct == 1
        print "using struct for branch summing:"
        print struct

        b4 = np.zeros((301, 398), dtype=bool)

        for i in range(0, 4):
            b4 = b4 | mahotas.morph.hitmiss(b3, struct[i])
        b4 = b4 > 0

        imgout = m.overlay(b1, b2, b4)
        mahotas.imsave("thresh.png", imgout)
        return b4
示例#29
0
    def process(self, im):
        # single pixel restructure element
        elem = np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]])

        print "starting img process.. binarizing"
        b1 = im > 205  # binarize
        print "removing single pixels"
        # remove single pixels
        singpix = mahotas.morph.hitmiss(b1, elem)
        b1 = (b1 - singpix) > 0
        print "closing holes"
        b1 = m.close_holes(b1)

        print "thinning"
        # b2 = m.thin(b1) #thin
        b2 = self.shitthin(b1)  # thin
        print "pruning"
        b3 = m.thin(b2, m.endpoints("homotopic"), 8)

        # remove single pixels
        singpix = mahotas.morph.hitmiss(b3, elem)
        b3 = b3 - singpix
        b3 = b3 > 0
        struct = np.ndarray((4, 3, 3), dtype=np.uint8)
        struct[0, :, :] = [[1, 2, 1], [0, 1, 0], [0, 1, 0]]
        for i in range(1, 4):
            print "gen %i structure.." % (i)
            struct[i, :, :] = np.rot90(struct[0], i)

            # struct = struct == 1
        print "using struct for branch summing:"
        print struct

        b4 = np.zeros((301, 398), dtype=bool)

        for i in range(0, 4):
            b4 = b4 | mahotas.morph.hitmiss(b3, struct[i])
        b4 = b4 > 0

        imgout = m.overlay(b1, b2, b4)
        mahotas.imsave("thresh.png", imgout)
        return b4
示例#30
0
def crnnRec(model, converter, im, text_recs):
    index = 0
    for rec in text_recs:
        pt1 = (rec[0], rec[1])
        pt2 = (rec[2], rec[3])
        pt3 = (rec[6], rec[7])
        pt4 = (rec[4], rec[5])
        partImg = dumpRotateImage(
            im, degrees(atan2(pt2[1] - pt1[1], pt2[0] - pt1[0])), pt1, pt2,
            pt3, pt4)
        mahotas.imsave('%s.jpg' % index, partImg)

        image = Image.fromarray(partImg).convert('L')
        #height,width,channel=partImg.shape[:3]
        #print(height,width,channel)
        #print(image.size)

        #image = Image.open('./img/t4.jpg').convert('L')
        scale = image.size[1] * 1.0 / 32
        w = image.size[0] / scale
        w = int(w)
        #print(w)

        transformer = dataset.resizeNormalize((w, 32))
        image = transformer(image).cuda()
        image = image.view(1, *image.size())
        image = Variable(image)
        model.eval()
        preds = model(image)
        _, preds = preds.max(2)
        preds = preds.squeeze(2)
        preds = preds.transpose(1, 0).contiguous().view(-1)
        preds_size = Variable(torch.IntTensor([preds.size(0)]))
        raw_pred = converter.decode(preds.data, preds_size.data, raw=True)
        sim_pred = converter.decode(preds.data, preds_size.data, raw=False)
        #print('%-20s => %-20s' % (raw_pred, sim_pred))
        print index
        print sim_pred.encode('utf-8')
        index = index + 1
示例#31
0
文件: interactive.py 项目: jni/cafe
def compute_spot_stats(image, target, directory):
    if image.dtype != np.uint8:
        channel_mins = image.min(axis=0).min(axis=0)[np.newaxis, np.newaxis, :]
        channel_maxs = image.max(axis=0).max(axis=0)[np.newaxis, np.newaxis, :]
        image = ((image.astype(float) - channel_mins) * 255 /
                 (channel_maxs - channel_mins)).astype(np.uint8)
    v = viewer.ImageViewer(image)
    v += CentroPlugin()
    overlay = v.show()[0][0]
    overlay = seg.relabel_sequential(overlay)[0]
    mask = (overlay == 1)
    objects = nd.label(mask)[0]
    property_names = (['size', 'mean'] +
                      ['quantile-%i' % i for i in [5, 25, 50, 75, 95]])
    props = [np.concatenate(([prop.area, prop.mean_intensity], prop.quantiles))
             for prop in measure.regionprops(objects, intensity_image=target)]
    props = np.array(props)
    fout_txt = os.path.join(directory, 'measure.txt')
    np.savetxt(fout_txt, props, fmt='%.2f', delimiter='\t',
               header='\t'.join(property_names))
    fout_im = os.path.join(directory, 'mask.png')
    mh.imsave(fout_im, 64 * overlay.astype(np.uint8))
示例#32
0
    def seg_display(self, prev_image):

        tmp_pre, segmentationPanel = [], []
        if os.path.exists(path.join(self.segmentPreview_dir, 'SegImage.gif')):
            os.remove(path.join(self.segmentPreview_dir, 'SegImage.gif'))
        mahotas.imsave(path.join(self.segmentPreview_dir,
                                 'frame0.png'), prev_image)
        r = 550.0 / prev_image.shape[1]
        dim = (550, int(prev_image.shape[0] * r))

        # perform the actual resizing of the image and show it
        prev_image = cv2.resize(prev_image, dim, interpolation=cv2.INTER_AREA)

        resized = cv2.resize(prev_image, (600, 350))

        mahotas.imsave(
            path.join(self.segmentPreview_dir, 'SegImage.gif'), resized)

        tmp_pre = tk.PhotoImage(
            file=str(path.join(self.segmentPreview_dir, 'SegImage.gif')))
        root.tmp_pre = tmp_pre
        _ = self.preconvax.create_image(283, 182, image=tmp_pre)
示例#33
0
def file_writer(filename, signal, _rescale = True, file_format='tif', 
                only_view = False, **kwds):
    '''Writes data to any format supported by PIL or freeimage if mahotas is 
        installed
        
        Note that only when mahotas and freeimage are installed it is possible 
        to write 16-bit tiff files.
        
        Parameters
        ----------
        filename: str
        signal: a Signal instance
        rescale: bool
            Rescales the data to use the full dynamic range available in the 
            chosen encoding. Note that this operation (obviously) affects the 
            scale of the data what might not always be a good idea
        file_format : str
            The fileformat defined by its extension that is any one supported by 
            PIL of mahotas if installed.  
    '''
    if only_view is True and signal.axes_manager.signal_dimension == 2:
        dc = signal()
    elif only_view is False and len(signal.data.squeeze().shape) == 2:
        dc = signal.data.squeeze()
    else:
        raise IOError("This format also support writing of 2D data")
        
    if file_format in ('tif', 'tiff') and mahotas_installed is True:
        
        bits = 16    
    else:
        # Only tiff supports 16-bits
        bits = 8
        
    if _rescale is True:
        dc = rescale(dc, bits)

    imsave(filename, dc.astype('uint%s' % bits))
    print "Image saved"
def create_membrane_and_background_images():
    for purpose in ['train','validate','test']:
        #img_search_string = '/media/vkaynig/NewVolume/IAE_ISBI2012/ground_truth/' + purpose + '/*.tif'
        img_search_string = '/media/vkaynig/Data1/Cmor_paper_data/labels/' + purpose + '/*.tif'
#        img_gray_search_string = '/media/vkaynig/NewVolume/IAE_ISBI2012/images/' + purpose + '/*.tif'
#        img_gray_search_string = '/media/vkaynig/NewVolume/Cmor_paper_data/images/' + purpose + '/*.tif'

        img_files = sorted( glob.glob( img_search_string ) )
#        img_gray_files = sorted( glob.glob( img_gray_search_string ) )
        
        for img_index in xrange(np.shape(img_files)[0]):
            print 'reading image ' + img_files[img_index] + '.'
            label_img = mahotas.imread(img_files[img_index])
            
#            gray_img =  mahotas.imread(img_gray_files[img_index])
            #boundaries = label_img==0
            boundaries = label_img == -1
            boundaries[0:-1,:] = np.logical_or(boundaries[0:-1,:], np.diff(label_img, axis=0)!=0)
            boundaries[:,0:-1] = np.logical_or(boundaries[:,0:-1], np.diff(label_img, axis=1)!=0)
            boundaries = 1-boundaries
            
            shrink_radius=10
            y,x = np.ogrid[-shrink_radius:shrink_radius+1, -shrink_radius:shrink_radius+1]
            disc = x*x + y*y <= (shrink_radius ** 2)
            background = boundaries

            membranes = 1-background
            #membranes = boundaries

            background = 1-(mahotas.erode(boundaries, disc) + 1)
            
            img_file_name = os.path.basename(img_files[img_index])
            #outputPath = '/media/vkaynig/NewVolume/IAE_ISBI2012/labels/'
            outputPath = '/media/vkaynig/Data1/Cmor_paper_data/labels/'
            
            print 'writing image' + img_file_name         
            mahotas.imsave(outputPath + 'background_nonDilate/' + purpose + '/' + img_file_name, np.uint8(background*255))
            mahotas.imsave(outputPath + 'membranes_nonDilate/' + purpose + '/' + img_file_name, np.uint8(membranes*255))
def proses_uji(request):
    dataImg = request.POST.get("citraData")
    format, imgstr = dataImg.split(";base64,")
    dataDecode = ContentFile(base64.b64decode(imgstr))
    # imgdata = base64.b64decode(dataImg)
    imgRandom = get_random_string(10)
    nama_gambar = imgRandom + ".png"
    now = datetime.datetime.now()
    with open("ladun/data_pengujian/" + nama_gambar, "wb+") as f:
        for chunk in dataDecode.chunks():
            f.write(chunk)

    # start perhitungan zernike
    data_secret = lsb.reveal("ladun/data_pengujian/" + nama_gambar)
    img_uji = mahotas.imread("ladun/data_pengujian/" + nama_gambar)
    img_uji = img_uji[:, :, 0]
    img_uji = mahotas.gaussian_filter(img_uji, 1)
    img_uji = (img_uji > img_uji.mean())
    radius = 10

    mahotas.imsave('ladun/data_zernike/' + nama_gambar, img_uji)
    value_zernike = mahotas.features.zernike_moments(img_uji, radius)
    value_to_list = value_zernike.tolist()
    citra_save = Pengujian_Citra.objects.create(
        kd_uji=imgRandom,
        nama_pengujian='Pengujian Citra',
        waktu_pengujian=now,
        base_svm_final='0',
        hasil_final=data_secret)
    citra_save.save()
    context = {
        'status': 'sukses',
        'dataCitra': nama_gambar,
        'zernikeValue': value_to_list,
        'secret': data_secret
    }
    return JsonResponse(context, safe=False)
def test_zernike(request):
    file_gambar = 'naskhi.png'
    img = mahotas.imread('ladun/data_latih/' + file_gambar)
    img = img[:, :, 0]
    img = mahotas.gaussian_filter(img, 1)
    img = (img > img.mean())
    kd = "004"
    # radius
    radius = 10
    mahotas.imsave('ladun/data_zernike/' + file_gambar, img)
    # computing zernike moments
    value_zernike = mahotas.features.zernike_moments(img, radius)
    value_to_list = value_zernike.tolist()
    panjang = len(value_to_list)
    awal = 0
    no = 1
    for x in value_to_list:
        awal = awal + x
        d = Nilai_Data_Latih.objects.create(kd_class=kd, node=no, value=awal)
        d.save()
        no += 1

    context = {'status': value_to_list, 'panjang': panjang, 'total': awal}
    return JsonResponse(context, safe=False)
def thresholding():
    img = cv2.imread(path + '.jpg', 0)
    ret, th1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
    th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
                                cv2.THRESH_BINARY,55,4)
    th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                                cv2.THRESH_BINARY,55,4)
    mahotas.imsave(path + '_Binary.jpg', th1)
    enhance_black(path + '_Binary')
    mahotas.imsave(path + '_Mean.jpg', th2)
    enhance_black(path + '_Mean')
    mahotas.imsave(path + '_Guassian.jpg', th3)
    enhance_black(path + '_Guassian')
示例#38
0
def watershed(img):
    # Diminui ruidos
    imgf = ndimage.gaussian_filter(img, 16)
    mahotas.imsave("dnaf.jpeg", imgf)
    rmax = pymorph.regmax(imgf)

    T = mahotas.thresholding.otsu(imgf)
    dist = ndimage.distance_transform_edt(imgf > T)
    dist = dist.max() - dist
    dist -= dist.min()
    dist = dist / float(dist.ptp()) * 255
    dist = dist.astype(np.uint8)
    mahotas.imsave("dist.jpeg", dist)

    seeds, nr_nuclei = ndimage.label(rmax)
    nuclei = pymorph.cwatershed(dist, seeds)
    mahotas.imsave("watershed.jpeg", nuclei)
示例#39
0
img = cv2.cvtColor(img, cv2.cv.CV_BGR2GRAY)
img /= 255

mask = cv2.imread("mask.png")
mask = cv2.cvtColor(mask, cv2.cv.CV_BGR2GRAY)
mask /= 255

print_img(img)
print_img(mask)
new_img = geodesic_dilation(img, mask) * 255
cv2.imwrite("./geodesic_dilation.png", new_img)

# Reconstrucao geodesica
f = np.asarray([0, 0, 1, 3, 3, 7, 7, 7, 7, 5, 2, 1, 1])
g = np.asarray([0, 0, 1, 2, 2, 2, 5, 2, 2, 2, 2, 1, 1])
geodesic_reconstruction_1d(f, g)

# watershed
img = mahotas.imread("dna.jpeg", as_grey=True)
img = img.astype(np.uint8)
# watershed(img)

# skeleton by influence zone (skiz)
img = mahotas.imread("bla.jpeg", as_grey=True)
img = img.astype(np.bool)
skiz = pymorph.skiz(img)
skiz *= 255 / skiz.max()
mahotas.imsave("skiz.png", skiz)
pylab.imshow(skiz)
pylab.show()
示例#40
0
    print '('+str(k)+', '+str(score)+')'
plt.show()
"""
heatmap=[]


x=0
for k in range(15,25):
    for i in range(100):
        heatmap.append([])
    for pad in range(0, 10):
        train_data=knn_trainer_helper.sortClasses(pad,trainPoints, trainimages, 1)
        test_data=knn_trainer_helper.sortClasses(pad,testPoints, testimages, 1)
        
        knn = sklearn.neighbors.KNeighborsClassifier(n_neighbors=k, weights='uniform', algorithm='ball_tree')
        knn.fit(train_data[0], train_data[1])
        test_predict = knn.predict(test_data[0])
        score = sklearn.metrics.accuracy_score(test_data[1], test_predict, normalize=True)
        
        for i in range(100):
            for j in range(100):
                heatmap[x*100+j].append(score*255)
            
        print '('+str(k)+', '+str(pad)+', '+str(score)+")"
    x+=1
plt.gray()
plt.imshow(heatmap)
plt.show()
map = np.matrix(heatmap, dtype=np.uint8, copy=True)
mahotas.imsave('results/heatmap.tif', map)
示例#41
0
def test_as_grey():
    colour = np.arange(16*16*3).reshape((16,16,3))
    imsave(_testimgname, colour.astype(np.uint8))
    c2 = imread(_testimgname, as_grey=True)
    assert len(c2.shape) == 2
    assert c2.shape == colour.shape[:-1]
示例#42
0
from matplotlib import pyplot as plt
import numpy as np
import mahotas as mh
image = mh.imread('../1400OS_10_01.jpeg')
image = mh.colors.rgb2gray(image)
im8 = mh.gaussian_filter(image,8)
im16 = mh.gaussian_filter(image,16)
im32 = mh.gaussian_filter(image,32)
h,w = im8.shape
canvas = np.ones((h,3*w+256), np.uint8)
canvas *= 255
canvas[:,:w] = im8
canvas[:,w+128:2*w+128] = im16
canvas[:,-w:] = im32
mh.imsave('../1400OS_10_05+.jpg', canvas[:,::2])

im32 = mh.stretch(im32)
ot32 = mh.otsu(im32)
mh.imsave('../1400OS_10_06+.jpg', (im32 > ot32).astype(np.uint8)*255)
示例#43
0
import mahotas as mh
from jugfile import method1
from matplotlib import cm
import numpy as np

im = mh.imread('images/dna-21.jpg')
mh.imsave('image_stretched.jpeg', mh.stretch(im.astype(float)**.01))
m1 = method1.f('images/dna-21.jpg', 2)
m1 = m1.astype(np.uint8)
color = ((cm.rainbow(m1.astype(float)/m1.max())[:,:,:3]).reshape(m1.shape+(3,)))
color[m1 == 0] = (0,0,0)
mh.imsave('image_method1.jpeg', mh.stretch(color))

ref = mh.imread('references/dna-21.png')
color = ((cm.rainbow(ref.astype(float)/ref.max())[:,:,:3]).reshape(m1.shape+(3,)))
color[ref == 0] = (0,0,0)
mh.imsave('image_reference.jpeg', mh.stretch(color))


示例#44
0
            for ele in range(0, 4):
                b = b | mahotas.morph.hitmiss(b, structleft[ele])

                b = b | mahotas.morph.hitmiss(b, structright[ele])
            print (np.all(lastFrame == b))
            if np.all(lastFrame == b) == True:
                break
            lastFrame = np.copy(b).astype(bool)
            ct += 1
        return lastFrame > 0

    def kmeans(self, img, maxiter):
        X = img
        thresh = X.mean()
        for iter in range(maxiter):
            thresh = (X[X < thresh].mean() + X[X >= thresh].mean()) / 2.0
            X[X < thresh] = 0
            X[X >= thresh] = 255
        return X == 255


if __name__ == "__main__":

    im = mahotas.imread("before.png")

    im = im[:, :, 0]
    f = FingerProcess()
    b4 = f.process(im)
    imgout = m.overlay(im, b4)
    mahotas.imsave("lol.png", imgout)
示例#45
0
import numpy as np
import mahotas as mh
image = mh.imread('../SimpleImageDataset/building05.jpg')
image = mh.colors.rgb2gray(image)

# Compute Gaussian filtered versions with increasing kernel widths
im8  = mh.gaussian_filter(image,  8)
im16 = mh.gaussian_filter(image, 16)
im32 = mh.gaussian_filter(image, 32)

# We now build a composite image with three panels:
#
# [ IM8 | | IM16 | | IM32 ]

h, w = im8.shape
canvas = np.ones((h, 3 * w + 256), np.uint8)
canvas *= 255
canvas[:, :w] = im8
canvas[:, w + 128:2 * w + 128] = im16
canvas[:, -w:] = im32
mh.imsave('../1400OS_10_05+.jpg', canvas[:, ::2])

# Threshold the image
# We need to first stretch it to convert to an integer image
im32 = mh.stretch(im32)
ot32 = mh.otsu(im32)

# Convert to 255 np.uint8 to match the other images
im255 = 255 * (im32 > ot32).astype(np.uint8)
mh.imsave('../1400OS_10_06+.jpg', im255)
# This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License

import numpy as np
import mahotas as mh

# This little script just builds an image with two examples, side-by-side:

text = mh.imread("simple-dataset/text21.jpg")
scene = mh.imread("simple-dataset/scene00.jpg")
h, w, _ = text.shape
canvas = np.zeros((h, 2 * w + 128, 3), np.uint8)
canvas[:, -w:] = scene
canvas[:, :w] = text
canvas = canvas[::4, ::4]
mh.imsave('../1400OS_10_10+.jpg', canvas)
示例#47
0
import mahotas as mh
import numpy as np
im = mh.imread('lenna.jpg')
r,g,b = im.transpose(2,0,1)
h,w = r.shape
r12 = mh.gaussian_filter(r, 12.)
g12 = mh.gaussian_filter(g, 12.)
b12 = mh.gaussian_filter(b, 12.)
im12 = mh.as_rgb(r12,g12,b12)

X,Y = np.mgrid[:h,:w]
X = X-h/2.
Y = Y-w/2.
X /= X.max()
Y /= Y.max()
C = np.exp(-2.*(X**2+ Y**2))
C -= C.min()
C /= C.ptp()
C = C[:,:,None]

ring = mh.stretch(im*C + (1-C)*im12)
mh.imsave('lenna-ring.jpg', ring)
示例#48
0
        if Debug:

            ncolors = 10000
            np.random.seed(7)
            color_map = np.uint8(np.random.randint(0,256,(ncolors+1)*3)).reshape((ncolors + 1, 3))
            
            import mahotas

            # output full block images
            # for image_i in range(block1.shape[2]):
            #     mahotas.imsave('block1_z{0:04}.tif'.format(image_i), color_map[block1[:, :, image_i] % ncolors])
            #     mahotas.imsave('block2_z{0:04}.tif'.format(image_i), color_map[block2[:, :, image_i] % ncolors])

            #output overlap images
            if single_image_matching:
                mahotas.imsave('packed_overlap1.tif', color_map[np.squeeze(inverse[packed_overlap1]) % ncolors])
                mahotas.imsave('packed_overlap2.tif', color_map[np.squeeze(inverse[packed_overlap2]) % ncolors])
            else:
                debug_out1 = b = np.rollaxis(packed_overlap1, direction, 3)
                debug_out2 = b = np.rollaxis(packed_overlap2, direction, 3)
                for image_i in range(debug_out1.shape[2]):
                    mahotas.imsave('packed_overlap1_z{0:04}.tif'.format(image_i), color_map[inverse[debug_out1[:, :, image_i]] % ncolors])
                    mahotas.imsave('packed_overlap2_z{0:04}.tif'.format(image_i), color_map[inverse[debug_out2[:, :, image_i]] % ncolors])

            # import pylab
            # pylab.figure()
            # pylab.imshow(block1[0, :, :] % 13)
            # pylab.title('block1')
            # pylab.figure()
            # pylab.imshow(block2[0, :, :] % 13)
            # pylab.title('block2')
                test_i = test_i + 1
                sample_type = 'test'

            #print "Sampled {5} at {0}, {1}, {2}, r{3:.2f} ({4})".format(samp_i, samp_j, imgi, rotation, sample_type, membrane_type)

            sample_count = sample_count + 1
            if sample_count % 5000 == 0:
                print "{0} samples ({1}, {2}, {3}).".format(sample_count, train_i, valid_i, test_i)

    print "Made a total of {0} samples ({1}, {2}, {3}).".format(sample_count, train_i, valid_i, test_i)

    if PNG_OUTPUT:
        outdir = "LGN1_MembraneSamples_{0}x{0}x{1}_mp{2:0.2f}\\train\\".format(imgd, zd, membrane_proportion)
        if not os.path.exists(outdir): os.makedirs(outdir)
        for imgi in range(ntrain):
            mahotas.imsave(outdir + "{0:08d}_{1}.png".format(imgi, train_set[1][imgi]), train_set[0][imgi,:].reshape((imgd,imgd)))

        outdir = "LGN1_MembraneSamples_{0}x{0}x{1}_mp{2:0.2f}\\valid\\".format(imgd, zd, membrane_proportion)
        if not os.path.exists(outdir): os.makedirs(outdir)
        for imgi in range(nvalid):
            mahotas.imsave(outdir + "{0:08d}_{1}.png".format(imgi, valid_set[1][imgi]), valid_set[0][imgi,:].reshape((imgd,imgd)))

        outdir = "LGN1_MembraneSamples_{0}x{0}x{1}_mp{2:0.2f}\\test\\".format(imgd, zd, membrane_proportion)
        if not os.path.exists(outdir): os.makedirs(outdir)
        for imgi in range(ntest):
            mahotas.imsave(outdir + "{0:08d}_{1}.png".format(imgi, test_set[1][imgi]), test_set[0][imgi,:].reshape((imgd,imgd)))

    if DOWNSAMPLE_BY != 1:
        ds_string = '_ds{0}b'.format(DOWNSAMPLE_BY)
    else:
        ds_string = ''
示例#50
0
        os.unlink(output_file)
    os.rename(temp_path, output_file)


if Debug:

    output_image_basename = output_file + '_debug_output'

    # for classi in range(model.nclass):
    #     output_image_file = output_image_basename + '_class{0}.png'.format(classi + 1)
    #     mahotas.imsave(output_image_file, np.uint8(prob_image[:,:,classi] * 255))

    if prob_image.shape[2] == 3:

        output_image_file = output_image_basename + '_allclass.png'
        mahotas.imsave(output_image_file, np.uint8(prob_image * 255))

        win_0 = np.logical_and(prob_image[:,:,0] > prob_image[:,:,1], prob_image[:,:,0] > prob_image[:,:,2])
        win_2 = np.logical_and(prob_image[:,:,2] > prob_image[:,:,0], prob_image[:,:,2] > prob_image[:,:,1])
        win_1 = np.logical_not(np.logical_or(win_0, win_2))

        win_image = prob_image
        win_image[:,:,0] = win_0 * 255
        win_image[:,:,1] = win_1 * 255
        win_image[:,:,2] = win_2 * 255

        output_image_file = output_image_basename + '_winclass.png'
        mahotas.imsave(output_image_file, np.uint8(win_image))

    elif prob_image.shape[2] == 2:
#
# It is made available under the MIT License

import numpy as np
import mahotas as mh

# Load our example image:
image = mh.imread('../SimpleImageDataset/building05.jpg')

# Convert to greyscale
image = mh.colors.rgb2gray(image, dtype=np.uint8)

# Compute a threshold value:
thresh = mh.thresholding.otsu(image)
print('Otsu threshold is {0}'.format(thresh))

# Compute the thresholded image
otsubin = (image > thresh)
print('Saving thresholded image (with Otsu threshold) to otsu-threshold.jpeg')
mh.imsave('otsu-threshold.jpeg', otsubin.astype(np.uint8) * 255)

# Execute morphological opening to smooth out the edges
otsubin = mh.open(otsubin, np.ones((15, 15)))
mh.imsave('otsu-closed.jpeg', otsubin.astype(np.uint8) * 255)

# An alternative thresholding method:
thresh = mh.thresholding.rc(image)
print('Ridley-Calvard threshold is {0}'.format(thresh))
print('Saving thresholded image (with Ridley-Calvard threshold) to rc-threshold.jpeg')
mh.imsave('rc-threshold.jpeg', (image > thresh).astype(np.uint8) * 255)
示例#52
0
            boundaries = output_ids==1

            for ci in range(3):
                overlay_colors[:,:,ci][boundaries] = 128

            current_image_f = np.float32(mahotas.imread(input_image_path)[:output_size, :output_size])
            
            if len(current_image_f.shape) == 3:
                current_image_f = current_image_f[:,:,0]

            overlay_colors[:,:,0] = (1-alpha) * overlay_colors[:,:,0] + alpha * current_image_f
            overlay_colors[:,:,1] = (1-alpha) * overlay_colors[:,:,1] + alpha * current_image_f
            overlay_colors[:,:,2] = (1-alpha) * overlay_colors[:,:,2] + alpha * current_image_f

            mahotas.imsave(output_path.replace('.', '_partial.', 1), overlay_colors)

            shutil.move(output_path.replace('.', '_partial.', 1), output_path)

            # tif = TIFF.open(output_path, mode='w')
            # tif.write_image(overlay_colors, compression='lzw')
            
        except IOError as e:
            print "I/O error({0}): {1}".format(e.errno, e.strerror)
        except KeyboardInterrupt:
            pass
        # except:
        #     print "Unexpected error:", sys.exc_info()[0]
        #     if repeat_attempt_i == job_repeat_attempts:
        #         raise
            
示例#53
0
    # Save / display results

    votes = d_votes.get()

    prob_image = np.float32(votes) / ntree

    output_image_basename = file.replace(input_image_folder, output_folder)

    # for classi in range(nclass):
    # 	output_image_file = output_image_basename.replace(input_image_suffix, '_class{0}.png'.format(classi + 1))
    # 	mahotas.imsave(output_image_file, np.uint8(prob_image[:,:,classi] * 255))

    output_image_file = output_image_basename.replace(input_image_suffix,
                                                      '_allclass.png')
    mahotas.imsave(output_image_file, np.uint8(prob_image * 255))

    win_0 = np.logical_and(prob_image[:, :, 0] > prob_image[:, :, 1],
                           prob_image[:, :, 0] > prob_image[:, :, 2])
    win_2 = np.logical_and(prob_image[:, :, 2] > prob_image[:, :, 0],
                           prob_image[:, :, 2] > prob_image[:, :, 1])
    win_1 = np.logical_not(np.logical_or(win_0, win_2))

    win_image = prob_image
    win_image[:, :, 0] = win_0 * 255
    win_image[:, :, 1] = win_1 * 255
    win_image[:, :, 2] = win_2 * 255

    output_image_file = output_image_basename.replace(input_image_suffix,
                                                      '_winclass.png')
    mahotas.imsave(output_image_file, np.uint8(win_image))
示例#54
0
文件: segment.py 项目: Rhoana/rhoana
    
                extra_cellular_id = np.max(seeds)+1
                seeds[extra_cellular_indices] = extra_cellular_id
    
                with timer.Timer("second watershed"):
                    ws = mahotas.cwatershed(blur_prob, seeds)
                dx, dy = np.gradient(ws)
                ws_boundary = np.logical_or(dx!=0, dy!=0)
    
                ## Optional - mark the extra-cellular space as boundary
                #ws_boundary[np.nonzero(ws == extra_cellular_id)] = 1
    
                segmentations[:,:,segmentation_count] = ws_boundary > 0

                if Debug:
                    mahotas.imsave(output_path + '.seg_{0}.png'.format(segmentation_count), np.uint8(segmentations[:,:,segmentation_count] * 255))

                segmentation_count = segmentation_count + 1
                print "Segmentation {0} produced aftert {1} seconds".format(segmentation_count, int(time.time() - main_st))
                sys.stdout.flush()
    
    
    
    # move to final destination
    out_hdf5.close()
    # move to final location
    if os.path.exists(output_path):
        os.unlink(output_path)
    os.rename(temp_path, output_path)
    print "Success"
except Exception as e:
    print 'Running time: ', total_time / 60.
    print 'finished sampling data'

    return data_set

if __name__=="__main__":
    import uuid

    test = generate_experiment_data_patch_prediction(purpose='train', nsamples=30, patchSize=572, outPatchSize=388)
    dir_path = './training_patches/'
    
    for i in xrange(30):
        unique_filename = str(uuid.uuid4())
        img = np.reshape(test[1][i],(388,388))
        img_gray = np.reshape(test[0][i],(572,572))
        mahotas.imsave(dir_path+unique_filename+'.tif', np.uint8(img*255))
        mahotas.imsave(dir_path+unique_filename+'_gray.tif', np.uint8((img_gray+0.5)*255))
        

    #data_val = generate_experiment_data_supervised(purpose='validate', nsamples=10000, patchSize=65, balanceRate=0.5)
    #data = generate_experiment_data_patch_prediction(purpose='validate', nsamples=2, patchSize=315, outPatchSize=215)
    # plt.imshow(np.reshape(data[0][0],(315,315))); plt.figure()
    # plt.imshow(np.reshape(data[1][0],(215,215))); plt.figure()
    # plt.imshow(np.reshape(data[2][0],(215,215))); plt.show()

    # image = mahotas.imread('ac3_input_0141.tif')
    # image = normalizeImage(image)
    # label = mahotas.imread('ac3_labels_0141.tif') / 255.
    # test = adjust_imprecise_boundaries(image, label, 10)

    # plt.imshow(label+image); plt.show()
示例#56
0
#plt.title('normal')
#plt.show()


pca = PCA().fit(train_data)
variance=pca.explained_variance_ratio_
sum = 0
i=0
accuracy=.995
while sum<=accuracy:
   sum+=variance[i]
   i+=1
print i
#plt.ylim(ymax=.05)
#plt.bar(np.arange(0,49**2),variance)
#plt.ylabel('variance ratio')
#plt.xlabel('components')
#plt.show()





pca = PCA(n_components=i)
fitted = pca.fit_transform(train_data)
patch=PCA.inverse_transform(pca,fitted)[0]

mahotas.imsave('results/pca images/variance_sum_'+str(accuracy)+'.tif',np.uint16np.array(patch).reshape(401,401))
plt.title(str(i))
plt.imshow(np.array(patch).reshape(401,401))
plt.show()
示例#57
0

if __name__ == '__main__':
    import mahotas
    import matplotlib.pyplot as plt
#    image = mahotas.imread('train-input0099.tif')
    image = mahotas.imread('ac3_input_0141.tif')

    x = T.matrix('x')

    test2 = MLP(rng=numpy.random.RandomState(1), input=x, n_out=2, fileName = 'tmp.pkl')

    prob = test2.classify_image(img=image, normMean=0.5, norm_std=1.0)
    plt.imshow(1-prob)
    plt.show()
    mahotas.imsave('tmp_output_05.png', np.uint8((1-prob)*255))

    hl = test2.hiddenLayers[0]
    plt.imshow(hl.visualize_filters())
    plt.show()
    mahotas.imsave('filter_output_05.png', np.uint8(hl.visualize_filters()))

    plt.plot(np.array(test2.trainingCost), label='training')
    plt.plot(np.array(test2.validationError), label='validation')
    plt.legend()
    plt.show()

    if len(test2.validationError) > 5000:
        plt.plot(np.array(test2.trainingCost)[-5000:], label='training')
        plt.plot(np.array(test2.validationError)[-5000:], label='validation')
        plt.legend()
import numpy as np
from matplotlib import pyplot as plt

# 이미지 로드 & B&W로 변환
image = mh.imread('../SimpleImageDataset/scene00.jpg')
image = mh.colors.rgb2grey(image, dtype=np.uint8)
plt.imshow(image)
plt.gray()
plt.title('original image')

thresh = mh.thresholding.otsu(image)
print('Otsu threshold is {}.'.format(thresh))

threshed = (image > thresh)
plt.figure()
plt.imshow(threshed)
plt.title('threholded image')
mh.imsave('thresholded.png', threshed.astype(np.uint8)*255)

im16 = mh.gaussian_filter(image, 16)

# 블러링 이미지로 경계 연산 반복
thresh = mh.thresholding.otsu(im16.astype(np.uint8))
threshed = (im16 > thresh)
plt.figure()
plt.imshow(threshed)
plt.title('threholded image (after blurring)')
print('Otsu threshold after blurring is {}.'.format(thresh))
mh.imsave('thresholded16.png', threshed.astype(np.uint8)*255)
plt.show()