当前位置: 首页>>代码示例>>Python>>正文


Python Image.fromarray方法代码示例

本文整理汇总了Python中Image.fromarray方法的典型用法代码示例。如果您正苦于以下问题:Python Image.fromarray方法的具体用法?Python Image.fromarray怎么用?Python Image.fromarray使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Image的用法示例。


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

示例1: make_pil_image

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def make_pil_image(*args, **kwargs):
    '''Creates a PIL Image object.

    USAGE: make_pil_image(source [, bands] [stretch=True] [stretch_all=False],
                          [bounds = (lower, upper)] )

    See `get_rgb` for description of arguments.
    '''
    try:
        from PIL import Image, ImageDraw
    except ImportError:
        import Image
        import ImageDraw

    rgb = get_rgb(*args, **kwargs)
    rgb = (rgb * 255).astype(np.ubyte)
    img = Image.fromarray(rgb)
    return img 
开发者ID:spectralpython,项目名称:spectral,代码行数:20,代码来源:graphics.py

示例2: showClustering

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def showClustering(self):

        localPixels = [None] * len(self.image.getdata())

        for idx, pixel in enumerate(self.pixels):
                shortest = float('Inf')
                for cluster in self.clusters:
                    distance = self.calcDistance(cluster.centroid, pixel)
                    if distance < shortest:
                        shortest = distance
                        nearest = cluster

                localPixels[idx] = nearest.centroid

        w, h = self.image.size
        localPixels = numpy.asarray(localPixels)\
            .astype('uint8')\
            .reshape((h, w, 3))

        colourMap = Image.fromarray(localPixels)
        colourMap.show() 
开发者ID:ZeevG,项目名称:python-dominant-image-colour,代码行数:23,代码来源:kmeans.py

示例3: _save

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def _save(self):
        tt = datetime.now()
        time_string = tt.strftime('%mm-%dd-%Hh-%Mm-%Ss')
        sub_path = os.path.join(self.save_path, time_string)

        if not os.path.exists(sub_path):
            os.makedirs(sub_path)

        prediction = self.model.prediction(self.batch)
        for i in range(128):
            image = self.batch[:, :, :, i]
            image = image.transpose(1, 2, 0)

            recon = numpy.array(prediction[:, :, :, i])
            recon = recon.transpose(1, 2, 0)

            image_array = numpy.uint8(rescale(numpy.hstack((image, recon))))

            to_save = Image.fromarray(image_array)
            filename = 'recon-%02d.jpeg' % i
            filepath = os.path.join(sub_path, filename)
            to_save.save(filepath) 
开发者ID:ifp-uiuc,项目名称:anna,代码行数:24,代码来源:__init__.py

示例4: __call__

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def __call__(self, tensor):
        data = tensor.asnumpy()
        data = data[0].transpose(1,2,0)
        return Image.fromarray(data) 
开发者ID:Kashu7100,项目名称:Qualia2.0,代码行数:6,代码来源:transforms.py

示例5: get_overfeat_output_raw

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def get_overfeat_output_raw(img_arr, layer_id, largenet, overfeatcmd=None,
                            net_weight_file=None, overfeat_dir=None,
                            architecture='linux_64'):

    if img_arr.dtype != np.uint8:
        raise ValueError('Please convert image to uint8')

    if img_arr.shape[2] != 3:
        raise ValueError('Last dimension must index color')

    overfeatcmd = get_overfeat_cmd(overfeatcmd, overfeat_dir, architecture)
    net_weight_file = get_net_weights(net_weight_file, largenet,
                                      overfeat_dir=overfeat_dir)

    image = Image.fromarray(img_arr)

    buf = StringIO.StringIO()
    image.save(buf, format='ppm')
    buf.seek(0)

    command = overfeatcmd + " " + net_weight_file + " -1 %d %d" % (
        int(largenet), layer_id)

    p = subprocess.Popen(
        command.split(' '), stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    output = p.communicate(input=buf.buf)[0]

    return output 
开发者ID:sklearn-theano,项目名称:sklearn-theano,代码行数:30,代码来源:overfeat_wrapper.py

示例6: sample_from_model

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def sample_from_model(model, param_file_path, vae_hyperParams, image_file_path, nImages=100):

    # get op to load the model                                                                                                    
    persister = tf.train.Saver()

    with tf.Session() as s:
        persister.restore(s, param_file_path)
        sample_list = s.run(model.get_samples(nImages))

    for i, samples in enumerate(sample_list):
        image = Image.fromarray(tile_raster_images(X=samples, img_shape=(28, 28), tile_shape=(int(np.sqrt(nImages)), int(np.sqrt(nImages))), tile_spacing=(1, 1)))
        image.save(image_file_path+"_component"+str(i)+".png") 
开发者ID:enalisnick,项目名称:mixture_density_VAEs,代码行数:14,代码来源:train_MixModel_VAE-2StochLayers.py

示例7: sample_from_model

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def sample_from_model(model, param_file_path, vae_hyperParams, image_file_path, nImages=100):

    # get op to load the model                                                                                                    
    persister = tf.train.Saver()

    with tf.Session() as s:
        persister.restore(s, param_file_path)
        samples = s.run(model.get_samples(nImages))

    image = Image.fromarray(tile_raster_images(X=samples, img_shape=(28, 28), tile_shape=(int(np.sqrt(nImages)), int(np.sqrt(nImages))), tile_spacing=(1, 1)))
    image.save(image_file_path+".png") 
开发者ID:enalisnick,项目名称:mixture_density_VAEs,代码行数:13,代码来源:train_reg_gaussVAE.py

示例8: get_gray_image

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def get_gray_image(self):
        """Getter for the gray_image property."""
        return Image.fromarray(self._gray_array) 
开发者ID:mozilla,项目名称:iris,代码行数:5,代码来源:screenshot_image.py

示例9: get_raw_image

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def get_raw_image(self):
        """Getter raw_image property."""
        return Image.fromarray(self._raw_image) 
开发者ID:mozilla,项目名称:iris,代码行数:5,代码来源:screenshot_image.py

示例10: _get_image_from_array

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def _get_image_from_array(scale: int, array) -> Image:
    """Converts a scaled array into Image."""
    if scale is None or array is None:
        return None
    return Image.fromarray(_apply_scale(scale, array)) 
开发者ID:mozilla,项目名称:iris,代码行数:7,代码来源:pattern.py

示例11: _draw_new_page

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def _draw_new_page(self):
        self.page_array = np.ones_like(self.img_arr)
        
        self.tall = set([i for i in self.get_indices() if 
                         self.get_boxes()[i][3] > 3*self.char_mean])
        
#        cv.drawContours(self.page_array, [self.contours[i] for i in 
#                        self.get_indices() if self.get_boxes()[i][2] <= self.tsek_mean + 3*self.tsek_std], 
#                        -1,0, thickness = -1)
#        
#        
#        self.page_array = cv.medianBlur(self.page_array, 19)
#        
#        cv.drawContours(self.page_array, [self.contours[i] for i in 
#                        self.get_indices() if self.get_boxes()[i][2] <= self.tsek_mean + 3*self.tsek_std], 
#                        -1,0, thickness = -1)
        cv.drawContours(self.page_array, [self.contours[i] for i in 
                        range(len(self.contours)) if 
                        self.get_boxes()[i][2] > self.smlmean + 3*self.smstd], 
                        -1,0, thickness = -1)
#        cv.drawContours(self.page_array, [self.contours[i] for i in 
#                        self.get_indices() if self.get_boxes()[i][3] <= 2*self.char_mean], 
#                        -1,0, thickness = -1)
#        cv.erode(self.page_array, None, self.page_array, iterations=2)
#        self.page_array = cv.morphologyEx(self.page_array, cv.MORPH_CLOSE, None,iterations=2)
        import Image
        Image.fromarray(self.page_array*255).show()
#        raw_input()
#        cv.dilate(self.page_array, None, self.page_array, iterations=1) 
开发者ID:zmr,项目名称:namsel,代码行数:31,代码来源:page_elements2.py

示例12: draw_hough_outline

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def draw_hough_outline(self, arr):
        
        arr = invert_bw(arr)
#         import Image
#         Image.fromarray(arr*255).show()
#        h = cv.HoughLinesP(arr, 2, np.pi/4, 5, minLineLength=arr.shape[0]*.10)
        h = cv.HoughLinesP(arr, 2, np.pi/4, 1, minLineLength=arr.shape[0]*.15, maxLineGap=5) #This
#         h = cv.HoughLinesP(arr, 2, np.pi/4, 1, minLineLength=arr.shape[0]*.15, maxLineGap=1)
#        h = cv.HoughLinesP(arr, 2, np.pi/4, 1, minLineLength=arr.shape[0]*.15)
        PI_O4 = np.pi/4
#        if h and h.any():
#        if self._page_type == 'pecha':
#            color = 1
#            thickness = 10
#        else: # Attempt to erase horizontal lines if page_type == book. 
#            # Why? Horizontal lines can break LineCluster if they are broken
#            # e.g. couldn't be filtered out prior to line_breaker.py
#            color = 0
#            thickness = 10
        if h is not None:
            for line in h[0]:
                new = (line[2]-line[0], line[3] - line[1])
                val = (new[0]/np.sqrt(np.dot(new, new)))
                theta = np.arccos(val)
                if theta >= PI_O4: # Vertical line
#                    print line[1] - line[3]
#                     cv.line(arr, (line[0], 0), (line[0], arr.shape[0]), 1, thickness=10)
                    if line[0] < .5*arr.shape[1]:
                        arr[:,:line[0]+12] = 0
                    else:
                        arr[:,line[0]-12:] = 0
                else: # horizontal line
                    if line[2] - line[0] >= .15 * arr.shape[1]:
#                         cv.line(arr, (0, line[1]), (arr.shape[1], line[1]), 1, thickness=50)
                        if line[1] < .5 *arr.shape[0]:
                            arr[:line[1]+17, :] = 0
                        else:
                            arr[line[1]-5:,:] = 0
        

        return ((arr*-1)+1).astype(np.uint8) 
开发者ID:zmr,项目名称:namsel,代码行数:43,代码来源:page_elements2.py

示例13: get_open_windows

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def get_open_windows():
	gtk.main_iteration_do(False)
	screen = wnck.screen_get_default()
	screen.force_update()
	win = screen.get_windows_stacked()
	windows=[]
	for w in win:
			if  'NORMAL' in str(w.get_window_type()):
				if "ducklauncher!!!"==w.get_name():
					pass		
				elif w.is_sticky()!=True and "ducklauncher!!"!=w.get_name():
					window={}	
					window['id']=w.get_xid()
					window['title'] =w.get_name()

					window['app']=w.get_application().get_name()
					
					#print w.get_class_group().get_name()
					ico = Apps.ico_from_app(w.get_application().get_icon_name())
					if ico==None:
						ico = Apps.ico_from_app(w.get_application().get_name())
					if ico==None:
						pix=w.get_icon()
						pix= pix.scale_simple(128,128,gtk.gdk.INTERP_HYPER)
						ico_data=  pix.get_pixels_array()
						img = Image.fromarray(ico_data, 'RGBA')
						home = os.path.expanduser("~")+"/.duck"
						try:
    							os.stat(home)
						except:
    							os.mkdir(home)
						#print window
						img_name=str(window["title"]).replace(" ","").replace(".","").lower()
						img_path="{0}/{1}.png".format(home,img_name)					
						img.save(img_path)
						ico=img_path
					window['icon']=ico


					windows.append(window)
	return windows 
开发者ID:the-duck,项目名称:launcher,代码行数:43,代码来源:Window.py

示例14: get_data

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def get_data(self):
        lmdb = "/datasets/celebHQ/celeb_hq.lmdb"
        ds = LMDBDataPoint(lmdb, shuffle=True)
        ds = ImageDecode(ds, index=0)
        ds.reset_state()
        resample = Image.BICUBIC

        self.remainingImages = ds.size()

        for dp in ds.get_data():
            # read image
            bgr = dp[0]

            # convert to Pil Image and resize

            rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
            pil_im = Image.fromarray(rgb)
            pil_im = pil_im.resize((self.image_size, self.image_size), resample=resample)

            # convert back to opencv fomat
            resized = np.array(pil_im)
            resized = resized[:, :, ::-1].copy()

            # beak for less images
            self.remainingImages -= 1

            print self.remainingImages
            # if (self.remainingImages < 29950):
            #     break
            yield [resized] 
开发者ID:PatWie,项目名称:tensorflow-recipes,代码行数:32,代码来源:convert_to_lmdb.py

示例15: create_thumb

# 需要导入模块: import Image [as 别名]
# 或者: from Image import fromarray [as 别名]
def create_thumb(self,im):
    
        x = 800
        y = 800
        size = (y,x)
        image = Image.fromarray(im)
        
        image.thumbnail(size, Image.ANTIALIAS)
        background = Image.new('RGBA', size, "black")
        background.paste(image, ((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
        
        return np.array(background)[:,:,0:3] 
开发者ID:imatge-upc,项目名称:retrieval-2016-deepvision,代码行数:14,代码来源:vis.py


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