• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python transform.resize函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中skimage.transform.resize函数的典型用法代码示例。如果您正苦于以下问题:Python resize函数的具体用法?Python resize怎么用?Python resize使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了resize函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: loadDataMontgomery

def loadDataMontgomery(df, path, im_shape):
    """Function for loading Montgomery dataset"""
    X, y = [], []
    for i, item in df.iterrows():
        img = img_as_float(io.imread(path + item[0]))
        gt = io.imread(path + item[1])
        l, r = np.where(img.sum(0) > 1)[0][[0, -1]]
        t, b = np.where(img.sum(1) > 1)[0][[0, -1]]
        img = img[t:b, l:r]
        mask = gt[t:b, l:r]
        img = transform.resize(img, im_shape)
        img = exposure.equalize_hist(img)
        img = np.expand_dims(img, -1)
        mask = transform.resize(mask, im_shape)
        mask = np.expand_dims(mask, -1)
        X.append(img)
        y.append(mask)
    X = np.array(X)
    y = np.array(y)
    X -= X.mean()
    X /= X.std()

    print '### Data loaded'
    print '\t{}'.format(path)
    print '\t{}\t{}'.format(X.shape, y.shape)
    print '\tX:{:.1f}-{:.1f}\ty:{:.1f}-{:.1f}\n'.format(X.min(), X.max(), y.min(), y.max())
    print '\tX.mean = {}, X.std = {}'.format(X.mean(), X.std())
    return X, y
开发者ID:eclique,项目名称:lung-segmentation-2d,代码行数:28,代码来源:load_data.py


示例2: normalize_size

def normalize_size(image, size=256, trans='c'):
	## 'c':central crop, 'w':warp, 'p':padding
	o_shape = image.shape
	assert o_shape[0] > size and o_shape[1] > size
	if trans == 'c':
		if o_shape[0] > o_shape[1]:
			dh = int( (o_shape[0] - o_shape[1])/2 )
			image = image[dh:dh+o_shape[1],:]
		else:
			dw = int( (o_shape[1] - o_shape[0])/2 )
			image = image[:,dw:dw+o_shape[0]]		
		new_shape = image.shape
		assert new_shape[0] == new_shape[1]
		image = resize(image, (size,size), order=3, preserve_range=False)
	elif trans == 'w':
		image = resize(image, (size,size), order=3, preserve_range=False)
	elif trans == 'p':
		background = np.zeros((size, size, 3))
		if o_shape[0] > o_shape[1]:
			new_shape = (size,size*o_shape[1]/o_shape[0])
			dh = 0
			dw = (size - new_shape[1])/2
		else:
			new_shape = (size*o_shape[0]/o_shape[1],size)
			dh = (size - new_shape[0])/2
			dw = 0
		image = resize(image, (new_shape[0],new_shape[1]), order=0, preserve_range=False)
		background[dh:dh+new_shape[0],dw:dw+new_shape[1],:] = image[:,:,:]
		image = background
	else:
		print "ERROR:undesignated transformation"
	return image
开发者ID:paramoecium,项目名称:RAPID,代码行数:32,代码来源:preprocessing.py


示例3: test

def test(classifier, pca):
	building = io.imread("http://www.nps.gov/tps/images/briefs/14-commercial-building.jpg")
	building = transform.resize(building, (200, 200, 3))
	building = color.rgb2gray(building)
	building = building.reshape(1, -1)
	# building = pca.transform(building)
	print building
	print classifier.predict(building)[0]
	print to_cat[str(classifier.predict(building)[0])] + " (expect building)"
	# print classifier.predict_proba(building)

	snow = io.imread("http://farm4.static.flickr.com/3405/3332148397_92d89db2ab.jpg")
	snow = transform.resize(snow, (200, 200, 3))
	snow = color.rgb2gray(snow)
	snow = snow.reshape(1, -1)
	# snow = pca.transform(snow)
	print snow
	print to_cat[str(classifier.predict(snow)[0])] + " (expect snow)"
	# print classifier.predict_proba(snow)


	flower = io.imread("https://upload.wikimedia.org/wikipedia/commons/f/fd/Daisy_flower_green_background.jpg")
	flower = transform.resize(flower, (200, 200, 3))
	flower = color.rgb2gray(flower)
	flower = flower.reshape(1, -1)
	# flower = pca.transform(flower)
	print to_cat[str(classifier.predict(flower)[0])] + " (expect plant)"
开发者ID:zverham,项目名称:svm_classifier,代码行数:27,代码来源:reader.py


示例4: image_compare

def image_compare(df, IMAGES_DIR='/home/ryan/asi_images/'):
    '''
    takes a list of n image ids and returns sum(n..n-1) n comparisons of r2 difference, r2(fft) difference, and average number of thresholded pixels
    '''
    img_buffer = {}
    return_list = []
    artdf = df[['_id', 'images']].copy()
    artdf.images = artdf.images.apply(getpath) 
    paths = artdf[['_id','images']].dropna()
    paths.index = paths._id
    paths = paths.images
    if paths.shape[0] < 2:
        return DataFrame([])
    for id_pair in combinations(paths.index, 2):
        if id_pair[0] in img_buffer:
            img1 = img_buffer[id_pair[0]]
        else:
            img_buffer[id_pair[0]] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + paths[id_pair[0]]), (300,300))))
            img1 = img_buffer[id_pair[0]]
        
        if id_pair[1] in img_buffer:
            img2 = img_buffer[id_pair[1]]
        else:
            img_buffer[id_pair[1]] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + paths[id_pair[1]]), (300,300))))
            img2 = img_buffer[id_pair[1]]
        return_list.append(
                [id_pair[0], id_pair[1], \
                    norm(img1 - img2), \
                    norm(fft2(img1) - fft2(img2)), \
                    #mean([sum(img1 > threshold_otsu(img1)), sum(img2 > threshold_otsu(img2))])]
                    #mean([sum(img1 > 0.9), sum(img2 > 0.9)])] 
                    std(img1)+std(img2)/2.]
       )
    return DataFrame(return_list, columns=['id1','id2','r2diff', 'fftdiff', 'stdavg'])
开发者ID:rhsimplex,项目名称:artsift,代码行数:34,代码来源:art_utils.py


示例5: modify

def modify(img):
    """Randomly modify an image
    
    This is a preprocessing step for training an OCR classifier. It takes
    in an image and casts it to greyscale, reshapes it, and adds some
    (1) rotations, (2) translations and (3) noise.
    
    If more efficiency is needed, we could factor out some of the initial
    nonrandom transforms.
    """
    
    block_size = np.random.uniform(20, 40)
    rotation = 5*np.random.randn()
    
    #print 'BLOCK SIZE', block_size
    #print 'ROTATION  ', rotation
    
    img = color.rgb2grey(img)
    img = transform.resize(img, output_shape=(50,30))
    img = filter.threshold_adaptive(img, block_size=block_size)
    
    # rotate the image
    img = np.logical_not(transform.rotate(np.logical_not(img), rotation))
    # translate the image
    img = shift(img)
    # add some noise to the image
    img = noise(img)
    
    img = transform.resize(img, output_shape=(25,15))
    return filter.threshold_adaptive(img, block_size=25)
开发者ID:rmcgibbo,项目名称:autogert,代码行数:30,代码来源:train_synthetic.py


示例6: create_thumbnail

 def create_thumbnail(self, size, img=None):
     print 'processing raw images'
     if img:
         return resize(img, (size, size))
     curr_dir = os.path.dirname(
         os.path.abspath(inspect.getfile(inspect.currentframe())))
     folders = os.walk(os.path.join(curr_dir, '../../data/train/'))
     images = []
     classes = []
     targets = []
     for class_id, folder in enumerate(folders):
         classes.append(folder[0][17:])
         for img in folder[2]:
             if img.index('.jpg') == -1:
                 continue
             image = imread(folder[0] + '/' + img)
             image = resize(image, (size, size))
             # Important to put -1, to have it 0-based.
             target = class_id - 1
             new_images, new_targets = self.augment_data(image, target)
             images.extend(new_images)
             targets.extend(new_targets)
     train = (images, targets)
     self.save_set('train' + str(size), images, targets)
     # f = open(curr_dir + '/train' + str(size) + '.pkl', 'wb')
     # pickle.dump(train, f, protocol=pickle.HIGHEST_PROTOCOL)
     # f.close()
     return train
开发者ID:seba-1511,项目名称:planktonChallenge,代码行数:28,代码来源:data.py


示例7: check_size

def check_size(img, min_image_width_height, fixed_image_size=None):
    '''
    checks if the image accords to the minimum and maximum size requirements
    or fixed image size and resizes if not
    
    :param img: the image to be checked
    :param min_image_width_height: the minimum image size
    :param fixed_image_size:
    '''
    if fixed_image_size is not None:
        if len(fixed_image_size) != 2:
            raise ValueError('The requested fixed image size is invalid!')
        new_img = resize(image=img, output_shape=fixed_image_size[::-1])
        new_img = new_img.astype(np.float32)
        return new_img
    elif np.amin(img.shape[:2]) < min_image_width_height:
        if np.amin(img.shape[:2]) == 0:
            return None
        scale = float(min_image_width_height + 1) / float(np.amin(img.shape[:2]))
        new_shape = (int(scale * img.shape[0]), int(scale * img.shape[1]))
        new_img = resize(image=img, output_shape=new_shape)
        new_img = new_img.astype(np.float32)
        return new_img
    else:
        return img
开发者ID:akramkohansal,项目名称:pytorch-phocnet,代码行数:25,代码来源:image_size.py


示例8: computeCAM

def computeCAM(snet, X, W, reshape_size=None, n_top_convs=20):
    """
    Applies a forward pass of the pre-processed samples "X" in the GAP net "snet" and generates the resulting
    CAM "maps" using the GAP weights "W" with the defined size "reshape_size".
    Additionally, it returns the best "n_top_convs" convolutional features for each of the classes. The ranking is
    computed considering the weight Wi assigned to the i-th feature map.
    """
    from skimage.transform import resize

    if reshape_size is None:
        reshape_size = [256, 256]

    # Apply forward pass in GAP model
    [X, predictions] = applyForwardPass(snet, X)

    # Get indices of best convolutional features for each class
    ind_best = np.zeros((W.shape[1], n_top_convs))
    for c in range(W.shape[1]):
        ind_best[c, :] = np.argsort(W[:, c])[::-1][:n_top_convs]

    # Compute heatmaps (CAMs) for each class [n_samples, n_classes, height, width]
    maps = np.zeros((X.shape[0], W.shape[1], reshape_size[0], reshape_size[1]))
    # Store top convolutional features
    convs = np.zeros((X.shape[0], W.shape[1], n_top_convs, reshape_size[0], reshape_size[1]))

    for s in range(X.shape[0]):
        weighted_activation = np.dot(np.transpose(W), np.reshape(X[s], (W.shape[0], X.shape[2] * X.shape[3])))
        mapping = np.reshape(weighted_activation, (W.shape[1], X.shape[2], X.shape[3]))
        maps[s] = resize(mapping, tuple([W.shape[1]] + reshape_size), order=1, preserve_range=True)

        for c in range(W.shape[1]):
            for enum_conv, i_conv in list(enumerate(ind_best[c])):
                convs[s, c, enum_conv] = resize(X[s, i_conv], reshape_size, order=1, preserve_range=True)

    return [maps, predictions, convs]
开发者ID:MarcBS,项目名称:staged_keras_wrapper,代码行数:35,代码来源:localization_utilities.py


示例9: _images_thumbnails

    def _images_thumbnails(self):
        from vispy.io import imsave, imread
        # TODO: Switch to using PIL for resizing
        from skimage.transform import resize
        import numpy as np
        gallery_dir = op.join(IMAGES_DIR, 'gallery')
        thumbs_dir = op.join(IMAGES_DIR, 'thumbs')
        carousel_dir = op.join(IMAGES_DIR, 'carousel')
        for fname in os.listdir(gallery_dir):
            filename1 = op.join(gallery_dir, fname)
            filename2 = op.join(thumbs_dir, fname)
            filename3 = op.join(carousel_dir, fname)
            #
            im = imread(filename1)

            newx = 200
            newy = int(newx * im.shape[0] / im.shape[1])
            im = (resize(im, (newy, newx), 2) * 255).astype(np.uint8)
            imsave(filename2, im)

            newy = 160  # This should match the carousel size!
            newx = int(newy * im.shape[1] / im.shape[0])
            im = (resize(im, (newy, newx), 1) * 255).astype(np.uint8)
            imsave(filename3, im)

            print('Created thumbnail and carousel %s' % fname)
开发者ID:rougier,项目名称:vispy,代码行数:26,代码来源:make.py


示例10: put_image

	def put_image(self, image_path):
		# print "Loading the image"
		self.image = io.imread(image_path, as_grey=True)
		self.image = transform.resize(self.image,(50,50))
		self.image_scaled = io.imread(image_path, as_grey=True)
		self.image_scaled = transform.resize(self.image_scaled,(50,50))
		self.image_scaled *= (1/self.image_scaled.max())
开发者ID:AkaZuko,项目名称:TextDetection,代码行数:7,代码来源:test_image.py


示例11: preproc

    def preproc(self, img, size, pixel_spacing, equalize=True, crop=True):
       """crop center and resize"""
        #    TODO: this is stupid, you could crop out the heart
        # But should test this
       if img.shape[0] < img.shape[1]:
           img = img.T
       # Standardize based on pixel spacing
       img = transform.resize(img, (int(img.shape[0]*(1.0/np.float32(pixel_spacing[0]))), int(img.shape[1]*(1.0/np.float32(pixel_spacing[1])))))
       # we crop image from center
       short_egde = min(img.shape[:2])
       yy = int((img.shape[0] - short_egde) / 2)
       xx = int((img.shape[1] - short_egde) / 2)
       if crop:
           crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
       # resize to 64, 64
           resized_img = transform.resize(crop_img, (size, size))
       else:
           resized_img = img
       #resized_img = gaussian_filter(resized_img, sigma=1)
       #resized_img = median_filter(resized_img, size=(3,3))
       if equalize:
           resized_img = equalize_hist(resized_img)
           resized_img = adjust_sigmoid(resized_img)
       resized_img *= 255.

       return resized_img.astype("float32")
开发者ID:Breakend,项目名称:LeftVentricleVolumeEstimation,代码行数:26,代码来源:data_utils.py


示例12: main

def main():
    for file_path in glob.glob("/home/lucas/Downloads/Lucas/GSK 10uM/*.JPG"):

        img = data.imread(file_path, as_grey=True)

        img = transform.resize(img, [600, 600])
        img_color = transform.resize(data.imread(file_path), [600, 600])

        img[img >img.mean()-0.1] = 0

        # io.imshow(img)
        # io.show()
        #
        edges = canny(img)
        bordas_fechadas = closing(img > 0.1, square(15)) # fechando gaps
        fill_cells = ndi.binary_fill_holes(bordas_fechadas)
        # io.imshow(fill_cells)
        # io.show()
        img_label = label(fill_cells, background=0)
        n= 0
        for  x in regionprops(img_label):
            if x.area < 2000 and x.area > 300:
                n +=1
                print x.area
                minr, minc, maxr, maxc = x.bbox
                try:
                    out_path_name = file_path.split("/")[-1].rstrip(".JPG")
                    io.imsave("out/cell_{}_pic_{}_area_{}.png".format(n, out_path_name, str(round(x.area))),img_color[minr-3: maxr+3, minc-3: maxc+3])
                    #io.show()
                except:
                    pass
开发者ID:LucasSilvaFerreira,项目名称:egg_finder,代码行数:31,代码来源:microscopia_eggs.py


示例13: sfit

def sfit(arr, degree=3, binning=16): # For efficiency, we downsample the input array before doing the fit.
    "Fit polynomial to a 2D array, aka surface."

# For info on resizing, see http://stackoverflow.com/questions/29958670/how-to-use-matlabs-imresize-in-python
    
    shape_small = (np.size(arr,0)/binning, np.size(arr,1)/binning)
    shape_big   = np.shape(arr)

# Create x and y arrays, which we need to pass to the fitting routine

    x_big, y_big = np.mgrid[:shape_big[0], :shape_big[1]]
    x_small = skt.resize(x_big, shape_small, order=1, preserve_range=True)
    y_small = skt.resize(y_big, shape_small, order=1, preserve_range=True)
    
    arr_small = skt.resize(arr, shape_small, order=1, preserve_range=True)
    p_init = astropy.modeling.models.Polynomial2D(degree=degree)

# Define the fitting routine

    fit_p = astropy.modeling.fitting.LevMarLSQFitter()
        
#    with warnings.catch_warnings():
# Ignore model linearity warning from the fitter
#        warnings.simplefilter('ignore')

# Do the fit itself
        
    poly = fit_p(p_init, x_small, y_small, arr_small)

# Take the returned polynomial, and apply it to our x and y axes to get the final surface fit

    surf_big = poly(x_big, y_big)
    
    return surf_big
开发者ID:henrythroop,项目名称:python,代码行数:34,代码来源:HBT.py


示例14: augmentation

def augmentation(image, imageB, org_width=160,org_height=224, width=190, height=262):
    max_angle=20
    image=resize(image,(width,height))
    imageB=resize(imageB,(width,height))

    angle=np.random.randint(max_angle)
    if np.random.randint(2):
        angle=-angle
    image=rotate(image,angle,resize=True)
    imageB=rotate(imageB,angle,resize=True)

    xstart=np.random.randint(width-org_width)
    ystart=np.random.randint(height-org_height)
    image=image[xstart:xstart+org_width,ystart:ystart+org_height]
    imageB=imageB[xstart:xstart+org_width,ystart:ystart+org_height]

    if np.random.randint(2):
        image=cv2.flip(image,1)
        imageB=cv2.flip(imageB,1)
    
    if np.random.randint(2):
        imageB=cv2.flip(imageB,0)
    # image=resize(image,(org_width,org_height))

    return image,imageB
开发者ID:neverspill,项目名称:u-net,代码行数:25,代码来源:train_res.py


示例15: generate_bg

def generate_bg(bg_resize=True):
    files = glob.glob("/usr/share/backgrounds/*/*.jpg")
    # random.choice(files)
    # print(random.choice(files))
    found = False
    while not found:
        fname = random.choice(files)
        bg = cv2.imread(fname) / 255.#, cv2.CV_LOAD_IMAGE_GRAYSCALE) / 255.
        if (bg.shape[1] >= OUTPUT_SHAPE[1] and
            bg.shape[0] >= OUTPUT_SHAPE[0]):
            found = True


    #print(files)
    # while not found:
    #     fname = "bgs/{:08d}.jpg".format(random.randint(0, num_bg_images - 1))
    #     bg = cv2.imread(fname, cv2.CV_LOAD_IMAGE_GRAYSCALE) / 255.
    #     if (bg.shape[1] >= OUTPUT_SHAPE[1] and
    #         bg.shape[0] >= OUTPUT_SHAPE[0]):
    #         found = True
    if bg_resize:
        x_shape = np.random.randint(OUTPUT_SHAPE[1], bg.shape[1])
        y_shape = np.random.randint(OUTPUT_SHAPE[0], bg.shape[0])
        resize(image=bg, output_shape=(y_shape, x_shape), order=3)
    x = random.randint(0, bg.shape[1] - OUTPUT_SHAPE[1])
    y = random.randint(0, bg.shape[0] - OUTPUT_SHAPE[0])
    bg = bg[y:y + OUTPUT_SHAPE[0], x:x + OUTPUT_SHAPE[1]]

    return bg, fname
开发者ID:kingtaurus,项目名称:cs231n,代码行数:29,代码来源:construct_proposals.py


示例16: repeated_sales

def repeated_sales(df, artistname, artname, r2thresh=7000, fftr2thresh=10000, IMAGES_DIR='/home/ryan/asi_images/'):
    """
        Takes a dataframe, artistname and artname and tries to decide, via image matching, if there is a repeat sale. Returns a dict of lot_ids, each entry a list of repeat sales
    """
    artdf = df[(df['artistID']==artistname) & (df['artTitle']==artname)]

    artdf.images = artdf.images.apply(getpath)
    paths = artdf[['_id','images']].dropna()
    id_dict = {}
    img_buffer = {}
    already_ordered = []
    for i, path_i in paths.values:
        id_dict[i] = []
        img_buffer[i] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + path_i), (300,300))))
        for j, path_j in paths[paths._id != i].values:
            if j > i and j not in already_ordered:
                if j not in img_buffer.keys():
                    img_buffer[j] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + path_j), (300,300))))
                if norm(img_buffer[i] - img_buffer[j]) < r2thresh and\
                        norm(fft2(img_buffer[i]) - fft2(img_buffer[j])) < fftr2thresh:
                    id_dict[i].append(j)
                    already_ordered.append(j)
    for key in id_dict.keys():
        if id_dict[key] == []:
            id_dict.pop(key)
    return id_dict
开发者ID:rhsimplex,项目名称:artsift,代码行数:26,代码来源:art_utils.py


示例17: get_batches_fn

    def get_batches_fn(batch_size):
        """
        Create batches of training data
        :param batch_size: Batch Size
        :return: Batches of training data
        """
        image_paths = glob(os.path.join(data_folder, 'image_2', '*.png'))
        label_paths = {
            re.sub(r'_(lane|road)_', '_', os.path.basename(path)): path
            for path in glob(os.path.join(data_folder, 'gt_image_2', '*_road_*.png'))}
        background_color = np.array([255, 0, 0])

        random.shuffle(image_paths)
        for batch_i in range(0, len(image_paths), batch_size):
            images = []
            gt_images = []
            for image_file in image_paths[batch_i:batch_i+batch_size]:
                gt_image_file = label_paths[os.path.basename(image_file)]

                #image = scipy.misc.imresize(scipy.misc.imread(image_file), image_shape)
                image = resize(scipy.misc.imread(image_file), image_shape)
                #gt_image = scipy.misc.imresize(scipy.misc.imread(gt_image_file), image_shape)
                gt_image = resize(scipy.misc.imread(gt_image_file), image_shape)

                gt_bg = np.all(gt_image == background_color, axis=2)
                gt_bg = gt_bg.reshape(*gt_bg.shape, 1)
                gt_image = np.concatenate((gt_bg, np.invert(gt_bg)), axis=2)

                images.append(image)
                gt_images.append(gt_image)

            yield np.array(images), np.array(gt_images)
开发者ID:pparthasarathy,项目名称:SDCND-U3P2-Road-Semantic-Segmentation,代码行数:32,代码来源:helper.py


示例18: daisy_features

def daisy_features(train_data_images, train_data_split_images, test_data_images, IMG_SIZE):
    canny(train_data_images, train_data_split_images, test_data_images, IMG_SIZE)
    train_data_features = []
    test_data_features = []
    train_data = []
    test_data = []
    train_data_split_crossfold = []
    print(4)
    #bow_train = cv2.BOWKMeansTrainer(8)

    #flann_params = dict(algorithm = 1, trees = 5)
    #matcher = cv2.FlannBasedMatcher(flann_params, {})

    #detect = cv2.xfeatures2d.SIFT_create()
    #extract = cv2.xfeatures2d.SIFT_create()

    #bow_extract = cv2.BOWImgDescriptorExtractor(extract, matcher)
    #help(bow_train)
    #help(bow_extract)
    for image in train_data_images:
        img =  imread(image, as_grey=True)
        resized_image = resize(img, (40,40))
        train_data.append(resized_image)

    for image in train_data_split_images:
        img =  imread(image, as_grey=True)
        resized_image = resize(img, (40,40))
        train_data_split_crossfold.append(resized_image)

    for image in test_data_images:
        img =  imread(image, as_grey=True)
        resized_image = resize(img, (40,40))
        test_data.append(resized_image)

    print(6)
    des = []
    des_cross = []
    des_test = []

    radius = 5
    for image in train_data:
        descs = daisy(image, radius=radius)
        des.append(descs)

    train_data_features = bow(des, train_data)
    del des

    print('oi1')

    #for image in train_data_split_crossfold:
        #descs = daisy(image, radius=radius)
        #des_cross.append(descs)

    print('oi1')
    #for image in test_data:
        #descs = daisy(image, radius=radius)
        #des_test.append(descs)

    print('oi1')
开发者ID:dvn123,项目名称:MachineLearning,代码行数:59,代码来源:image_features.py


示例19: iterate_train

 def iterate_train(self,batchsize,data_augment=False):
     num_batch=40000
     for i in range(num_batch/batchsize):
         start=i*batchsize
         end=(i+1)*batchsize
         if (data_augment==False):
             x=self.train_set_x.get_value(borrow=True)[start:end]
             x=(x-self.mean)/256.0
             x=np.asarray(x,dtype=theano.config.floatX)
             yield x, self.train_set_y.eval()[start:end]
         else:
             imgs=self.train_set_x.get_value(borrow=True)[start:end]
             for j in range(imgs.shape[0]):
                 #horizontally flip
                 if randint(0,1)==0:
                     target=np.copy(imgs[j])
                     for i in range(imgs[j].shape[2]):
                         target[:,:,i]=imgs[j][:,:,imgs[j].shape[2]-1-i]
                     imgs[j]=target
                     
                     
                 #color transform
                 target=np.zeros([3,32,32])
                 mix=range(3)
                 np.random.shuffle(mix)
                 for x in range(3):
                     target[x]=imgs[j][mix[x]]
                 imgs[j]=target
                 
                 
                 r=randint(0,7)
                 if r==0:
                     tmp=np.transpose(imgs[j],(1,2,0));
                     tmp=transform.resize(tmp[0:28,0:28,:],[32,32,3]) 
                     imgs[j]=np.transpose(tmp,(2,0,1))                        
                 elif r==1:
                     tmp=np.transpose(imgs[j],(1,2,0))
                     tmp=transform.resize(tmp[0:28,4:32,:],[32,32,3]) 
                     imgs[j]=np.transpose(tmp,(2,0,1))
                 elif r==2:
                     tmp=np.transpose(imgs[j],(1,2,0))
                     tmp=transform.resize(tmp[4:32,0:28,:],[32,32,3]) 
                     imgs[j]=np.transpose(tmp,(2,0,1))
                 elif r==3:
                     tmp=np.transpose(imgs[j],(1,2,0))
                     tmp=transform.resize(tmp[4:32,4:32,:],[32,32,3]) 
                     imgs[j]=np.transpose(tmp,(2,0,1))
                 elif r==4:
                     tmp=np.asarray(imgs[j],dtype='int32')
                     tmp=transform.rotate(image=tmp,angle=5)
                     imgs[j]=np.asarray(imgs[j],dtype=theano.config.floatX)
                 elif r==5:
                     tmp=np.asarray(imgs[j],dtype='int32')
                     tmp=transform.rotate(image=tmp,angle=-5)
                     imgs[j]=np.asarray(imgs[j],dtype=theano.config.floatX)
             imgs=(imgs-self.mean)/256.0
             imgs=np.asarray(imgs,dtype=theano.config.floatX)
             yield imgs,self.train_set_y.eval()[start:end]
开发者ID:ducquangkstn,项目名称:cnn,代码行数:58,代码来源:cifar10.py


示例20: preprocessing

 def preprocessing(self):
     p = resize(self.p, (256, 256))
     image = np.zeros(shape=(258, 258))
     image[1:257, 1:257] = p
     image_ratio = self.universe(image)
     image = image_ratio[0]
     ratio = image_ratio[1]
     image = resize(image, (252, 252))
     return image, ratio
开发者ID:stels07,项目名称:CS534-OCR,代码行数:9,代码来源:feature_extraction.py



注:本文中的skimage.transform.resize函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python transform.rotate函数代码示例发布时间:2022-05-27
下一篇:
Python transform.rescale函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap