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


Python misc.fromimage函数代码示例

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


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


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