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

Python misc.fromimage函数代码示例

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

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



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

示例1: liner

def liner():
    "提取眼睛行(带眼镜)"
    #import os
    #try: os.mkdir('glassline')
    #except: pass
    import PIL.Image
    glassmodel = np.empty((len(glasslist),(70-25)*(90-0)),np.uint8)
    idx = 0
    for i in glasslist:
        img = PIL.Image.open(s2o(dataset.read(i)))
        img=img.crop((0,25,90,70))
        glassmodel[idx] = misc.fromimage(img).flatten()
        #img.save('glassline\\'+i.split('/')[-1])
        print i
        idx+=1
    print glassmodel.shape
    np.save('glassline.npy',glassmodel)

    nglassmodel = np.empty((len(noglasslist),(70-25)*(90-0)),np.uint8)
    idx = 0
    for i in noglasslist:
        img = PIL.Image.open(s2o(dataset.read(i)))
        img=img.crop((0,25,90,70))
        nglassmodel[idx] = misc.fromimage(img).flatten()
        #img.save('glassline\\'+i.split('/')[-1])
        print i
        idx+=1
    print nglassmodel.shape
    np.save('nglassline.npy',nglassmodel)
开发者ID:wzc11,项目名称:glasses-removal,代码行数:29,代码来源:model1-2.py


示例2: read_captcha

def read_captcha( file ):
    from time import time

    image = Image.open( file )
    image = image.convert( "P" )
    image = image.resize( ( image.size[0] * 3, image.size[1] * 3 ), Image.ANTIALIAS )

    image2 = Image.new( "P", image.size, 255 )

    for x in range( image.size[1] ):
      for y in range( image.size[0] ):
        pix = image.getpixel( ( y, x ) )
        if pix > 15 and pix < 150:
            pass
            image2.putpixel( ( y, x ), 0 )

    image2 = image2.convert( 'RGB' )

    data = misc.fromimage( image2 )
    data_slices = find_paws( 255-data, smooth_radius = 2, threshold = 200 )

    draw = ImageDraw.Draw( image2 )

    letters = []
    bboxes = slice_to_bbox( data_slices )
    for bbox in bboxes:
        xwidth = bbox.x2 - bbox.x1
        ywidth = bbox.y2 - bbox.y1
        if xwidth < 40 and ywidth < 40:
            draw.rectangle( ( bbox.x1 - 1, bbox.y1 - 1, bbox.x2 + 1, bbox.y2 + 1 ), fill='white' )
        elif xwidth > 60 and ywidth > 69:
            letters.append( ( bbox.x1, bbox.y1, bbox.x2, bbox.y2 ) )
            #draw.rectangle( ( bbox.x1 - 1, bbox.y1 - 1, bbox.x2 + 1, bbox.y2 + 1 ), outline='red' )
   
    letters = sorted( letters, key=lambda i: i[0] )
    if len( letters ) == 5: 
        i = 0
        final_result = []
        for letter in letters:
            i += 1
            im = image2.crop( letter )
            image = image.convert( "P" )
            im = im.resize( ( im.size[0], im.size[1] ), Image.ANTIALIAS )
            im = im.filter( ImageFilter.DETAIL )

            dt = misc.fromimage( im )

            filename = 'resources/%s-%d.png' % ( file, i )
            im = misc.toimage( dt )
            im.save( filename )

            tempFile = tempfile.NamedTemporaryFile( delete = False )

            process = subprocess.Popen(['tesseract', filename, tempFile.name, '-psm', '10', 'letters' ], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
            process.communicate()
            final_result.append( open( tempFile.name + '.txt', 'r' ).read() )

        return ''.join( [ l.upper().strip() for l in final_result ] )
开发者ID:jackMort,项目名称:hamster-bot,代码行数:58,代码来源:captcha.py


示例3: _loadImageY

	def _loadImageY(self, path, is_noise):
		im = Image.open(path).convert('YCbCr')

		if is_noise:
			im = misc.fromimage(im).astype('float32')
		else:
			im = misc.fromimage(im.resize((2*im.size[0], 2*im.size[1]), resample=Image.NEAREST)).astype('float32')

		x = np.reshape(np.array(im[:,:,0]), (1, 1, im.shape[0], im.shape[1])) / 255.0

		return im, x
开发者ID:Rompei,项目名称:waifu2x-keras,代码行数:11,代码来源:waifu2x.py


示例4: _loadImageRGB

	def _loadImageRGB(self, path, is_noise):
		im = Image.open(path)

		if is_noise:
			im = misc.fromimage(im).astype('float32')
		else:
			im = misc.fromimage(im.resize((2*im.size[0], 2*im.size[1]), resample=Image.NEAREST)).astype('float32')

		x = np.array([[im[:,:,0], im[:,:,1], im[:,:,2]]])/255.0

		return im, x
开发者ID:Rompei,项目名称:waifu2x-keras,代码行数:11,代码来源:waifu2x.py


示例5: original_color_transform

def original_color_transform(content, generated, mask=None):
    generated = fromimage(toimage(generated, mode='RGB'), mode='YCbCr')  # Convert to YCbCr color space

    if mask is None:
        generated[:, :, 1:] = content[:, :, 1:]  # Generated CbCr = Content CbCr
    else:
        width, height, channels = generated.shape

        for i in range(width):
            for j in range(height):
                if mask[i, j] == 1:
                    generated[i, j, 1:] = content[i, j, 1:]

    generated = fromimage(toimage(generated, mode='YCbCr'), mode='RGB')  # Convert to RGB color space
    return generated
开发者ID:ankushswar1,项目名称:Neural-Style-Transfer,代码行数:15,代码来源:Network.py


示例6: threshold2

def threshold2(frame, threshold):
    '''Returns a list of the pixel indicies of all of the pixels in the image
    whose value is below the given threshold. Requires 'im_array' to be a 2D
    bitmap array of numbers (for our purposes these numbers represent an
    8-bit image and therefore take on values from 0-255.)'''

    points = []

    frame = frame.point(lambda p: p < threshold)

    im_array = fromimage(frame).astype('float')

    try:
        B = argwhere(im_array)
        (ystart, xstart), (ystop, xstop) = B.min(0), B.max(0) + 1 
        cropped_array = im_array[ystart:ystop, xstart:xstop]
            
        p = array(nonzero(cropped_array)).swapaxes(0,1)

        for (y,x) in p:
            points.append((xstart+x,ystart+y))
    except ValueError:
        pass
        
    return points
开发者ID:JamieWoodbury,项目名称:Brownian-Spot-Tracker,代码行数:25,代码来源:MultipleBeadBrownian.py


示例7: fonts_template

def fonts_template(fn=None,ttf=None):
    ttf = ttf or 'c:/windows/fonts/ariali.ttf'
    fn = fn or 'd:/temp/fonts.arrs'

    m = dict()
    font = ImageFont.truetype(ttf, 18)
    for e in  '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ':
        arr = font.getmask(e, mode='L')
        arr = Image.Image()._new(arr)
        arr = misc.fromimage(arr)
        h,w = arr.shape
        
        print '%s:<%s,%s> %s'%(e, h,w, arr[0,0])
        if w<10:
            tmp = numpy.ndarray( (h,10), dtype=arr.dtype )
            tmp.fill(0)
            i = (10-w)/2
            tmp[:,i:i+w] = arr
            arr = tmp
        #arr = arr[3:18,:]
        arr = arr[2:19,:]
        arr = im_norm(arr)
        rs = ndimage.correlate(arr,arr, mode='constant', cval=0.0)
        limit = numpy.max(rs)
        m[e] = (limit,arr)

    cPickle.dump(m, open(fn,'wb'))
开发者ID:Big-Data,项目名称:ec2,代码行数:27,代码来源:image.py


示例8: prepare_image_for_correlation

def prepare_image_for_correlation(im):
    letterArray = fromimage(im.convert('RGB'))
    # Black and white
    letterArray = scipy.inner(letterArray, [299, 587, 114]) / 1000.0
    # Normalize
    letterArray = (letterArray - letterArray.mean()) / letterArray.std()
    return letterArray
开发者ID:nachogoro,项目名称:wordcrack-herminia,代码行数:7,代码来源:boardgenerator.py


示例9: im2ar

def im2ar( image_ ):
    """Convert PIL Image to Numpy array."""
    if image_.mode in ('L', 'I', 'F'):
        # Warning: only works with PIL.Image.Image whose mode is 'L', 'I' or 'F'
        #          => error if mode == 'I;16' for instance
        array_ = fromimage( image_ )
        return array_
开发者ID:tjlane,项目名称:electrolysis,代码行数:7,代码来源:gatan.py


示例10: snapshot

def snapshot(image=None, size=None):
    r"""Acquires an image as a numpy array.

        If the image argument is None, a screenshot is grabbed. otherwise, the
        given image is converted to a 2- or 3-dimensional numpy array, depending
        on whether it's colour or grayscale.
    """
    if isinstance(image, ndarray):
        return image

    if image == None:
        try:
            from ImageGrab import grab

            image = grab()
            image.save("screenshot.png")
        except:
            from os import system

            name = "screenshot.png"
            command = "scrot %s" % name
            system(command)
            image = loadimage(name)
    elif isinstance(image, basestring):
        image = loadimage(image)
        image.load()

    if size != None:
        (m, n) = size
        image = image.resize((n, m), ANTIALIAS)

    return dstack(fromimage(channel) for channel in image.split())
开发者ID:xperroni,项目名称:Skeye,代码行数:32,代码来源:__init__.py


示例11: tst_fromimage

def tst_fromimage(filename, irange):
    fp = open(filename, "rb")
    img = misc.fromimage(PIL.Image.open(fp))
    fp.close()
    imin,imax = irange
    assert_(img.min() >= imin)
    assert_(img.max() <= imax)
开发者ID:Acebulf,项目名称:scipy,代码行数:7,代码来源:test_pilutil.py


示例12: resize

def resize(data, dims):
    """ Wrapper to resize an image """
    import scipy.misc as smp
    import Image
    tmp = smp.fromimage(smp.toimage(data, mode='F'))
    tmp = tmp.resize(dims, Image.ANTIALIAS)
    return tmp
开发者ID:dhparks,项目名称:als_speckle,代码行数:7,代码来源:symmetries.py


示例13: score

def score(filename):
    """
    Score individual image files for the genetic algorithm.
    The idea is to derive predictive factors for the langmuir performance
    (i.e., max power) based on the connectivity, phase fractions, domain sizes,
    etc. The scoring function should be based on multivariate fits from a database
    of existing simulations. To ensure good results, use robust regression techniques
    and cross-validate the best-fit.

    :param filename: image file name
    :type filename: str

    :return score (ideally as an estimated maximum power in W/(m^2))
    :rtype float
    """
    # this works around a weird bug in scipy.misc.imread with 1-bit images
    # open them with PIL as 8-bit greyscale "L" and then convert to ndimage
    pil_img = Image.open(filename)
    image = misc.fromimage(pil_img.convert("L"))

    width, height = image.shape
    if width != 256 or height != 256:
        print "Size Error: ", filename

    #    isize = analyze.interface_size(image)
    ads1, std1 = analyze.average_domain_size(image)

    # we now need to invert the image to get the second domain size
    inverted = (image < image.mean())
    ads2, std2 = analyze.average_domain_size(inverted)

    #overall average domain size
    ads = (ads1 + ads2) / 2.0

    # transfer distances
    # connectivity
    td1, connect1, td2, connect2 = analyze.transfer_distance(image)

    spots = np.logical_xor(image,
        ndimage.binary_erosion(image, structure=np.ones((2,2))))
    erosion = np.count_nonzero(spots)

    spots = np.logical_xor(image,
        ndimage.binary_dilation(image, structure=np.ones((2,2))))
    dilation = np.count_nonzero(spots)

    # fraction of phase one
    nonzero = np.count_nonzero(image)
    fraction = float(nonzero) / float(image.size)
    # scores zero at 0, 1 and maximum at 0.5
    ps = fraction*(1.0-fraction)

    # from simulations with multivariate nonlinear regression
    return (-1.98566e8) + (-1650.14)/ads + (-680.92)*math.pow(ads,0.25) + \
           1.56236e7*math.tanh(14.5*(connect1 + 0.4)) + 1.82945e8*math.tanh(14.5*(connect2 + 0.4)) \
           + 2231.32*connect1*connect2 \
           + (-4.72813)*td1 + (-4.86025)*td2 \
           + 3.79109e7*ps**8 \
           + 0.0540293*dilation + 0.0700451*erosion
开发者ID:JoshuaSBrown,项目名称:langmuir,代码行数:59,代码来源:ga.py


示例14: tst_fromimage

def tst_fromimage(filename, irange, shape):
    fp = open(filename, "rb")
    img = misc.fromimage(PIL.Image.open(fp))
    fp.close()
    imin, imax = irange
    assert_equal(img.min(), imin)
    assert_equal(img.max(), imax)
    assert_equal(img.shape, shape)
开发者ID:Linkid,项目名称:scipy,代码行数:8,代码来源:test_pilutil.py


示例15: convert_profile_numpy_transform

def convert_profile_numpy_transform(image_np, transform):
    if (not have_pilutil) or (not have_cms):
        return image_np

    in_image_pil = toimage(image_np)
    convert_profile_pil_transform(in_image_pil, transform, inPlace=True)
    image_out = fromimage(in_image_pil)
    return image_out
开发者ID:Cadair,项目名称:ginga,代码行数:8,代码来源:io_rgb.py


示例16: img2code

 def img2code(self, ss, alpha=0.4):
     im = Image.open(StringIO(ss))
     im = im.convert('L')
     arr = misc.fromimage(im)
     roi,res = self.decode(arr)
     if len(roi)!=4: return None
     
     return ''.join( e[0] for e in roi )
开发者ID:Big-Data,项目名称:ec2,代码行数:8,代码来源:captcha.py


示例17: setUp

    def setUp(self):
        image_name = '../media/kewell1.jpg'
        
        self.reference_image_uint8 = fromimage(Image.open(image_name))

        self.fv = vivid.ImageSource(imlist=[image_name])
        self.cs = vivid.ConvertedSource(self.fv, target_type = vivid.cv.CV_32FC3)
        self.gs = vivid.GreySource(self.cs)
开发者ID:mertdikmen,项目名称:ViVid,代码行数:8,代码来源:test_reading.py


示例18: _read_tiff

def _read_tiff(filename):
    """
    Reads a TIFF and returns the image as a NumPy array (double
    precision).

    Uses tifffile.py (by Christoph Gohlke) to detect size and depth of
    image.

    Notes
    -----
    TOFIX: The library doesn't convert our Photon Focus 12-bit tiffs
    correctly, so we call a special decoder for all 12-bit tiffs
    (should fix this in the future so that all tiffs can be opened by
    tifffile)
    """
    tif = TIFFfile(filename)

    might_be_color = True
    if len(tif.pages) > 1:
        try:
            arr = tif.asarray().transpose()
            might_be_color = False
        except Exception:
            print('failed to read multipage tiff, attempting to read a single page')

    # assuming a one-page tiff here...
    depth = tif[0].tags.bits_per_sample.value
    width = tif[0].tags.image_width.value
    height = tif[0].tags.image_length.value
    # I think the "samples per pixel" corresponds to the number of
    # channels; check on a 24-bit tiff to make sure
    channels = tif[0].tags.samples_per_pixel.value

    if depth == 8:
        tif.close()
        # use PIL to open it
        # TOFIX: see if tifffile will open 8-bit tiffs from our
        # cameras correctly
        im = PILImage.open(filename)
        arr = fromimage(im).astype('d')
    elif depth == 12:
        tif.close()
        if width == height:
            arr = _read_tiff_12bit(filename, height)
        else:
            raise NotImplementedError("Read non-square 12 bit tiff")
    else:
        # use the tifffile representation
        arr = tif.asarray().astype('d')
        tif.close()

    try:
        # 270 is the image description tag
        description = PILImage.open(filename).tag[270]
    except KeyError:
        description = "{}"

    return arr, might_be_color, description
开发者ID:RebeccaWPerry,项目名称:holography-gpu,代码行数:58,代码来源:image_file_io.py


示例19: load_image

def load_image(inf, spacing=None, medium_index=None, illum_wavelen=None, illum_polarization=None, normals=None, noise_sd=None, channel=None, name=None):
    """
    Load data or results

    Parameters
    ----------
    inf : single or list of basestring or files
        File to load.  If the file is a yaml file, all other arguments are
        ignored.  If inf is a list of image files or filenames they are all
        loaded as a a timeseries hologram
    channel : int or tuple of ints (optional)
        number(s) of channel to load for a color image (in general 0=red,
        1=green, 2=blue)

    Returns
    -------
    obj : The object loaded, :class:`holopy.core.marray.Image`, or as loaded from yaml

    """
    if name is None:
        name = os.path.splitext(os.path.split(inf)[-1])[0]

    with open(inf,'rb') as pi:
        arr = fromimage(pilimage.open(pi)).astype('d')
        if hasattr(pi, 'tag') and isinstance(yaml.load(pi.tag[270][0]), dict):
            warnings.warn("Metadata detected but ignored. Use hp.load to read it")

    extra_dims = None
    if channel is None:
        if arr.ndim > 2:
            raise BadImage('Not a greyscale image. You must specify which channel(s) to use')
    elif arr.ndim == 2:
            if not channel == 'all':
                warnings.warn("Not a color image (channel number ignored)")
            pass
    else:
        # color image with specified channel(s)
        if channel == 'all':
            channel = range(arr.shape[2])
        channel = ensure_array(channel)
        if channel.max() >= arr.shape[2]:
            raise LoadError(filename,
                "The image doesn't have a channel number {0}".format(channel.max()))
        else:
            arr = arr[:, :, channel].squeeze()

            if len(channel) > 1:
                # multiple channels. increase output dimensionality
                if channel.max() <=2:
                    channel = [['red','green','blue'][c] for c in channel]
                extra_dims = {illumination: channel}
                if not is_none(illum_wavelen) and not isinstance(illum_wavelen,dict) and len(ensure_array(illum_wavelen)) == len(channel):
                    illum_wavelen = xr.DataArray(ensure_array(illum_wavelen), dims=illumination, coords=extra_dims)
                if not isinstance(illum_polarization, dict) and np.array(illum_polarization).ndim == 2:
                    pol_index = xr.DataArray(channel, dims=illumination, name=illumination)
                    illum_polarization=xr.concat([to_vector(pol) for pol in illum_polarization], pol_index)

    return data_grid(arr, spacing, medium_index, illum_wavelen, illum_polarization, normals, noise_sd, name, extra_dims)
开发者ID:barkls,项目名称:holopy,代码行数:58,代码来源:io.py


示例20: load_drawn_labels

def load_drawn_labels(name):
    fn = pyhrf.get_data_file_name('simu_labels_%s.png' %name)
    if not op.exists(fn):
        raise Exception('Unknown label map %s (%s)' %(name,fn))

    from scipy.misc import fromimage
    from PIL import Image
    labels = fromimage(Image.open(fn))
    return labels[np.newaxis,:,:]
开发者ID:pmesejo,项目名称:pyhrf,代码行数:9,代码来源:scenarios.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python misc.imread函数代码示例发布时间:2022-05-27
下一篇:
Python misc.factorial函数代码示例发布时间: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